Commit 5b76913c by liuhui

Initial commit

parents
Showing with 17698 additions and 0 deletions
.DS_Store
######################################################################
# Build Tools
.gradle
/build/
!gradle/wrapper/gradle-wrapper.jar
target/
!.mvn/wrapper/maven-wrapper.jar
######################################################################
# IDE
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
*/.externalToolBuilders/
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
nbproject/private/
build/*
nbbuild/
dist/
nbdist/
.nb-gradle/
######################################################################
# Others
*.log
*.xml.versionsBackup
!*/build/*.java
!*/build/*.html
!*/build/*.xml
<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.sinobase</groupId>
<artifactId>sinobase</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<groupId>com.sinobase</groupId>
<artifactId>sinobase-base</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>sinobase-common</name>
<description>remote call interface</description>
<dependencies>
<!-- SpringBoot 核心包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- SpringBoot WEB依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- sinobase-datasource -->
<dependency>
<groupId>com.sinobase</groupId>
<artifactId>sinobase-datasource</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<!--常用工具类 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<!-- http-client -->
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<!-- 阿里JSON解析器 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<!-- SpringBoot集成mybatis Plus框架 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.6</version>
</dependency>
<!-- json处理工具 -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.3</version>
<classifier>jdk15</classifier>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<!-- shiro-spring -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
</dependency>
<!-- swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<srource>1.8</srource>
<target>1.8</target>
<encoding>UTF-8</encoding>
<showWarning>true</showWarning>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.sinobase.common.constant;
import java.util.HashMap;
import java.util.Map;
/**
* 通用数据库映射Map数据
*
* @author sinobase
*/
public class CommonMap
{
/** 状态编码转换 */
public static Map<String, String> javaTypeMap = new HashMap<String, String>();
static
{
initJavaTypeMap();
}
/**
* 返回状态映射
*/
public static void initJavaTypeMap()
{
javaTypeMap.put("tinyint", "Integer");
javaTypeMap.put("smallint", "Integer");
javaTypeMap.put("mediumint", "Integer");
javaTypeMap.put("int", "Integer");
javaTypeMap.put("integer", "integer");
javaTypeMap.put("bigint", "Long");
javaTypeMap.put("float", "Float");
javaTypeMap.put("double", "Double");
javaTypeMap.put("decimal", "BigDecimal");
javaTypeMap.put("bit", "Boolean");
javaTypeMap.put("char", "String");
javaTypeMap.put("varchar", "String");
javaTypeMap.put("tinytext", "String");
javaTypeMap.put("text", "String");
javaTypeMap.put("mediumtext", "String");
javaTypeMap.put("longtext", "String");
javaTypeMap.put("time", "Date");
javaTypeMap.put("date", "Date");
javaTypeMap.put("datetime", "Date");
javaTypeMap.put("timestamp", "Date");
}
}
package com.sinobase.common.constant;
/**
* 通用常量信息
*
* @author sinobase
*/
public class Constants
{
/**
* UTF-8 字符集
*/
public static final String UTF8 = "UTF-8";
/**
* 通用成功标识
*/
public static final String SUCCESS = "0";
/**
* 通用失败标识
*/
public static final String FAIL = "1";
/**
* 登录成功
*/
public static final String LOGIN_SUCCESS = "Success";
/**
* 注销
*/
public static final String LOGOUT = "Logout";
/**
* 登录失败
*/
public static final String LOGIN_FAIL = "Error";
/**
* 自动去除表前缀
*/
public static String AUTO_REOMVE_PRE = "true";
/**
* 当前记录起始索引
*/
public static String PAGE_NUM = "pageNum";
/**
* 每页显示记录数
*/
public static String PAGE_SIZE = "pageSize";
/**
* 排序列
*/
public static String ORDER_BY_COLUMN = "orderByColumn";
/**
* 排序的方向 "desc" 或者 "asc".
*/
public static String IS_ASC = "isAsc";
/**
* 请假单状态标识 草稿
*/
public static String START_FLAG = "5";
/**
* 请假单状态标识 审核中
*/
public static String SUB_FLAG = "1";
/**
* 请假单状态标识 办结
*/
public static String END_FLAG = "4";
/**
*请假单状态标识 归档
*/
public static String DOSSIER_FLAG = "3";
/**
*请假单状态标识 撤办
*/
public static String REMOVE_FLAG = "0";
/**
*请假单状态标识 审批通过
*/
public static String APPROVAL_FLAG = "6";
/**
*请假单状态标识 审批不通过
*/
public static String NOAPPROVAL_FLAG = "7";
/**
* 国投智能外部单位
*
*/
public static String COMPANY_EXTEND = "231560";
}
package com.sinobase.common.constant;
/**
* 权限通用常量
*
* @author sinobase
*/
public class PermissionConstants
{
/** 新增权限 */
public static final String ADD_PERMISSION = "add";
/** 修改权限 */
public static final String EDIT_PERMISSION = "edit";
/** 删除权限 */
public static final String REMOVE_PERMISSION = "remove";
/** 导出权限 */
public static final String EXPORT_PERMISSION = "export";
/** 显示权限 */
public static final String VIEW_PERMISSION = "view";
/** 查询权限 */
public static final String LIST_PERMISSION = "list";
}
package com.sinobase.common.constant;
/**
* 任务调度通用常量
*
* @author sinobase
*/
public interface ScheduleConstants
{
public static final String TASK_CLASS_NAME = "__TASK_CLASS_NAME__";
public static final String TASK_PROPERTIES = "__TASK_PROPERTIES__";
/** 默认 */
public static final String MISFIRE_DEFAULT = "0";
/** 立即触发执行 */
public static final String MISFIRE_IGNORE_MISFIRES = "1";
/** 触发一次执行 */
public static final String MISFIRE_FIRE_AND_PROCEED = "2";
/** 不触发立即执行 */
public static final String MISFIRE_DO_NOTHING = "3";
public enum Status
{
/**
* 正常
*/
NORMAL("0"),
/**
* 暂停
*/
PAUSE("1");
private String value;
private Status(String value)
{
this.value = value;
}
public String getValue()
{
return value;
}
}
}
package com.sinobase.common.constant;
/**
* Shiro通用常量
*
* @author sinobase
*/
public interface ShiroConstants
{
/**
* 当前登录的用户
*/
public static final String CURRENT_USER = "currentUser";
/**
* 用户名
*/
public static final String CURRENT_USERNAME = "username";
/**
* 消息key
*/
public static String MESSAGE = "message";
/**
* 错误key
*/
public static String ERROR = "errorMsg";
/**
* 编码格式
*/
public static String ENCODING = "UTF-8";
/**
* 当前在线会话
*/
public String ONLINE_SESSION = "online_session";
/**
* 验证码key
*/
public static final String CURRENT_CAPTCHA = "captcha";
/**
* 验证码开关
*/
public static final String CURRENT_ENABLED = "captchaEnabled";
/**
* 验证码开关
*/
public static final String CURRENT_TYPE = "captchaType";
/**
* 验证码
*/
public static final String CURRENT_VALIDATECODE = "validateCode";
/**
* 验证码错误
*/
public static final String CAPTCHA_ERROR = "captchaError";
}
package com.sinobase.common.constant;
public class SinoDept {
/**
* 办公厅 四位id
*/
public static final String BAN_GONG_TING = "00020034";
/** 保障中心 */
public static final String DEPT_SDIC_BZZX = "00020060";
}
package com.sinobase.common.constant;
/**
* 用户常量信息
*
* @author sinobase
*/
public class UserConstants
{
/** 正常状态 */
public static final String NORMAL = "0";
/** 异常状态 */
public static final String EXCEPTION = "1";
/** 用户封禁状态 */
public static final String USER_BLOCKED = "1";
/** 角色封禁状态 */
public static final String ROLE_BLOCKED = "0";
/** 部门正常状态 */
public static final String DEPT_NORMAL = "1";
/**
* 用户名长度限制
*/
public static final int USERNAME_MIN_LENGTH = 2;
public static final int USERNAME_MAX_LENGTH = 20;
/** 登录名称是否唯一的返回结果码 */
public final static String USER_NAME_UNIQUE = "0";
public final static String USER_NAME_NOT_UNIQUE = "1";
/** 手机号码是否唯一的返回结果 */
public final static String USER_PHONE_UNIQUE = "0";
public final static String USER_PHONE_NOT_UNIQUE = "1";
/** e-mail 是否唯一的返回结果 */
public final static String USER_EMAIL_UNIQUE = "0";
public final static String USER_EMAIL_NOT_UNIQUE = "1";
/** 部门名称是否唯一的返回结果码 */
public final static String DEPT_NAME_UNIQUE = "0";
public final static String DEPT_NAME_NOT_UNIQUE = "1";
/** 角色名称是否唯一的返回结果码 */
public final static String ROLE_NAME_UNIQUE = "0";
public final static String ROLE_NAME_NOT_UNIQUE = "1";
/** 岗位名称是否唯一的返回结果码 */
public final static String POST_NAME_UNIQUE = "0";
public final static String POST_NAME_NOT_UNIQUE = "1";
/** 角色权限是否唯一的返回结果码 */
public final static String ROLE_KEY_UNIQUE = "0";
public final static String ROLE_KEY_NOT_UNIQUE = "1";
/** 岗位编码是否唯一的返回结果码 */
public final static String POST_CODE_UNIQUE = "0";
public final static String POST_CODE_NOT_UNIQUE = "1";
/** 菜单名称是否唯一的返回结果码 */
public final static String MENU_NAME_UNIQUE = "0";
public final static String MENU_NAME_NOT_UNIQUE = "1";
/** 字典类型是否唯一的返回结果码 */
public final static String DICT_TYPE_UNIQUE = "0";
public final static String DICT_TYPE_NOT_UNIQUE = "1";
/** 参数键名是否唯一的返回结果码 */
public final static String CONFIG_KEY_UNIQUE = "0";
public final static String CONFIG_KEY_NOT_UNIQUE = "1";
/**
* 密码长度限制
*/
public static final int PASSWORD_MIN_LENGTH = 5;
public static final int PASSWORD_MAX_LENGTH = 20;
/**
* 手机号码格式限制
*/
public static final String MOBILE_PHONE_NUMBER_PATTERN = "^0{0,1}(13[0-9]|15[0-9]|14[0-9]|18[0-9])[0-9]{8}$";
/**
* 邮箱格式限制
*/
public static final String EMAIL_PATTERN = "^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.?";
}
package com.sinobase.common.exception;
/**
* 业务异常
*
* @author sinobase
*/
public class BusinessException extends RuntimeException
{
private static final long serialVersionUID = 1L;
protected final String message;
public BusinessException(String message)
{
this.message = message;
}
@Override
public String getMessage()
{
return message;
}
}
package com.sinobase.common.exception;
/**
* 演示模式异常
*
* @author sinobase
*/
public class DemoModeException extends RuntimeException
{
private static final long serialVersionUID = 1L;
public DemoModeException()
{
}
}
package com.sinobase.common.exception.base;
import org.springframework.util.StringUtils;
import com.sinobase.common.utils.MessageUtils;
/**
* 基础异常
*
* @author sinobase
*/
public class BaseException extends RuntimeException
{
private static final long serialVersionUID = 1L;
/**
* 所属模块
*/
private String module;
/**
* 错误码
*/
private String code;
/**
* 错误码对应的参数
*/
private Object[] args;
/**
* 错误消息
*/
private String defaultMessage;
public BaseException(String module, String code, Object[] args, String defaultMessage)
{
this.module = module;
this.code = code;
this.args = args;
this.defaultMessage = defaultMessage;
}
public BaseException(String module, String code, Object[] args)
{
this(module, code, args, null);
}
public BaseException(String module, String defaultMessage)
{
this(module, null, null, defaultMessage);
}
public BaseException(String code, Object[] args)
{
this(null, code, args, null);
}
public BaseException(String defaultMessage)
{
this(null, null, null, defaultMessage);
}
@Override
public String getMessage()
{
String message = null;
if (!StringUtils.isEmpty(code))
{
message = MessageUtils.message(code, args);
}
if (message == null)
{
message = defaultMessage;
}
return message;
}
public String getModule()
{
return module;
}
public String getCode()
{
return code;
}
public Object[] getArgs()
{
return args;
}
public String getDefaultMessage()
{
return defaultMessage;
}
@Override
public String toString()
{
return this.getClass() + "{" + "module='" + module + '\'' + ", message='" + getMessage() + '\'' + '}';
}
}
package com.sinobase.common.support;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import com.sinobase.common.utils.StringUtils;
/**
* 字符集工具类
*
* @author sinobase
*
*/
public class CharsetKit
{
/** ISO-8859-1 */
public static final String ISO_8859_1 = "ISO-8859-1";
/** UTF-8 */
public static final String UTF_8 = "UTF-8";
/** GBK */
public static final String GBK = "GBK";
/** ISO-8859-1 */
public static final Charset CHARSET_ISO_8859_1 = Charset.forName(ISO_8859_1);
/** UTF-8 */
public static final Charset CHARSET_UTF_8 = Charset.forName(UTF_8);
/** GBK */
public static final Charset CHARSET_GBK = Charset.forName(GBK);
/**
* 转换为Charset对象
*
* @param charset 字符集,为空则返回默认字符集
* @return Charset
*/
public static Charset charset(String charset)
{
return StringUtils.isEmpty(charset) ? Charset.defaultCharset() : Charset.forName(charset);
}
/**
* 转换字符串的字符集编码
*
* @param source 字符串
* @param srcCharset 源字符集,默认ISO-8859-1
* @param destCharset 目标字符集,默认UTF-8
* @return 转换后的字符集
*/
public static String convert(String source, String srcCharset, String destCharset)
{
return convert(source, Charset.forName(srcCharset), Charset.forName(destCharset));
}
/**
* 转换字符串的字符集编码
*
* @param source 字符串
* @param srcCharset 源字符集,默认ISO-8859-1
* @param destCharset 目标字符集,默认UTF-8
* @return 转换后的字符集
*/
public static String convert(String source, Charset srcCharset, Charset destCharset)
{
if (null == srcCharset)
{
srcCharset = StandardCharsets.ISO_8859_1;
}
if (null == destCharset)
{
srcCharset = StandardCharsets.UTF_8;
}
if (StringUtils.isEmpty(source) || srcCharset.equals(destCharset))
{
return source;
}
return new String(source.getBytes(srcCharset), destCharset);
}
/**
* @return 系统字符集编码
*/
public static String systemCharset()
{
return Charset.defaultCharset().name();
}
}
package com.sinobase.common.support;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.text.NumberFormat;
import java.util.Set;
import com.sinobase.common.utils.StringUtils;
/**
* 类型转换器
*
* @author sinobase
*/
public class Convert {
/**
* 转换为字符串<br>
* 如果给定的值为null,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public static String toStr(Object value, String defaultValue) {
if (null == value) {
return defaultValue;
}
if (value instanceof String) {
return (String) value;
}
return value.toString();
}
/**
* 转换为字符串<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static String toStr(Object value) {
return toStr(value, null);
}
/**
* 转换为字符<br>
* 如果给定的值为null,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public static Character toChar(Object value, Character defaultValue) {
if (null == value) {
return defaultValue;
}
if (value instanceof Character) {
return (Character) value;
}
final String valueStr = toStr(value, null);
return StringUtils.isEmpty(valueStr) ? defaultValue : valueStr.charAt(0);
}
/**
* 转换为字符<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static Character toChar(Object value) {
return toChar(value, null);
}
/**
* 转换为byte<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public static Byte toByte(Object value, Byte defaultValue) {
if (value == null) {
return defaultValue;
}
if (value instanceof Byte) {
return (Byte) value;
}
if (value instanceof Number) {
return ((Number) value).byteValue();
}
final String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr)) {
return defaultValue;
}
try {
return Byte.parseByte(valueStr);
} catch (Exception e) {
return defaultValue;
}
}
/**
* 转换为byte<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static Byte toByte(Object value) {
return toByte(value, null);
}
/**
* 转换为Short<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public static Short toShort(Object value, Short defaultValue) {
if (value == null) {
return defaultValue;
}
if (value instanceof Short) {
return (Short) value;
}
if (value instanceof Number) {
return ((Number) value).shortValue();
}
final String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr)) {
return defaultValue;
}
try {
return Short.parseShort(valueStr.trim());
} catch (Exception e) {
return defaultValue;
}
}
/**
* 转换为Short<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static Short toShort(Object value) {
return toShort(value, null);
}
/**
* 转换为Number<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public static Number toNumber(Object value, Number defaultValue) {
if (value == null) {
return defaultValue;
}
if (value instanceof Number) {
return (Number) value;
}
final String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr)) {
return defaultValue;
}
try {
return NumberFormat.getInstance().parse(valueStr);
} catch (Exception e) {
return defaultValue;
}
}
/**
* 转换为Number<br>
* 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static Number toNumber(Object value) {
return toNumber(value, null);
}
/**
* 转换为int<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public static Integer toInt(Object value, Integer defaultValue) {
if (value == null) {
return defaultValue;
}
if (value instanceof Integer) {
return (Integer) value;
}
if (value instanceof Number) {
return ((Number) value).intValue();
}
final String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr)) {
return defaultValue;
}
try {
return Integer.parseInt(valueStr.trim());
} catch (Exception e) {
return defaultValue;
}
}
/**
* 转换为int<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>0</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static Integer toInt(Object value) {
return toInt(value, 0);
}
/**
* 转换为Integer数组<br>
*
* @param str 被转换的值
* @return 结果
*/
public static Integer[] toIntArray(String str) {
return toIntArray(",", str);
}
/**
* 转换为Long数组<br>
*
* @param str 被转换的值
* @return 结果
*/
public static Long[] toLongArray(String str) {
return toLongArray(",", str);
}
/**
* 转换为Integer数组<br>
*
* @param split 分隔符
* @param split 被转换的值
* @return 结果
*/
public static Integer[] toIntArray(String split, String str) {
if (StringUtils.isEmpty(str)) {
return new Integer[] {};
}
String[] arr = str.split(split);
final Integer[] ints = new Integer[arr.length];
for (int i = 0; i < arr.length; i++) {
final Integer v = toInt(arr[i], 0);
ints[i] = v;
}
return ints;
}
/**
* 转换为Long数组<br>
*
* @param split 分隔符
* @param str 被转换的值
* @return 结果
*/
public static Long[] toLongArray(String split, String str) {
if (StringUtils.isEmpty(str)) {
return new Long[] {};
}
String[] arr = str.split(split);
final Long[] longs = new Long[arr.length];
for (int i = 0; i < arr.length; i++) {
final Long v = toLong(arr[i], null);
longs[i] = v;
}
return longs;
}
/**
* 转换为String数组<br>
*
* @param str 被转换的值
* @return 结果
*/
public static String[] toStrArray(String str) {
return toStrArray(",", str);
}
/**
* 转换为String数组<br>
*
* @param split 分隔符
* @param split 被转换的值
* @return 结果
*/
public static String[] toStrArray(String split, String str) {
return str.split(split);
}
/**
* 转换为long<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public static Long toLong(Object value, Long defaultValue) {
if (value == null) {
return defaultValue;
}
if (value instanceof Long) {
return (Long) value;
}
if (value instanceof Number) {
return ((Number) value).longValue();
}
final String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr)) {
return defaultValue;
}
try {
// 支持科学计数法
return new BigDecimal(valueStr.trim()).longValue();
} catch (Exception e) {
return defaultValue;
}
}
/**
* 转换为long<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static Long toLong(Object value) {
return toLong(value, null);
}
/**
* 转换为double<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public static Double toDouble(Object value, Double defaultValue) {
if (value == null) {
return defaultValue;
}
if (value instanceof Double) {
return (Double) value;
}
if (value instanceof Number) {
return ((Number) value).doubleValue();
}
final String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr)) {
return defaultValue;
}
try {
// 支持科学计数法
return new BigDecimal(valueStr.trim()).doubleValue();
} catch (Exception e) {
return defaultValue;
}
}
/**
* 转换为double<br>
* 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static Double toDouble(Object value) {
return toDouble(value, null);
}
/**
* 转换为Float<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public static Float toFloat(Object value, Float defaultValue) {
if (value == null) {
return defaultValue;
}
if (value instanceof Float) {
return (Float) value;
}
if (value instanceof Number) {
return ((Number) value).floatValue();
}
final String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr)) {
return defaultValue;
}
try {
return Float.parseFloat(valueStr.trim());
} catch (Exception e) {
return defaultValue;
}
}
/**
* 转换为Float<br>
* 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static Float toFloat(Object value) {
return toFloat(value, null);
}
/**
* 转换为boolean<br>
* String支持的值为:true、false、yes、ok、no,1,0 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public static Boolean toBool(Object value, Boolean defaultValue) {
if (value == null) {
return defaultValue;
}
if (value instanceof Boolean) {
return (Boolean) value;
}
String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr)) {
return defaultValue;
}
valueStr = valueStr.trim().toLowerCase();
switch (valueStr) {
case "true":
return true;
case "false":
return false;
case "yes":
return true;
case "ok":
return true;
case "no":
return false;
case "1":
return true;
case "0":
return false;
default:
return defaultValue;
}
}
/**
* 转换为boolean<br>
* 如果给定的值为空,或者转换失败,返回默认值<code>false</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static Boolean toBool(Object value) {
return toBool(value, false);
}
/**
* 转换为Enum对象<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
*
* @param clazz Enum的Class
* @param value 值
* @param defaultValue 默认值
* @return Enum
*/
public static <E extends Enum<E>> E toEnum(Class<E> clazz, Object value, E defaultValue) {
if (value == null) {
return defaultValue;
}
if (clazz.isAssignableFrom(value.getClass())) {
@SuppressWarnings("unchecked") E myE = (E) value;
return myE;
}
final String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr)) {
return defaultValue;
}
try {
return Enum.valueOf(clazz, valueStr);
} catch (Exception e) {
return defaultValue;
}
}
/**
* 转换为Enum对象<br>
* 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
*
* @param clazz Enum的Class
* @param value 值
* @return Enum
*/
public static <E extends Enum<E>> E toEnum(Class<E> clazz, Object value) {
return toEnum(clazz, value, null);
}
/**
* 转换为BigInteger<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public static BigInteger toBigInteger(Object value, BigInteger defaultValue) {
if (value == null) {
return defaultValue;
}
if (value instanceof BigInteger) {
return (BigInteger) value;
}
if (value instanceof Long) {
return BigInteger.valueOf((Long) value);
}
final String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr)) {
return defaultValue;
}
try {
return new BigInteger(valueStr);
} catch (Exception e) {
return defaultValue;
}
}
/**
* 转换为BigInteger<br>
* 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static BigInteger toBigInteger(Object value) {
return toBigInteger(value, null);
}
/**
* 转换为BigDecimal<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public static BigDecimal toBigDecimal(Object value, BigDecimal defaultValue) {
if (value == null) {
return defaultValue;
}
if (value instanceof BigDecimal) {
return (BigDecimal) value;
}
if (value instanceof Long) {
return new BigDecimal((Long) value);
}
if (value instanceof Double) {
return new BigDecimal((Double) value);
}
if (value instanceof Integer) {
return new BigDecimal((Integer) value);
}
final String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr)) {
return defaultValue;
}
try {
return new BigDecimal(valueStr);
} catch (Exception e) {
return defaultValue;
}
}
/**
* 转换为BigDecimal<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static BigDecimal toBigDecimal(Object value) {
return toBigDecimal(value, null);
}
/**
* 将对象转为字符串<br>
* 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法
*
* @param obj 对象
* @return 字符串
*/
public static String utf8Str(Object obj) {
return str(obj, CharsetKit.CHARSET_UTF_8);
}
/**
* 将对象转为字符串<br>
* 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法
*
* @param obj 对象
* @param charsetName 字符集
* @return 字符串
*/
public static String str(Object obj, String charsetName) {
return str(obj, Charset.forName(charsetName));
}
/**
* 将对象转为字符串<br>
* 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法
*
* @param obj 对象
* @param charset 字符集
* @return 字符串
*/
public static String str(Object obj, Charset charset) {
if (null == obj) {
return null;
}
if (obj instanceof String) {
return (String) obj;
} else if (obj instanceof byte[] || obj instanceof Byte[]) {
return str((Byte[]) obj, charset);
} else if (obj instanceof ByteBuffer) {
return str((ByteBuffer) obj, charset);
}
return obj.toString();
}
/**
* 将byte数组转为字符串
*
* @param bytes byte数组
* @param charset 字符集
* @return 字符串
*/
public static String str(byte[] bytes, String charset) {
return str(bytes, StringUtils.isEmpty(charset) ? Charset.defaultCharset() : Charset.forName(charset));
}
/**
* 解码字节码
*
* @param data 字符串
* @param charset 字符集,如果此字段为空,则解码的结果取决于平台
* @return 解码后的字符串
*/
public static String str(byte[] data, Charset charset) {
if (data == null) {
return null;
}
if (null == charset) {
return new String(data);
}
return new String(data, charset);
}
/**
* 将编码的byteBuffer数据转换为字符串
*
* @param data 数据
* @param charset 字符集,如果为空使用当前系统字符集
* @return 字符串
*/
public static String str(ByteBuffer data, String charset) {
if (data == null) {
return null;
}
return str(data, Charset.forName(charset));
}
/**
* 将编码的byteBuffer数据转换为字符串
*
* @param data 数据
* @param charset 字符集,如果为空使用当前系统字符集
* @return 字符串
*/
public static String str(ByteBuffer data, Charset charset) {
if (null == charset) {
charset = Charset.defaultCharset();
}
return charset.decode(data).toString();
}
// -----------------------------------------------------------------------
// 全角半角转换
/**
* 半角转全角
*
* @param input String.
* @return 全角字符串.
*/
public static String toSBC(String input) {
return toSBC(input, null);
}
/**
* 半角转全角
*
* @param input String
* @param notConvertSet 不替换的字符集合
* @return 全角字符串.
*/
public static String toSBC(String input, Set<Character> notConvertSet) {
char c[] = input.toCharArray();
for (int i = 0; i < c.length; i++) {
if (null != notConvertSet && notConvertSet.contains(c[i])) {
// 跳过不替换的字符
continue;
}
if (c[i] == ' ') {
c[i] = '\u3000';
} else if (c[i] < '\177') {
c[i] = (char) (c[i] + 65248);
}
}
return new String(c);
}
/**
* 全角转半角
*
* @param input String.
* @return 半角字符串
*/
public static String toDBC(String input) {
return toDBC(input, null);
}
/**
* 替换全角为半角
*
* @param text 文本
* @param notConvertSet 不替换的字符集合
* @return 替换后的字符
*/
public static String toDBC(String text, Set<Character> notConvertSet) {
char c[] = text.toCharArray();
for (int i = 0; i < c.length; i++) {
if (null != notConvertSet && notConvertSet.contains(c[i])) {
// 跳过不替换的字符
continue;
}
if (c[i] == '\u3000') {
c[i] = ' ';
} else if (c[i] > '\uFF00' && c[i] < '\uFF5F') {
c[i] = (char) (c[i] - 65248);
}
}
String returnString = new String(c);
return returnString;
}
/**
* 数字金额大写转换 先写个完整的然后将如零拾替换成零
*
* @param n 数字
* @return 中文大写数字
*/
public static String digitUppercase(double n) {
String[] fraction = { "角", "分" };
String[] digit = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
String[][] unit = { { "元", "万", "亿" }, { "", "拾", "佰", "仟" } };
String head = n < 0 ? "负" : "";
n = Math.abs(n);
String s = "";
for (int i = 0; i < fraction.length; i++) {
s += (digit[(int) (Math.floor(n * 10 * Math.pow(10, i)) % 10)] + fraction[i]).replaceAll("(零.)+", "");
}
if (s.length() < 1) {
s = "整";
}
int integerPart = (int) Math.floor(n);
for (int i = 0; i < unit[0].length && integerPart > 0; i++) {
String p = "";
for (int j = 0; j < unit[1].length && n > 0; j++) {
p = digit[integerPart % 10] + unit[1][j] + p;
integerPart = integerPart / 10;
}
s = p.replaceAll("(零.)*零$", "").replaceAll("^$", "零") + unit[0][i] + s;
}
return head + s.replaceAll("(零.)*零元", "元").replaceFirst("(零.)+", "").replaceAll("(零.)+", "零").replaceAll("^整$", "零元整");
}
}
package com.sinobase.common.support;
import com.sinobase.common.utils.StringUtils;
public class StrFormatter
{
public static final String EMPTY_JSON = "{}";
public static final char C_BACKSLASH = '\\';
public static final char C_DELIM_START = '{';
public static final char C_DELIM_END = '}';
/**
* 格式化字符串<br>
* 此方法只是简单将占位符 {} 按照顺序替换为参数<br>
* 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可<br>
* 例:<br>
* 通常使用:format("this is {} for {}", "a", "b") -> this is a for b<br>
* 转义{}: format("this is \\{} for {}", "a", "b") -> this is \{} for a<br>
* 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>
*
* @param strPattern 字符串模板
* @param argArray 参数列表
* @return 结果
*/
public static String format(final String strPattern, final Object... argArray)
{
if (StringUtils.isEmpty(strPattern) || StringUtils.isEmpty(argArray))
{
return strPattern;
}
final int strPatternLength = strPattern.length();
// 初始化定义好的长度以获得更好的性能
StringBuilder sbuf = new StringBuilder(strPatternLength + 50);
int handledPosition = 0;
int delimIndex;// 占位符所在位置
for (int argIndex = 0; argIndex < argArray.length; argIndex++)
{
delimIndex = strPattern.indexOf(EMPTY_JSON, handledPosition);
if (delimIndex == -1)
{
if (handledPosition == 0)
{
return strPattern;
}
else
{ // 字符串模板剩余部分不再包含占位符,加入剩余部分后返回结果
sbuf.append(strPattern, handledPosition, strPatternLength);
return sbuf.toString();
}
}
else
{
if (delimIndex > 0 && strPattern.charAt(delimIndex - 1) == C_BACKSLASH)
{
if (delimIndex > 1 && strPattern.charAt(delimIndex - 2) == C_BACKSLASH)
{
// 转义符之前还有一个转义符,占位符依旧有效
sbuf.append(strPattern, handledPosition, delimIndex - 1);
sbuf.append(Convert.utf8Str(argArray[argIndex]));
handledPosition = delimIndex + 2;
}
else
{
// 占位符被转义
argIndex--;
sbuf.append(strPattern, handledPosition, delimIndex - 1);
sbuf.append(C_DELIM_START);
handledPosition = delimIndex + 1;
}
}
else
{
// 正常占位符
sbuf.append(strPattern, handledPosition, delimIndex);
sbuf.append(Convert.utf8Str(argArray[argIndex]));
handledPosition = delimIndex + 2;
}
}
}
// append the characters following the last {} pair.
// 加入最后一个占位符后所有的字符
sbuf.append(strPattern, handledPosition, strPattern.length());
return sbuf.toString();
}
}
\ No newline at end of file
package com.sinobase.common.util;
/**
* 常量专用类
*
* @author liuhui001
*
*/
public class CommonContent {
/**
* 国投智能外部单位
*
*/
public static String COMPANY_EXTEND = "231560";
}
package com.sinobase.common.util;
import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.commons.lang3.time.DateFormatUtils;
import com.sinobase.common.utils.StringUtils;
/**
* 时间工具类
*
* @author sinobase
*/
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
public static String YYYY = "yyyy";
public static String YYYY_MM = "yyyy-MM";
public static String YYYY_MM_DD = "yyyy-MM-dd";
public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
private static String[] parsePatterns = {"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", "yyyy.MM.dd",
"yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM", "yyyy"};
/**
* 获取当前Date型日期
*
* @return Date() 当前日期
*/
public static Date getNowDate() {
return new Date();
}
/**
* 获取当前日期,
*
* @param formater 默认格式为yyyy-MM-dd
* @return String
*/
public static String getNowDate(String formater) {
return dateTimeNow(formater);
}
/**
* 获取当前日期, 默认格式为yyyy-MM-dd
*
* @return String
*/
public static String getDate() {
return dateTimeNow(YYYY_MM_DD);
}
public static final String getTime() {
return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
}
public static final String dateTimeNow() {
return dateTimeNow(YYYYMMDDHHMMSS);
}
public static final String dateTimeNow(final String format) {
return parseDateToStr(format, new Date());
}
public static final String dateTime(final Date date) {
return parseDateToStr(YYYY_MM_DD, date);
}
public static final String parseDateToStr(final String format, final Date date) {
return new SimpleDateFormat(format).format(date);
}
public static final Date dateTime(final String format, final String ts) {
try {
return new SimpleDateFormat(format).parse(ts);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
/**
* 日期路径 即年/月/日 如2018/08/08
*/
public static final String datePath() {
Date now = new Date();
return DateFormatUtils.format(now, "yyyy/MM/dd");
}
/**
* 日期路径 即年/月/日 如20180808
*/
public static final String dateTime() {
Date now = new Date();
return DateFormatUtils.format(now, "yyyyMMdd");
}
/**
* 日期型字符串转化为日期 格式
*/
public static Date parseDate(String str) {
if (str == null) {
return null;
}
try {
return parseDate(str, parsePatterns);
} catch (ParseException e) {
return null;
}
}
/**
* 获取服务器启动时间
*/
public static Date getServerStartDate() {
long time = ManagementFactory.getRuntimeMXBean().getStartTime();
return new Date(time);
}
/**
* 计算两个时间差
*/
public static String getDatePoor(Date endDate, Date nowDate) {
Map<String, String> dateMap = getDateDiff(endDate, nowDate);
String day = dateMap.get("day");
String hour = dateMap.get("hour");
String min = dateMap.get("min");
String sec = dateMap.get("sec");
return day + "天" + hour + "小时" + min + "分钟" + sec + "秒";
}
public static Map<String, String> getDateDiff(Date endDate, Date nowDate) {
Map<String, String> dateMap = new HashMap<>();
long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
long ns = 1000;
// 获得两个时间的毫秒时间差异
long diff = endDate.getTime() - nowDate.getTime();
// 计算差多少天
long day = diff / nd;
// 计算差多少小时
long hour = diff % nd / nh;
// 计算差多少分钟
long min = diff % nd % nh / nm;
// 计算差多少秒//输出结果
long sec = diff % nd % nh % nm / ns;
// return day + "天" + hour + "小时" + min + "分钟" + sec + "秒";
dateMap.put("day", day + "");
dateMap.put("hour", hour + "");
dateMap.put("min", min + "");
dateMap.put("sec", sec + "");
return dateMap;
}
/**
* 获取两个日期相关的天数
*
* @param oneDate
* @param twoDate
* @return
*/
public static Long getDiffDay(String oneDate, String twoDate) {
Map<String, String> dateMap = new HashMap<>();
long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
long ns = 1000;
long day = 0;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date start = dateFormat.parse(oneDate);
Date end = dateFormat.parse(twoDate);
// 获得两个时间的毫秒时间差异
long diff = start.getTime() - end.getTime();
// 计算差多少天
day = diff / nd;
// 计算差多少小时
long hour = diff % nd / nh;
// 计算差多少分钟
long min = diff % nd % nh / nm;
// 计算差多少秒//输出结果
long sec = diff % nd % nh % nm / ns;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return day;
}
/**
* 获取两个日期相关的小时数
*
* @param oneDate
* @param twoDate
* @return
*/
public static Long getDiffhour(String oneDate, String twoDate) {
Map<String, String> dateMap = new HashMap<>();
long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
long ns = 1000;
long day = 0;
long diff = 0;
long hour = 0;
long min = 0;
long sec = 0;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date start = dateFormat.parse(oneDate);
Date end = dateFormat.parse(twoDate);
// 获得两个时间的毫秒时间差异
diff = start.getTime() - end.getTime();
// 计算差多少天
day = diff / nd;
// 计算差多少小时
hour = diff % nd / nh;
// 计算差多少分钟
min = diff % nd % nh / nm;
// 计算差多少秒//输出结果
sec = diff % nd % nh % nm / ns;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return hour;
}
/**
* 返回某个日期相差的日期(返回格式 yyyy-MM-dd)
*
* @param date
* @param i 相差的天数
* @return
*/
public static String getDiffDay(String date, int i) {
Calendar cal = new GregorianCalendar();
cal.setTime(parseDate(date));
cal.set(Calendar.DATE, cal.get(Calendar.DATE) + i);
return parseDateToStr("yyyy-MM-dd", cal.getTime());
}
/**
* 返回某个日期相差的日期(返回格式 yyyy-MM-dd)
*
* @param date
* @param i 相差的天数
* @return
*/
public static String getDiffDay(Date date, int i) {
Calendar cal = new GregorianCalendar();
cal.setTime(date);
cal.set(Calendar.DATE, cal.get(Calendar.DATE) + i);
return parseDateToStr("yyyy-MM-dd", cal.getTime());
}
/**
* 判断时间是否在时间段内
*
* @param nowTime
* @param beginTime
* @param endTime
* @return
*/
public static boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) {
Calendar date = Calendar.getInstance();
date.setTime(nowTime);
Calendar begin = Calendar.getInstance();
begin.setTime(beginTime);
Calendar end = Calendar.getInstance();
end.setTime(endTime);
if (date.after(begin) && date.before(end)) {
return true;
} else {
return false;
}
}
/**
* 判断时间是否在时间段内 *
*
* @param nowDate 当前时间 yyyy-MM-dd HH:mm:ss :2019-07-22 00:00:00
* @param beginDate 开始时间 00:00:00 2019-07-23 09:00
* @param endDate 结束时间 00:05:00 2019-07-25 18:00
* @return
*/
public static boolean isInDate(String nowDate, String beginDate, String endDate) {
if(StringUtils.isEmpty(nowDate) || StringUtils.isEmpty(beginDate) || StringUtils.isEmpty(endDate)) {
return false;
}
Calendar date = parse2Calendar(nowDate);
Date nowTime = parse2Date(nowDate);
if (date.after(parse2Calendar(beginDate)) && date.before(parse2Calendar(endDate))) {
return true;
} else if (nowTime.compareTo(parse2Date(beginDate)) == 0 || nowTime.compareTo(parse2Date(endDate)) == 0) {
return true;
} else {
return false;
}
}
/**
* 获取两个日期间的所有日期
*
* @param startDate 开始日期
* @param endDate 结束日期
* @param format 返回的格式
* @return
*/
public static List<String> getDays(String startDate, String endDate, String format) {
List<String> days = new ArrayList<String>();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat rFormat = new SimpleDateFormat("".equals(format) ? "yyyy-MM-dd" : format);
try {
Date start = dateFormat.parse(startDate);
Date end = dateFormat.parse(endDate);
Calendar tempStart = Calendar.getInstance();
tempStart.setTime(start);
Calendar tempEnd = Calendar.getInstance();
tempEnd.setTime(end);
tempEnd.add(Calendar.DATE, +1);// 日期加1(包含结束)
while (tempStart.before(tempEnd)) {
days.add(rFormat.format(tempStart.getTime()));
tempStart.add(Calendar.DAY_OF_YEAR, 1);
}
} catch (ParseException e) {
e.printStackTrace();
}
return days;
}
/**
* 获取两个日期间的一定间隔数量的日期
*
* @param startDate 开始日期
* @param endDate 结束日期
* @param format 返回的格式
* @param intervalDay 间隔天数
* @return
*/
public static List<String> getDays(String startDate, String endDate, String format, Integer intervalDay) {
List<String> days = new ArrayList<>();
List<String> resultDays = new ArrayList<>();
days = getDays(startDate, endDate, format);
if (DateUtils.parseDate(startDate).getTime() < DateUtils.parseDate(endDate).getTime()) {
resultDays.add(startDate);
}
if (days != null && days.size() > intervalDay) {
for (int i = 0; i < days.size(); ) {
if (!resultDays.contains(days.get(i))) {
resultDays.add(days.get(i));
}
i = i + intervalDay;
}
}
return resultDays;
}
/**
* 获取两个日期间所有月份的最后一天 如果设置 num(几号) 则返回 要取得的日期
*
* @param startDate
* @param endDate
* @param format
* @param num
* @return
*/
public static List<String> getMonthForLastDays(String startDate, String endDate, String format, Integer num) {
List<String> days = getDays(startDate, endDate, format);
List<String> resultDays = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
if (num > 31 || num <= 0) {
num = 0;
}
for (String day : days) {
Calendar date = Calendar.getInstance();
date.setTime(parseDate(day));
String yearMonth = sdf.format(date.getTime());
int year = Integer.parseInt(yearMonth.split("-")[0]); // 年
int month = Integer.parseInt(yearMonth.split("-")[1]); // 月
Calendar cal = Calendar.getInstance();
// 设置年份
cal.set(Calendar.YEAR, year);
// 设置月份
cal.set(Calendar.MONTH, month - 1);
// 获取某月最大天数
int lastDay = cal.getActualMaximum(Calendar.DATE);
// 设置日历中月份的最大天数
if (num > 0 && lastDay > num) {
cal.set(Calendar.DAY_OF_MONTH, num);
} else {
cal.set(Calendar.DAY_OF_MONTH, lastDay);
}
SimpleDateFormat sdd = new SimpleDateFormat("yyyy-MM-dd");
if (!resultDays.contains(sdd.format(cal.getTime()))) {
if (DateUtils.parseDate(endDate).getTime() > cal.getTime().getTime()) {
resultDays.add(sdd.format(cal.getTime()));
}
}
}
return resultDays;
}
/**
* 获取月的日期
*
* @param date 所在月的某一天
* @param format 格式 默认 yyyy-MM-dd
* @param isAllDay 是否所有天
* @return
*/
public static List<String> getMonthDay(String date, String format, boolean isAllDay) {
List<String> list = new ArrayList<String>();
Calendar cal = parse2Calendar(date);
cal.add(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
int totalDays = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
SimpleDateFormat returnFormat = new SimpleDateFormat("".equals(format) ? "yyyy-MM-dd" : format);
list.add(returnFormat.format(cal.getTime()));
if (isAllDay) {
for (int i = 2; i <= totalDays; i++) {
cal.set(Calendar.DAY_OF_MONTH, i);
list.add(returnFormat.format(cal.getTime()));
}
} else {
cal.set(Calendar.DAY_OF_MONTH, totalDays);
list.add(returnFormat.format(cal.getTime()));
}
return list;
}
/**
* 得到某一天是这一年的第几周
*
* @param date
* @return
*/
public static int getWeekNo(String date) {
Calendar cal = Calendar.getInstance();
try {
cal.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(date));
} catch (ParseException e) {
e.printStackTrace();
}
int week = cal.get(Calendar.WEEK_OF_YEAR);
return week;
}
/**
* 判断是否为周六、周日
*
* @param date 输入的日期
* @return
* @throws ParseException
*/
public static boolean isWeekend(String date) throws ParseException {
boolean flag = false;
try {
Calendar cal = parse2Calendar(date);
flag = cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY;
} catch (Exception e) {
}
return flag;
}
/**
* 解析日期字符串为 Calendar 类型,
*
* @param date 日期字符串 格式 2019-01-12
* @return
*/
public static Calendar parse2Calendar(String date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date newDate = new Date();
if (date!=null && !"".equals(date)) {
try {
if (date.length() < 11) {
date += " 00:00";
}
newDate = dateFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
Calendar cal = Calendar.getInstance();
cal.setTime(newDate);
return cal;
}
/**
* 根据传入的日期月份获取月份的最后一天的日期
*
* @param Date : 格式:yyyy-mm
* @return
*/
public static String getMonthLastDayByDate(String Date) {
Date date = DateUtils.parseDate(Date);
final Calendar cal = Calendar.getInstance();
cal.setTime(date);
final int last = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_MONTH, last);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
return simpleDateFormat.format(cal.getTime());
}
/**
* 解析日期字符串为 Date 类型,
*
* @param date 日期字符串 格式 2019-01-12 或 2019-01-12 00:00
* @return
*/
public static Date parse2Date(String date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date newDate = new Date();
if (date!=null && !"".equals(date)) {
try {
if (date.length() < 11) {
date += " 00:00";
}
newDate = dateFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
return newDate;
}
/**
* 日期格式化
*
* @param date
* @param format
* @return
*/
public static String parse(String date, String format) {
SimpleDateFormat dateFormat = new SimpleDateFormat("".equals(format) ? "yyyy-MM-dd HH:mm" : format, Locale.SIMPLIFIED_CHINESE);
if(date==null || "".equals(date) || date.toLowerCase().equals("null")){
date = getNowDate("yyyy-MM-dd HH:mm");
}
Calendar cal = parse2Calendar(date);
String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
String rDate = dateFormat.format(cal.getTime());
return rDate;
}
/**
* 根据年、周号 获取周的开始结束日期
*
* @param year
* @param weekNo
* @param format
* @param isAllDay
* @return
*/
public static List<String> getWeekDayByNum(int year, int weekNo, String format, boolean isAllDay) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
cal.set(Calendar.YEAR, year);
cal.set(Calendar.WEEK_OF_YEAR, weekNo);
return getWeekDay(cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.DAY_OF_MONTH), format, isAllDay);
}
/**
* 获取周的开始结束日期
*
* @param date 日期所在的周,默认当前周
* @param format 返回的日期格式,默认 yyyy-MM-dd
* @param isAllDay 是否所有日期
* @return
*/
public static List<String> getWeekDay(String date, String format, boolean isAllDay) {
Calendar cal = parse2Calendar(date);
List<String> list = new ArrayList<String>();
int dayWeek = cal.get(Calendar.DAY_OF_WEEK);//  获得当前日期是一个星期的第几天  
if (1 == dayWeek) {
cal.add(Calendar.DAY_OF_MONTH, -1);
}
cal.setFirstDayOfWeek(Calendar.MONDAY);
int day = cal.get(Calendar.DAY_OF_WEEK);
SimpleDateFormat returnFormat = new SimpleDateFormat("".equals(format) ? "yyyy-MM-dd" : format);
cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
list.add(returnFormat.format(cal.getTime()));
if (isAllDay) {
for (int i = 1; i < 7; i++) {
cal.add(Calendar.DATE, 1);
list.add(returnFormat.format(cal.getTime()));
}
} else {
cal.add(Calendar.DATE, 6);
list.add(returnFormat.format(cal.getTime()));
}
return list;
}
/**
* 获取上周的开始时间
*
* @return
*/
@SuppressWarnings("unused")
public static String getLastWeekStartDay() {
Date date = new Date();
if (date == null) {
return null;
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
if (dayofweek == 1) {
dayofweek += 7;
}
cal.add(Calendar.DATE, 2 - dayofweek - 7);
return new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
}
/**
* 获取上周的结束时间
*
* @return
*/
public static String getLastWeekEndDay() {
Calendar cal = Calendar.getInstance();
try {
cal.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(getLastWeekStartDay()));
} catch (ParseException e) {
e.printStackTrace();
}
cal.add(Calendar.DAY_OF_WEEK, 6);
return new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
}
/**
* 获取本周周五
*
* @return
*/
public static String getWeekFriday() {
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = new GregorianCalendar();
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek() + 4);
Date last = cal.getTime();
return formater.format(last);
}
/**
* 获取当前时间的下一个双周 周五日期
*
* @return
*/
public static String getMonthBiweeklyFriday() {
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
// 当前日期是本月第几周
int weeks = c.get(Calendar.WEEK_OF_MONTH);
if (weeks % 2 == 0) {
return getWeekFriday();
} else {
c.setTime(parseDate(getWeekFriday()));
c.add(Calendar.WEEK_OF_MONTH, 1);
return formater.format(c.getTime());
}
}
/**
* 获取当前月最后一天
*
* @return
*/
public static String getMonthLastDay() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
return new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
}
/**
* 获取某段时间内的周一(二等等)的日期
*
* @param dataBegin 开始日期
* @param dataEnd 结束日期
* @param weekDays 获取周几,1-6代表周一到周六。0代表周日
* @return 返回日期List
*/
public static List<String> getDayOfWeekWithinDateInterval(String dataBegin, String dataEnd, int weekDays) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
List<String> dateResult = new ArrayList<>();
Calendar cal = Calendar.getInstance();
String[] dateInterval = {dataBegin, dataEnd};
Date[] dates = new Date[dateInterval.length];
for (int i = 0; i < dateInterval.length; i++) {
String[] ymd = dateInterval[i].split("[^\\d]+");
cal.set(Integer.parseInt(ymd[0]), Integer.parseInt(ymd[1]) - 1, Integer.parseInt(ymd[2]));
dates[i] = cal.getTime();
}
for (Date date = dates[0]; date.compareTo(dates[1]) <= 0; ) {
cal.setTime(date);
if (cal.get(Calendar.DAY_OF_WEEK) - 1 == weekDays) {
String format = sdf.format(date);
dateResult.add(format);
}
cal.add(Calendar.DATE, 1);
date = cal.getTime();
}
return dateResult;
}
/**
* 获取某段时间内的1号(2号等等)的日期
*
* @param dataBegin 开始日期
* @param dataEnd 结束日期
* @param monthDays 获取周几,1-31 代表月1号到31号
* @return 返回日期List
*/
public static List<String> getDayOfMonthWithinDateInterval(String dataBegin, String dataEnd, int monthDays) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
List<String> dateResult = new ArrayList<>();
Calendar cal = Calendar.getInstance();
String[] dateInterval = {dataBegin, dataEnd};
Date[] dates = new Date[dateInterval.length];
for (int i = 0; i < dateInterval.length; i++) {
String[] ymd = dateInterval[i].split("[^\\d]+");
cal.set(Integer.parseInt(ymd[0]), Integer.parseInt(ymd[1]) - 1, Integer.parseInt(ymd[2]));
dates[i] = cal.getTime();
}
for (Date date = dates[0]; date.compareTo(dates[1]) <= 0; ) {
cal.setTime(date);
if (cal.get(Calendar.DAY_OF_MONTH) == monthDays) {
String format = sdf.format(date);
dateResult.add(format);
}
cal.add(Calendar.DATE, 1);
date = cal.getTime();
}
return dateResult;
}
public static String addMinutes(String date, int minutes) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Calendar cal = parse2Calendar(date);
cal.add(Calendar.MINUTE, minutes);// 24小时制
return format.format(cal.getTime());
}
/**
* 根据当前时间获取数组中距离当前时间最近的下一个时间节点 专用于反馈页面的时间节点计算
*
* @param times
* @return
*/
public static String getRecentTimeForArray(String[] times) {
String resultDate = "";
Date nowDate = new Date(); // 当前时间
for (String time : times) {
Long num = getDiffDay(time, parseDateToStr("yyyy-MM-dd HH:mm:ss", nowDate));
if (num >= 0) {
if (StringUtils.isEmpty(resultDate)) {
resultDate = time;
}
}
}
if(StringUtils.isEmpty(resultDate)){
resultDate = times[times.length - 1];
}
return resultDate;
}
/**
* 根据开始时间和结束时间去除节假日(周六、周日)返回上班天数
*
* @param startDate
* @param endDate
* @return
*/
public static Integer goOutHolidays(Date startDate, Date endDate) {
Integer weekDays = 0;
List<String> allDays = DateUtils.getDays(DateUtils.parseDateToStr("yyyy-MM-dd", startDate), DateUtils.parseDateToStr("yyyy-MM-dd", endDate), "yyyy-MM-dd");
for (String day : allDays) {
try {
//如果不是周六日
if (!DateUtils.isWeekend(day)) {
weekDays++;
}
} catch (ParseException e) {
e.printStackTrace();
}
}
return weekDays;
}
public static void main(String[] args) {
// 反馈 办结
//System.out.println(DateUtils.getDateDiff(DateUtils.parseDate("2020-1-5"),DateUtils.parseDate("2020-1-1")).get("day"));
//System.out.println(DateUtils.getDiffDay("2020-1-4","2020-1-1"));
List<String> list =new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("e");
System.out.println(list.indexOf("b"));
}
//日期转换为中文(简体)
//开始
private static String getChinese(String digital) {
switch (Integer.parseInt(digital)) {
case 0:
return "〇";
case 1:
return "一";
case 2:
return "二";
case 3:
return "三";
case 4:
return "四";
case 5:
return "五";
case 6:
return "六";
case 7:
return "七";
case 8:
return "八";
case 9:
return "九";
case 10:
return "十";
}
return "〇";
}
public static String getYearChinese(String digital) {
DateUtils d = new DateUtils();
String retDate = "";
for (int i=0;i<digital.length();i++){
retDate = retDate + d.getChinese(String.valueOf(digital.charAt(i)));
}
return retDate;
}
public static String getMonthDayChinese(String digital) {
DateUtils d = new DateUtils();
String retDate = "";
if (digital.length()==1){
retDate = retDate + d.getChinese(String.valueOf(digital.charAt(0)));
}else{
if(String.valueOf(digital.charAt(0)).equals("0")){
retDate = retDate + d.getChinese(String.valueOf(digital.charAt(1)));
}else
if(String.valueOf(digital.charAt(0)).equals("1")){
retDate = retDate + d.getChinese("10");
if (String.valueOf(digital.charAt(1)).equals("0")){}else{
retDate = retDate + d.getChinese(String.valueOf(digital.charAt(1)));
}
}else{
retDate = retDate + d.getChinese(String.valueOf(digital.charAt(0)));
retDate = retDate + d.getChinese("10");
if (String.valueOf(digital.charAt(1)).equals("0")){}else{
retDate = retDate + d.getChinese(String.valueOf(digital.charAt(1)));
}
}
}
return retDate;
}
}
package com.sinobase.common.util;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Map;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSONObject;
public class HttpRequestUtil {
public static final String POST = "POST";
public static final String GET = "GET";
public static final String DEFAULT_CHARSET = "UTF-8";
private static Log log = LogFactory.getLog(HttpRequestUtil.class);
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
// 默认统一对参数进行encode编码
return sendGetReq(url, param, true);
}
/**
* 向指定URL发送GET方法的请求,不进行转码
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式,若请求参数不是规范格式请提前对参数进行转码处理
* @return URL 所代表远程资源的响应结果
*/
public static String sendGetNoEncode(String url, String param) {
// 默认统一对参数进行encode编码
return sendGetReq(url, param, false);
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
// 默认统一对参数进行encode编码
return sendPostReq(url, param, true);
}
/**
* 向指定URL发送POST方法的请求,不进行转码
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式,若请求参数不是规范格式请提前对参数进行转码处理
* @return URL 所代表远程资源的响应结果
*/
public static String sendPostNoEncode(String url, String param) {
// 默认统一对参数进行encode编码
return sendPostReq(url, param, false);
}
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @param isEncode
* 是否要对参数进行 Encode 处理, true 进行处理 false 不进行处理
* @return URL 所代表远程资源的响应结果
*/
private static String sendGetReq(String url, String param, Boolean isEncode) {
String result = "";
InputStreamReader reader = null;
try {
String urlNameString = url;
if (StringUtils.isNotBlank(param) && isEncode) {
urlNameString = urlNameString + "?" + settingPar(param);
}
else {
urlNameString = urlNameString + "?" + param;
}
log.debug("接口请求路径:" + urlNameString);
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.setRequestProperty("Accept-Charset", DEFAULT_CHARSET);
connection.setRequestProperty("Content-Type", "text/plain;charset=UTF-8");
connection.setReadTimeout(10000);//设置读取超时时间
connection.setConnectTimeout(10000);//设置连接超时时间
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
log.debug(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
reader = new InputStreamReader(connection.getInputStream(), DEFAULT_CHARSET);
result = reader2String(reader);
}
catch (Exception e) {
log.error("发送GET请求出现异常!", e);
}
// 使用finally块来关闭输入流
finally {
try {
if (reader != null) {
reader.close();
}
}
catch (Exception e2) {
return "";
}
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @param isEncode
* 是否要对参数进行 Encode 处理, true 进行处理 false 不进行处理
*
* @return 所代表远程资源的响应结果
*/
private static String sendPostReq(String url, String param, Boolean isEncode) {
log.debug("begin post service url:" + url);
log.debug("begin post service param:" + param);
PrintWriter out = null;
BufferedReader in = null;
InputStreamReader reader = null;
String result = "";
InputStream input = null;
try {
String urlNameString = url;
if (StringUtils.isNotBlank(param) && isEncode) {
// param = settingPar(param);
urlNameString = urlNameString + "?" + settingPar(param);
}
else {
urlNameString = urlNameString + "?" + param;
}
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", DEFAULT_CHARSET);
conn.setRequestProperty("Content-Type", "text/plain;charset=UTF-8");
conn.setReadTimeout(10000);//设置读取超时时间
conn.setConnectTimeout(10000);//设置连接超时时间
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), DEFAULT_CHARSET));
// 发送请求参数
//out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
input = conn.getInputStream();
reader = new InputStreamReader(input, DEFAULT_CHARSET);
return reader2String(reader);
}
catch (Exception e) {
log.error("发送 POST 请求出现异常!", e);
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (input != null) {
input.close();
}
if (reader != null) {
reader.close();
}
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
}
catch (IOException ex) {
return "";
}
}
return result;
}
/**
* 流转字符串
*
* @param reader
* @return
* @throws IOException
*/
private static String reader2String(Reader reader) throws IOException {
int len = 0;
char[] buf = new char[1024];
StringBuilder sb = new StringBuilder();
while ((len = reader.read(buf)) != -1) {
sb.append(new String(buf, 0, len));
}
return sb.toString();
}
/**
*
* <B>方法名称:</B><BR>
* <B>概要说明:对参数值进行转码</B><BR>
*
* @author:pangxj
* @cretetime:2018年1月11日 上午11:00:08
* @param par
* @return
* @throws UnsupportedEncodingException String
*/
private static String settingPar(String par) throws UnsupportedEncodingException {
if (StringUtils.isNotBlank(par)) {
String[] pars = par.split("&");
StringBuffer sb = new StringBuffer();
for (String pa : pars) {
String[] tempPar = pa.split("=");
if (sb.length() > 0) {
sb.append("&");
}
sb.append(tempPar[0].trim());
sb.append("=");
if (tempPar.length > 1) {
sb.append(URLEncoder.encode(tempPar[1].trim(), DEFAULT_CHARSET));
}
}
return sb.toString();
}
return "";
}
/**
*
* <B>方法名称:发起POST请求</B><BR>
* <B>概要说明:</B><BR>
*
* @param url
* 请求地址
* @param params
* 传递的参数
* @param charset
* 字符集
* @return
*/
public static String sendPost(String url, Map<String, String> params, String charset) {
String result = "";
HttpClient client = new HttpClient();
HttpMethod method = new PostMethod(url);
method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
method.setRequestHeader("Cookie", "special-cookie=value");
// method.setRequestHeader("", "");
// 设置Http Post数据
if (params != null) {
HttpMethodParams p = new HttpMethodParams();
for (Map.Entry<String, String> entry : params.entrySet()) {
p.setParameter(entry.getKey(), entry.getValue());
}
method.setParams(p);
}
// List<NameValuePair> nvps = new ArrayList<NameValuePair>();
// nvps.add(new BasicNameValuePair("signature", ""));
// method.setEntity(new UrlEncodedFormEntity(nvps));
try {
client.executeMethod(method);
if (method.getStatusCode() == HttpStatus.SC_OK) {
InputStream in = method.getResponseBodyAsStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, charset));
result = reader2String(reader);
in.close();
reader.close();
}
}
catch (IOException e) {
log.error("执行HTTP Post请求" + url + "时,发生异常!", e);
}
finally {
method.releaseConnection();
}
return result;
}
/**
*
* <B>方法名称:</B><BR>
* <B>概要说明:发JSON报文用此方法</B><BR>
*
* @param url
* @param data
* @return
*/
public static String sendPostUrl(String url, String data) {
String response = null;
try {
CloseableHttpClient httpclient = null;
CloseableHttpResponse httpresponse = null;
try {
httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url);
StringEntity stringentity = new StringEntity(data, ContentType.create("text/json", DEFAULT_CHARSET));
stringentity.setContentEncoding(DEFAULT_CHARSET);
httppost.setEntity(stringentity);
httpresponse = httpclient.execute(httppost);
response = EntityUtils.toString(httpresponse.getEntity(), DEFAULT_CHARSET);
}
finally {
if (httpclient != null) {
httpclient.close();
}
if (httpresponse != null) {
httpresponse.close();
}
}
}
catch (Exception e) {
log.error("发JSON报文错误", e);
}
return response;
}
/**
*
* <B>方法名称:</B><BR>
* <B>概要说明:发JSON报文用此方法</B><BR>
*
* @param url
* @param data
* @return
*/
public static String sendGetUrl(String url) {
String response = null;
try {
CloseableHttpClient httpclient = null;
CloseableHttpResponse httpresponse = null;
try {
httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet(url);
httpresponse = httpclient.execute(httpget);
response = EntityUtils.toString(httpresponse.getEntity(), DEFAULT_CHARSET);
}
finally {
if (httpclient != null) {
httpclient.close();
}
if (httpresponse != null) {
httpresponse.close();
}
}
}
catch (Exception e) {
log.error("发JSON报文错误", e);
}
return response;
}
// 发送请求
public static JSONObject httpsRequest(String requestUrl, String requestMethod) {
return httpsRequest(requestUrl, requestMethod, null);
}
public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
return JSONObject.parseObject(httpsRequestString(requestUrl, requestMethod, outputStr));
}
public static String httpsRequestString(String requestUrl, String requestMethod) {
return httpsRequestString(requestUrl, requestMethod, null);
}
public static String httpsRequestString(String requestUrl, String requestMethod, String outputStr) {
String result = "";
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
try {
TrustManager[] tm = { new JEEX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.setSSLSocketFactory(ssf);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod(requestMethod);
if (null != outputStr) {
OutputStream outputStream = conn.getOutputStream();
outputStream.write(outputStr.getBytes(DEFAULT_CHARSET));
outputStream.close();
}
inputStream = conn.getInputStream();
inputStreamReader = new InputStreamReader(inputStream, DEFAULT_CHARSET);
bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
conn.disconnect();
result = buffer.toString();
}
catch (Exception e) {
log.error(e);
}
finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (inputStreamReader != null) {
inputStreamReader.close();
}
if (inputStream != null) {
inputStream.close();
}
}
catch (IOException ex) {
//ex.printStackTrace();
}
}
return result;
}
public static byte[] httpsRequestByte(String requestUrl, String requestMethod) {
return httpsRequestByte(requestUrl, requestMethod, null);
}
public static byte[] httpsRequestByte(String requestUrl, String requestMethod, String outputStr) {
try {
TrustManager[] tm = { new JEEX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod(requestMethod);
if (null != outputStr) {
OutputStream outputStream = conn.getOutputStream();
outputStream.write(outputStr.getBytes(DEFAULT_CHARSET));
outputStream.close();
}
InputStream inputStream = conn.getInputStream();
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int n = 0;
if (inputStream != null) {
while (-1 != (n = inputStream.read(buffer))) {
output.write(buffer, 0, n);
}
inputStream.close();
}
byte[] res = new byte[output.toByteArray().length];
res = output.toByteArray();
output.close();
return res;
}
catch (Exception e) {
log.error(e);
}
return null;
}
public static String urlEnodeUTF8(String str) {
String result = str;
try {
result = URLEncoder.encode(str, DEFAULT_CHARSET);
}
catch (Exception e) {
log.error(e);
}
return result;
}
}
class JEEX509TrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
class TrustAnyHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
// 直接返回true
return true;
}
}
\ No newline at end of file
package com.sinobase.common.util;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.util.UUID;
/**
* 用于生产各种各样的ID
* @author LouBin
*/
public class IdUtils {
private static String middle = "";
static {
middle = MathUtils.makeUpNewData(Math.abs(NetworkUtils.getHostIP().hashCode()) + "", 4) + // 4位IP地址hash
MathUtils.makeUpNewData(NetworkUtils.getPid(), 4); // 4位PID进程hash
}
/**
* 以毫微秒做基础计数, 返回唯一有序增长ID
* <pre> System.nanoTime() </pre>
* 线程数量: 100
* 执行次数: 1000
* 平均耗时: 222 ms
* 数组长度: 100000
* Map Size: 100000
* @return ID长度32位
*/
public static String getIncreaseIdByNanoTime() {
return System.nanoTime() + // 时间戳-14位
middle + // 标志-8位
MathUtils.makeUpNewData(Thread.currentThread().hashCode() + "", 3) + // 3位线程标志
MathUtils.randomDigitNumber(7); // 随机7位数
}
/**
* 毫秒做基础计数, 返回ID, 有几率出现线程并发
* @return ID长度 15 位
*/
public static String getIdByTime() {
long r = 0;
synchronized (new byte[0]) {
r = (long) ((Math.random() + 1) * 100);
}
return System.currentTimeMillis() + String.valueOf(r).substring(1);
}
/**
* 以毫秒做基础计数, 返回唯一有序增长ID, 有几率出现线程并发
* <pre>
* System.currentTimeMillis()
* </pre>
* <pre>
* 线程数量: 100
* 执行次数: 1000
* 平均耗时: 206 ms
* 数组长度: 100000
* Map Size: 99992
* </pre>
*
* @return ID长度32位
*/
public static String getIncreaseIdByCurrentTimeMillis() {
return System.currentTimeMillis() + // 时间戳-14位
middle + // 标志-8位
MathUtils.makeUpNewData(Thread.currentThread().hashCode() + "", 3) + // 3位线程标志
MathUtils.randomDigitNumber(8); // 随机8位数
}
/**
* 基于UUID+MD5产生唯一无序ID
*
* <pre>
* 线程数量: 100
* 执行次数: 1000
* 平均耗时: 591 ms
* 数组长度: 100000
* Map Size: 100000
* </pre>
*
* @return ID长度32位
*/
public static String getRandomIdByUUID() {
return DigestUtils.md5Hex(UUID.randomUUID().toString());
}
/* ---------------------------------------------分割线------------------------- ----------------------- */
/** 字符串MD5处理类 */
private static class DigestUtils {
private static final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
private static final char[] DIGITS_UPPER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
private static char[] encodeHex(final byte[] data, final char[] toDigits) {
final int l = data.length;
final char[] out = new char[l << 1];
for (int i = 0, j = 0; i < l; i++) {
out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
out[j++] = toDigits[0x0F & data[i]];
}
return out;
}
public static String md5Hex(String str) {
return md5Hex(str, false);
}
public static String md5Hex(String str, boolean isUpper) {
try {
return new String(encodeHex(MessageDigest.getInstance("MD5").digest(str.getBytes("UTF-8")), isUpper ? DIGITS_UPPER : DIGITS_LOWER));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
/* ---------------------------------------------分割线------------------------------------------------*/
/** 网络相关的处理类 */
private static class NetworkUtils {
private static final String DEFAULT_HOST_IP = "10.10.10.10";
/**
* 获取当前进程的PID
*/
public static String getPid() {
return ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
}
/**
* 获取当前进程的主机IP地址
*/
public static String getHostIP() {
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
return DEFAULT_HOST_IP;
}
}
}
/* ---------------------------------------------分割线------------------------------------------------*/
/** 数据处理的相关类 */
private static class MathUtils {
private static final String DEFAULT_DIGITS = "0";
private static final String FIRST_DEFAULT_DIGITS = "1";
/**
* @param target 目标数字
* @param length 需要补充到的位数, 补充默认数字[0], 第一位默认补充[1]
* @return 补充后的结果
*/
public static String makeUpNewData(String target, int length) {
return makeUpNewData(target, length, DEFAULT_DIGITS);
}
/**
* @param target 目标数字
* @param length 需要补充到的位数
* @param add 需要补充的数字, 补充默认数字[0], 第一位默认补充[1]
* @return 补充后的结果
*/
public static String makeUpNewData(String target, int length, String add) {
if (target.startsWith("-"))
target.replace("-", "");
if (target.length() >= length)
return target.substring(0, length);
StringBuffer sb = new StringBuffer(FIRST_DEFAULT_DIGITS);
for (int i = 0; i < length - (1 + target.length()); i++) {
sb.append(add);
}
return sb.append(target).toString();
}
/**
* 生产一个随机的指定位数的字符串数字
* @param length
* @return
*/
public static String randomDigitNumber(int length) {
int start = Integer.parseInt(makeUpNewData("", length));// 1000+8999=9999
int end = Integer.parseInt(makeUpNewData("", length + 1)) - start;// 9000
return (int) (Math.random() * end) + start + "";
}
public static void main(String args[]) {
System.out.println(UUID.randomUUID().toString());
System.out.println(DigestUtils.md5Hex(UUID.randomUUID().toString()));
}
}
}
package com.sinobase.common.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
import com.sinobase.common.utils.StringUtils;
import com.sinobase.framework.web.page.TableDataInfo;
import com.sinobase.project.system.portal.domain.Message;
/**
* Map通用处理方法
*
* @author sinobase
*/
public class MapDataUtil {
public static Map<String, Object> convertDataMap(HttpServletRequest request) {
Map<String, String[]> properties = request.getParameterMap();
Map<String, Object> returnMap = new HashMap<String, Object>();
Iterator<?> entries = properties.entrySet().iterator();
Map.Entry<?, ?> entry;
String name = "";
String value = "";
while (entries.hasNext()) {
entry = (Entry<?, ?>) entries.next();
name = (String) entry.getKey();
Object valueObj = entry.getValue();
if (null == valueObj) {
value = "";
} else if (valueObj instanceof String[]) {
String[] values = (String[]) valueObj;
for (int i = 0; i < values.length; i++) {
value = values[i] + ",";
}
value = value.substring(0, value.length() - 1);
} else {
value = valueObj.toString();
}
returnMap.put(name, value);
}
return returnMap;
}
/**
* 将json对象转换成Map
* @param jsonmap
* @return
*/
@SuppressWarnings("unchecked")
public Map<String, String> jsonToMap(net.sf.json.JSONObject jsonmap) {
Map<String, String> map = new HashMap<String, String>();
Iterator<String> iterator = (Iterator<String>) jsonmap.keys();
String key = null;
String value = null;
while (iterator.hasNext()) {
key = iterator.next();
try {
value = jsonmap.getString(key);
} catch (Exception e) {
e.printStackTrace();
}
map.put(key, value);
}
return map;
}
/**
* APP数据返回封装
* @param code
* @param msg
* @param tableDataInfo 数据列表
* @return
*/
public static Map<String,Object> tableDataInfoToMap(String code, String msg, TableDataInfo tableDataInfo){
Map<String,Object> resultMap = new HashMap<>();
code = StringUtils.isNotEmpty(code) ? code : "1";
resultMap.put("code",code);
resultMap.put("msg", ("1".equals(code) ? "请求错误" : "操作成功") );
resultMap.put("data",tableDataInfo);
return resultMap;
}
/**
* APP数据返回封装
* @param code
* @param msg
* @param object 数据实体
* @return
*/
public static Map<String,Object> objectToMap(String code,String msg,Object object){
Map<String,Object> resultMap = new HashMap<>();
code = StringUtils.isNotEmpty(code) ? code : "1";
resultMap.put("code",code);
resultMap.put("msg", ("1".equals(code) ? "请求错误" : "操作成功") );
resultMap.put("data",object);
return resultMap;
}
/**
* 数据返回初始化
*
* @param list
* @param number
* @return
*/
public static Map<String, Object> initMap(List<Message> list, Integer number) {
if(number == null){
number = 0;
}
Map<String, Object> map = new HashMap<>();
if (list == null) {
map.put("data", new ArrayList<>());
map.put("number", 0);
} else {
if (number > 0) {
if (list.size() > number) {
map.put("data", list.subList(0, number));
} else {
map.put("data", list);
}
} else {
map.put("data", list);
}
map.put("number", list.size());
}
return map;
}
}
package com.sinobase.common.utils;
import java.math.BigDecimal;
/**
* 精确的浮点数运算
*
* @author sinobase
*/
public class Arith
{
/** 默认除法运算精度 */
private static final int DEF_DIV_SCALE = 10;
/** 这个类不能实例化 */
private Arith()
{
}
/**
* 提供精确的加法运算。
* @param v1 被加数
* @param v2 加数
* @return 两个参数的和
*/
public static double add(double v1, double v2)
{
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2).doubleValue();
}
/**
* 提供精确的减法运算。
* @param v1 被减数
* @param v2 减数
* @return 两个参数的差
*/
public static double sub(double v1, double v2)
{
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.subtract(b2).doubleValue();
}
/**
* 提供精确的乘法运算。
* @param v1 被乘数
* @param v2 乘数
* @return 两个参数的积
*/
public static double mul(double v1, double v2)
{
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.multiply(b2).doubleValue();
}
/**
* 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到
* 小数点以后10位,以后的数字四舍五入。
* @param v1 被除数
* @param v2 除数
* @return 两个参数的商
*/
public static double div(double v1, double v2)
{
return div(v1, v2, DEF_DIV_SCALE);
}
/**
* 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指
* 定精度,以后的数字四舍五入。
* @param v1 被除数
* @param v2 除数
* @param scale 表示表示需要精确到小数点以后几位。
* @return 两个参数的商
*/
public static double div(double v1, double v2, int scale)
{
if (scale < 0)
{
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
if (b1.compareTo(BigDecimal.ZERO) == 0)
{
return BigDecimal.ZERO.doubleValue();
}
return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 提供精确的小数位四舍五入处理。
* @param v 需要四舍五入的数字
* @param scale 小数点后保留几位
* @return 四舍五入后的结果
*/
public static double round(double v, int scale)
{
if (scale < 0)
{
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(Double.toString(v));
BigDecimal one = new BigDecimal("1");
return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
}
package com.sinobase.common.utils;
import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.commons.lang3.time.DateFormatUtils;
/**
* 时间工具类
*
* @author sinobase
*/
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
public static String YYYY = "yyyy";
public static String YYYY_MM = "yyyy-MM";
public static String YYYY_MM_DD = "yyyy-MM-dd";
public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
private static String[] parsePatterns = {"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", "yyyy.MM.dd",
"yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM", "yyyy"};
/**
* 获取当前Date型日期
*
* @return Date() 当前日期
*/
public static Date getNowDate() {
return new Date();
}
/**
* 获取当前日期,
*
* @param formater 默认格式为yyyy-MM-dd
* @return String
*/
public static String getNowDate(String formater) {
return dateTimeNow(formater);
}
/**
* 获取当前日期, 默认格式为yyyy-MM-dd
*
* @return String
*/
public static String getDate() {
return dateTimeNow(YYYY_MM_DD);
}
public static final String getTime() {
return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
}
public static final String dateTimeNow() {
return dateTimeNow(YYYYMMDDHHMMSS);
}
public static final String dateTimeNow(final String format) {
return parseDateToStr(format, new Date());
}
public static final String dateTime(final Date date) {
return parseDateToStr(YYYY_MM_DD, date);
}
public static final String parseDateToStr(final String format, final Date date) {
return new SimpleDateFormat(format).format(date);
}
public static final Date dateTime(final String format, final String ts) {
try {
return new SimpleDateFormat(format).parse(ts);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
/**
* 日期路径 即年/月/日 如2018/08/08
*/
public static final String datePath() {
Date now = new Date();
return DateFormatUtils.format(now, "yyyy/MM/dd");
}
/**
* 日期路径 即年/月/日 如20180808
*/
public static final String dateTime() {
Date now = new Date();
return DateFormatUtils.format(now, "yyyyMMdd");
}
/**
* 日期型字符串转化为日期 格式
*/
public static Date parseDate(String str) {
if (str == null) {
return null;
}
try {
return parseDate(str, parsePatterns);
} catch (ParseException e) {
return null;
}
}
/**
* 获取服务器启动时间
*/
public static Date getServerStartDate() {
long time = ManagementFactory.getRuntimeMXBean().getStartTime();
return new Date(time);
}
/**
* 计算两个时间差
*/
public static String getDatePoor(Date endDate, Date nowDate) {
Map<String, String> dateMap = getDateDiff(endDate, nowDate);
String day = dateMap.get("day");
String hour = dateMap.get("hour");
String min = dateMap.get("min");
String sec = dateMap.get("sec");
return day + "天" + hour + "小时" + min + "分钟" + sec + "秒";
}
public static Map<String, String> getDateDiff(Date endDate, Date nowDate) {
Map<String, String> dateMap = new HashMap<>();
long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
long ns = 1000;
// 获得两个时间的毫秒时间差异
long diff = endDate.getTime() - nowDate.getTime();
// 计算差多少天
long day = diff / nd;
// 计算差多少小时
long hour = diff % nd / nh;
// 计算差多少分钟
long min = diff % nd % nh / nm;
// 计算差多少秒//输出结果
long sec = diff % nd % nh % nm / ns;
// return day + "天" + hour + "小时" + min + "分钟" + sec + "秒";
dateMap.put("day", day + "");
dateMap.put("hour", hour + "");
dateMap.put("min", min + "");
dateMap.put("sec", sec + "");
return dateMap;
}
/**
* 获取两个日期相关的天数
*
* @param oneDate
* @param twoDate
* @return
*/
public static Long getDiffDay(String oneDate, String twoDate) {
Map<String, String> dateMap = new HashMap<>();
long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
long ns = 1000;
long day = 0;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date start = dateFormat.parse(oneDate);
Date end = dateFormat.parse(twoDate);
// 获得两个时间的毫秒时间差异
long diff = start.getTime() - end.getTime();
// 计算差多少天
day = diff / nd;
// 计算差多少小时
long hour = diff % nd / nh;
// 计算差多少分钟
long min = diff % nd % nh / nm;
// 计算差多少秒//输出结果
long sec = diff % nd % nh % nm / ns;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return day;
}
/**
* 获取两个日期相关的小时数
*
* @param oneDate
* @param twoDate
* @return
*/
public static Long getDiffhour(String oneDate, String twoDate) {
Map<String, String> dateMap = new HashMap<>();
long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
long ns = 1000;
long day = 0;
long diff = 0;
long hour = 0;
long min = 0;
long sec = 0;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date start = dateFormat.parse(oneDate);
Date end = dateFormat.parse(twoDate);
// 获得两个时间的毫秒时间差异
diff = start.getTime() - end.getTime();
// 计算差多少天
day = diff / nd;
// 计算差多少小时
hour = diff % nd / nh;
// 计算差多少分钟
min = diff % nd % nh / nm;
// 计算差多少秒//输出结果
sec = diff % nd % nh % nm / ns;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return hour;
}
/**
* 返回某个日期相差的日期(返回格式 yyyy-MM-dd)
*
* @param date
* @param i 相差的天数
* @return
*/
public static String getDiffDay(String date, int i) {
Calendar cal = new GregorianCalendar();
cal.setTime(parseDate(date));
cal.set(Calendar.DATE, cal.get(Calendar.DATE) + i);
return parseDateToStr("yyyy-MM-dd", cal.getTime());
}
/**
* 返回某个日期相差的日期(返回格式 yyyy-MM-dd)
*
* @param date
* @param i 相差的天数
* @return
*/
public static String getDiffDay(Date date, int i) {
Calendar cal = new GregorianCalendar();
cal.setTime(date);
cal.set(Calendar.DATE, cal.get(Calendar.DATE) + i);
return parseDateToStr("yyyy-MM-dd", cal.getTime());
}
/**
* 判断时间是否在时间段内
*
* @param nowTime
* @param beginTime
* @param endTime
* @return
*/
public static boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) {
Calendar date = Calendar.getInstance();
date.setTime(nowTime);
Calendar begin = Calendar.getInstance();
begin.setTime(beginTime);
Calendar end = Calendar.getInstance();
end.setTime(endTime);
if (date.after(begin) && date.before(end)) {
return true;
} else {
return false;
}
}
/**
* 判断时间是否在时间段内 *
*
* @param nowDate 当前时间 yyyy-MM-dd HH:mm:ss :2019-07-22 00:00:00
* @param beginDate 开始时间 00:00:00 2019-07-23 09:00
* @param endDate 结束时间 00:05:00 2019-07-25 18:00
* @return
*/
public static boolean isInDate(String nowDate, String beginDate, String endDate) {
if(StringUtils.isEmpty(nowDate) || StringUtils.isEmpty(beginDate) || StringUtils.isEmpty(endDate)) {
return false;
}
Calendar date = parse2Calendar(nowDate);
Date nowTime = parse2Date(nowDate);
if (date.after(parse2Calendar(beginDate)) && date.before(parse2Calendar(endDate))) {
return true;
} else if (nowTime.compareTo(parse2Date(beginDate)) == 0 || nowTime.compareTo(parse2Date(endDate)) == 0) {
return true;
} else {
return false;
}
}
/**
* 获取两个日期间的所有日期
*
* @param startDate 开始日期
* @param endDate 结束日期
* @param format 返回的格式
* @return
*/
public static List<String> getDays(String startDate, String endDate, String format) {
List<String> days = new ArrayList<String>();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat rFormat = new SimpleDateFormat("".equals(format) ? "yyyy-MM-dd" : format);
try {
Date start = dateFormat.parse(startDate);
Date end = dateFormat.parse(endDate);
Calendar tempStart = Calendar.getInstance();
tempStart.setTime(start);
Calendar tempEnd = Calendar.getInstance();
tempEnd.setTime(end);
tempEnd.add(Calendar.DATE, +1);// 日期加1(包含结束)
while (tempStart.before(tempEnd)) {
days.add(rFormat.format(tempStart.getTime()));
tempStart.add(Calendar.DAY_OF_YEAR, 1);
}
} catch (ParseException e) {
e.printStackTrace();
}
return days;
}
/**
* 获取两个日期间的一定间隔数量的日期
*
* @param startDate 开始日期
* @param endDate 结束日期
* @param format 返回的格式
* @param intervalDay 间隔天数
* @return
*/
public static List<String> getDays(String startDate, String endDate, String format, Integer intervalDay) {
List<String> days = new ArrayList<>();
List<String> resultDays = new ArrayList<>();
days = getDays(startDate, endDate, format);
if (DateUtils.parseDate(startDate).getTime() < DateUtils.parseDate(endDate).getTime()) {
resultDays.add(startDate);
}
if (days != null && days.size() > intervalDay) {
for (int i = 0; i < days.size(); ) {
if (!resultDays.contains(days.get(i))) {
resultDays.add(days.get(i));
}
i = i + intervalDay;
}
}
return resultDays;
}
/**
* 获取两个日期间所有月份的最后一天 如果设置 num(几号) 则返回 要取得的日期
*
* @param startDate
* @param endDate
* @param format
* @param num
* @return
*/
public static List<String> getMonthForLastDays(String startDate, String endDate, String format, Integer num) {
List<String> days = getDays(startDate, endDate, format);
List<String> resultDays = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
if (num > 31 || num <= 0) {
num = 0;
}
for (String day : days) {
Calendar date = Calendar.getInstance();
date.setTime(parseDate(day));
String yearMonth = sdf.format(date.getTime());
int year = Integer.parseInt(yearMonth.split("-")[0]); // 年
int month = Integer.parseInt(yearMonth.split("-")[1]); // 月
Calendar cal = Calendar.getInstance();
// 设置年份
cal.set(Calendar.YEAR, year);
// 设置月份
cal.set(Calendar.MONTH, month - 1);
// 获取某月最大天数
int lastDay = cal.getActualMaximum(Calendar.DATE);
// 设置日历中月份的最大天数
if (num > 0 && lastDay > num) {
cal.set(Calendar.DAY_OF_MONTH, num);
} else {
cal.set(Calendar.DAY_OF_MONTH, lastDay);
}
SimpleDateFormat sdd = new SimpleDateFormat("yyyy-MM-dd");
if (!resultDays.contains(sdd.format(cal.getTime()))) {
if (DateUtils.parseDate(endDate).getTime() > cal.getTime().getTime()) {
resultDays.add(sdd.format(cal.getTime()));
}
}
}
return resultDays;
}
/**
* 获取月的日期
*
* @param date 所在月的某一天
* @param format 格式 默认 yyyy-MM-dd
* @param isAllDay 是否所有天
* @return
*/
public static List<String> getMonthDay(String date, String format, boolean isAllDay) {
List<String> list = new ArrayList<String>();
Calendar cal = parse2Calendar(date);
cal.add(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
int totalDays = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
SimpleDateFormat returnFormat = new SimpleDateFormat("".equals(format) ? "yyyy-MM-dd" : format);
list.add(returnFormat.format(cal.getTime()));
if (isAllDay) {
for (int i = 2; i <= totalDays; i++) {
cal.set(Calendar.DAY_OF_MONTH, i);
list.add(returnFormat.format(cal.getTime()));
}
} else {
cal.set(Calendar.DAY_OF_MONTH, totalDays);
list.add(returnFormat.format(cal.getTime()));
}
return list;
}
/**
* 得到某一天是这一年的第几周
*
* @param date
* @return
*/
public static int getWeekNo(String date) {
Calendar cal = Calendar.getInstance();
try {
cal.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(date));
} catch (ParseException e) {
e.printStackTrace();
}
int week = cal.get(Calendar.WEEK_OF_YEAR);
return week;
}
/**
* 判断是否为周六、周日
*
* @param date 输入的日期
* @return
* @throws ParseException
*/
public static boolean isWeekend(String date) throws ParseException {
boolean flag = false;
try {
Calendar cal = parse2Calendar(date);
flag = cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY;
} catch (Exception e) {
}
return flag;
}
/**
* 解析日期字符串为 Calendar 类型,
*
* @param date 日期字符串 格式 2019-01-12
* @return
*/
public static Calendar parse2Calendar(String date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date newDate = new Date();
if (date!=null && !"".equals(date)) {
try {
if (date.length() < 11) {
date += " 00:00";
}
newDate = dateFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
Calendar cal = Calendar.getInstance();
cal.setTime(newDate);
return cal;
}
/**
* 根据传入的日期月份获取月份的最后一天的日期
*
* @param Date : 格式:yyyy-mm
* @return
*/
public static String getMonthLastDayByDate(String Date) {
Date date = DateUtils.parseDate(Date);
final Calendar cal = Calendar.getInstance();
cal.setTime(date);
final int last = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_MONTH, last);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
return simpleDateFormat.format(cal.getTime());
}
/**
* 解析日期字符串为 Date 类型,
*
* @param date 日期字符串 格式 2019-01-12 或 2019-01-12 00:00
* @return
*/
public static Date parse2Date(String date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date newDate = new Date();
if (date!=null && !"".equals(date)) {
try {
if (date.length() < 11) {
date += " 00:00";
}
newDate = dateFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
return newDate;
}
/**
* 日期格式化
*
* @param date
* @param format
* @return
*/
public static String parse(String date, String format) {
SimpleDateFormat dateFormat = new SimpleDateFormat("".equals(format) ? "yyyy-MM-dd HH:mm" : format, Locale.SIMPLIFIED_CHINESE);
if(date==null || "".equals(date) || date.toLowerCase().equals("null")){
date = getNowDate("yyyy-MM-dd HH:mm");
}
Calendar cal = parse2Calendar(date);
String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
String rDate = dateFormat.format(cal.getTime());
return rDate;
}
/**
* 根据年、周号 获取周的开始结束日期
*
* @param year
* @param weekNo
* @param format
* @param isAllDay
* @return
*/
public static List<String> getWeekDayByNum(int year, int weekNo, String format, boolean isAllDay) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
cal.set(Calendar.YEAR, year);
cal.set(Calendar.WEEK_OF_YEAR, weekNo);
return getWeekDay(cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.DAY_OF_MONTH), format, isAllDay);
}
/**
* 获取周的开始结束日期
*
* @param date 日期所在的周,默认当前周
* @param format 返回的日期格式,默认 yyyy-MM-dd
* @param isAllDay 是否所有日期
* @return
*/
public static List<String> getWeekDay(String date, String format, boolean isAllDay) {
Calendar cal = parse2Calendar(date);
List<String> list = new ArrayList<String>();
int dayWeek = cal.get(Calendar.DAY_OF_WEEK);//  获得当前日期是一个星期的第几天  
if (1 == dayWeek) {
cal.add(Calendar.DAY_OF_MONTH, -1);
}
cal.setFirstDayOfWeek(Calendar.MONDAY);
int day = cal.get(Calendar.DAY_OF_WEEK);
SimpleDateFormat returnFormat = new SimpleDateFormat("".equals(format) ? "yyyy-MM-dd" : format);
cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
list.add(returnFormat.format(cal.getTime()));
if (isAllDay) {
for (int i = 1; i < 7; i++) {
cal.add(Calendar.DATE, 1);
list.add(returnFormat.format(cal.getTime()));
}
} else {
cal.add(Calendar.DATE, 6);
list.add(returnFormat.format(cal.getTime()));
}
return list;
}
/**
* 获取上周的开始时间
*
* @return
*/
@SuppressWarnings("unused")
public static String getLastWeekStartDay() {
Date date = new Date();
if (date == null) {
return null;
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
if (dayofweek == 1) {
dayofweek += 7;
}
cal.add(Calendar.DATE, 2 - dayofweek - 7);
return new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
}
/**
* 获取上周的结束时间
*
* @return
*/
public static String getLastWeekEndDay() {
Calendar cal = Calendar.getInstance();
try {
cal.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(getLastWeekStartDay()));
} catch (ParseException e) {
e.printStackTrace();
}
cal.add(Calendar.DAY_OF_WEEK, 6);
return new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
}
/**
* 获取本周周五
*
* @return
*/
public static String getWeekFriday() {
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = new GregorianCalendar();
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek() + 4);
Date last = cal.getTime();
return formater.format(last);
}
/**
* 获取当前时间的下一个双周 周五日期
*
* @return
*/
public static String getMonthBiweeklyFriday() {
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
// 当前日期是本月第几周
int weeks = c.get(Calendar.WEEK_OF_MONTH);
if (weeks % 2 == 0) {
return getWeekFriday();
} else {
c.setTime(parseDate(getWeekFriday()));
c.add(Calendar.WEEK_OF_MONTH, 1);
return formater.format(c.getTime());
}
}
/**
* 获取当前月最后一天
*
* @return
*/
public static String getMonthLastDay() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
return new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
}
/**
* 获取某段时间内的周一(二等等)的日期
*
* @param dataBegin 开始日期
* @param dataEnd 结束日期
* @param weekDays 获取周几,1-6代表周一到周六。0代表周日
* @return 返回日期List
*/
public static List<String> getDayOfWeekWithinDateInterval(String dataBegin, String dataEnd, int weekDays) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
List<String> dateResult = new ArrayList<>();
Calendar cal = Calendar.getInstance();
String[] dateInterval = {dataBegin, dataEnd};
Date[] dates = new Date[dateInterval.length];
for (int i = 0; i < dateInterval.length; i++) {
String[] ymd = dateInterval[i].split("[^\\d]+");
cal.set(Integer.parseInt(ymd[0]), Integer.parseInt(ymd[1]) - 1, Integer.parseInt(ymd[2]));
dates[i] = cal.getTime();
}
for (Date date = dates[0]; date.compareTo(dates[1]) <= 0; ) {
cal.setTime(date);
if (cal.get(Calendar.DAY_OF_WEEK) - 1 == weekDays) {
String format = sdf.format(date);
dateResult.add(format);
}
cal.add(Calendar.DATE, 1);
date = cal.getTime();
}
return dateResult;
}
/**
* 获取某段时间内的1号(2号等等)的日期
*
* @param dataBegin 开始日期
* @param dataEnd 结束日期
* @param monthDays 获取周几,1-31 代表月1号到31号
* @return 返回日期List
*/
public static List<String> getDayOfMonthWithinDateInterval(String dataBegin, String dataEnd, int monthDays) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
List<String> dateResult = new ArrayList<>();
Calendar cal = Calendar.getInstance();
String[] dateInterval = {dataBegin, dataEnd};
Date[] dates = new Date[dateInterval.length];
for (int i = 0; i < dateInterval.length; i++) {
String[] ymd = dateInterval[i].split("[^\\d]+");
cal.set(Integer.parseInt(ymd[0]), Integer.parseInt(ymd[1]) - 1, Integer.parseInt(ymd[2]));
dates[i] = cal.getTime();
}
for (Date date = dates[0]; date.compareTo(dates[1]) <= 0; ) {
cal.setTime(date);
if (cal.get(Calendar.DAY_OF_MONTH) == monthDays) {
String format = sdf.format(date);
dateResult.add(format);
}
cal.add(Calendar.DATE, 1);
date = cal.getTime();
}
return dateResult;
}
public static String addMinutes(String date, int minutes) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Calendar cal = parse2Calendar(date);
cal.add(Calendar.MINUTE, minutes);// 24小时制
return format.format(cal.getTime());
}
/**
* 根据当前时间获取数组中距离当前时间最近的下一个时间节点 专用于反馈页面的时间节点计算
*
* @param times
* @return
*/
public static String getRecentTimeForArray(String[] times) {
String resultDate = "";
Date nowDate = new Date(); // 当前时间
for (String time : times) {
Long num = getDiffDay(time, parseDateToStr("yyyy-MM-dd HH:mm:ss", nowDate));
if (num >= 0) {
if (StringUtils.isEmpty(resultDate)) {
resultDate = time;
}
}
}
if(StringUtils.isEmpty(resultDate)){
resultDate = times[times.length - 1];
}
return resultDate;
}
/**
* 根据开始时间和结束时间去除节假日(周六、周日)返回上班天数
*
* @param startDate
* @param endDate
* @return
*/
public static Integer goOutHolidays(Date startDate, Date endDate) {
Integer weekDays = 0;
List<String> allDays = DateUtils.getDays(DateUtils.parseDateToStr("yyyy-MM-dd", startDate), DateUtils.parseDateToStr("yyyy-MM-dd", endDate), "yyyy-MM-dd");
for (String day : allDays) {
try {
//如果不是周六日
if (!DateUtils.isWeekend(day)) {
weekDays++;
}
} catch (ParseException e) {
e.printStackTrace();
}
}
return weekDays;
}
public static void main(String[] args) {
// 反馈 办结
//System.out.println(DateUtils.getDateDiff(DateUtils.parseDate("2020-1-5"),DateUtils.parseDate("2020-1-1")).get("day"));
//System.out.println(DateUtils.getDiffDay("2020-1-4","2020-1-1"));
List<String> list =new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("e");
System.out.println(list.indexOf("b"));
}
//日期转换为中文(简体)
//开始
private static String getChinese(String digital) {
switch (Integer.parseInt(digital)) {
case 0:
return "〇";
case 1:
return "一";
case 2:
return "二";
case 3:
return "三";
case 4:
return "四";
case 5:
return "五";
case 6:
return "六";
case 7:
return "七";
case 8:
return "八";
case 9:
return "九";
case 10:
return "十";
}
return "〇";
}
public static String getYearChinese(String digital) {
DateUtils d = new DateUtils();
String retDate = "";
for (int i=0;i<digital.length();i++){
retDate = retDate + d.getChinese(String.valueOf(digital.charAt(i)));
}
return retDate;
}
public static String getMonthDayChinese(String digital) {
DateUtils d = new DateUtils();
String retDate = "";
if (digital.length()==1){
retDate = retDate + d.getChinese(String.valueOf(digital.charAt(0)));
}else{
if(String.valueOf(digital.charAt(0)).equals("0")){
retDate = retDate + d.getChinese(String.valueOf(digital.charAt(1)));
}else
if(String.valueOf(digital.charAt(0)).equals("1")){
retDate = retDate + d.getChinese("10");
if (String.valueOf(digital.charAt(1)).equals("0")){}else{
retDate = retDate + d.getChinese(String.valueOf(digital.charAt(1)));
}
}else{
retDate = retDate + d.getChinese(String.valueOf(digital.charAt(0)));
retDate = retDate + d.getChinese("10");
if (String.valueOf(digital.charAt(1)).equals("0")){}else{
retDate = retDate + d.getChinese(String.valueOf(digital.charAt(1)));
}
}
}
return retDate;
}
}
package com.sinobase.common.utils;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.util.UUID;
/**
* 用于生产各种各样的ID
* @author LouBin
*/
public class IdUtils {
private static String middle = "";
static {
middle = MathUtils.makeUpNewData(Math.abs(NetworkUtils.getHostIP().hashCode()) + "", 4) + // 4位IP地址hash
MathUtils.makeUpNewData(NetworkUtils.getPid(), 4); // 4位PID进程hash
}
/**
* 以毫微秒做基础计数, 返回唯一有序增长ID
* <pre> System.nanoTime() </pre>
* 线程数量: 100
* 执行次数: 1000
* 平均耗时: 222 ms
* 数组长度: 100000
* Map Size: 100000
* @return ID长度32位
*/
public static String getIncreaseIdByNanoTime() {
return System.nanoTime() + // 时间戳-14位
middle + // 标志-8位
MathUtils.makeUpNewData(Thread.currentThread().hashCode() + "", 3) + // 3位线程标志
MathUtils.randomDigitNumber(7); // 随机7位数
}
/**
* 毫秒做基础计数, 返回ID, 有几率出现线程并发
* @return ID长度 15 位
*/
public static String getIdByTime() {
long r = 0;
synchronized (new byte[0]) {
r = (long) ((Math.random() + 1) * 100);
}
return System.currentTimeMillis() + String.valueOf(r).substring(1);
}
/**
* 以毫秒做基础计数, 返回唯一有序增长ID, 有几率出现线程并发
* <pre>
* System.currentTimeMillis()
* </pre>
* <pre>
* 线程数量: 100
* 执行次数: 1000
* 平均耗时: 206 ms
* 数组长度: 100000
* Map Size: 99992
* </pre>
*
* @return ID长度32位
*/
public static String getIncreaseIdByCurrentTimeMillis() {
return System.currentTimeMillis() + // 时间戳-14位
middle + // 标志-8位
MathUtils.makeUpNewData(Thread.currentThread().hashCode() + "", 3) + // 3位线程标志
MathUtils.randomDigitNumber(8); // 随机8位数
}
/**
* 基于UUID+MD5产生唯一无序ID
*
* <pre>
* 线程数量: 100
* 执行次数: 1000
* 平均耗时: 591 ms
* 数组长度: 100000
* Map Size: 100000
* </pre>
*
* @return ID长度32位
*/
public static String getRandomIdByUUID() {
return DigestUtils.md5Hex(UUID.randomUUID().toString());
}
/* ---------------------------------------------分割线------------------------- ----------------------- */
/** 字符串MD5处理类 */
private static class DigestUtils {
private static final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
private static final char[] DIGITS_UPPER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
private static char[] encodeHex(final byte[] data, final char[] toDigits) {
final int l = data.length;
final char[] out = new char[l << 1];
for (int i = 0, j = 0; i < l; i++) {
out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
out[j++] = toDigits[0x0F & data[i]];
}
return out;
}
public static String md5Hex(String str) {
return md5Hex(str, false);
}
public static String md5Hex(String str, boolean isUpper) {
try {
return new String(encodeHex(MessageDigest.getInstance("MD5").digest(str.getBytes("UTF-8")), isUpper ? DIGITS_UPPER : DIGITS_LOWER));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
/* ---------------------------------------------分割线------------------------------------------------*/
/** 网络相关的处理类 */
private static class NetworkUtils {
private static final String DEFAULT_HOST_IP = "10.10.10.10";
/**
* 获取当前进程的PID
*/
public static String getPid() {
return ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
}
/**
* 获取当前进程的主机IP地址
*/
public static String getHostIP() {
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
return DEFAULT_HOST_IP;
}
}
}
/* ---------------------------------------------分割线------------------------------------------------*/
/** 数据处理的相关类 */
private static class MathUtils {
private static final String DEFAULT_DIGITS = "0";
private static final String FIRST_DEFAULT_DIGITS = "1";
/**
* @param target 目标数字
* @param length 需要补充到的位数, 补充默认数字[0], 第一位默认补充[1]
* @return 补充后的结果
*/
public static String makeUpNewData(String target, int length) {
return makeUpNewData(target, length, DEFAULT_DIGITS);
}
/**
* @param target 目标数字
* @param length 需要补充到的位数
* @param add 需要补充的数字, 补充默认数字[0], 第一位默认补充[1]
* @return 补充后的结果
*/
public static String makeUpNewData(String target, int length, String add) {
if (target.startsWith("-"))
target.replace("-", "");
if (target.length() >= length)
return target.substring(0, length);
StringBuffer sb = new StringBuffer(FIRST_DEFAULT_DIGITS);
for (int i = 0; i < length - (1 + target.length()); i++) {
sb.append(add);
}
return sb.append(target).toString();
}
/**
* 生产一个随机的指定位数的字符串数字
* @param length
* @return
*/
public static String randomDigitNumber(int length) {
int start = Integer.parseInt(makeUpNewData("", length));// 1000+8999=9999
int end = Integer.parseInt(makeUpNewData("", length + 1)) - start;// 9000
return (int) (Math.random() * end) + start + "";
}
public static void main(String args[]) {
System.out.println(UUID.randomUUID().toString());
System.out.println(DigestUtils.md5Hex(UUID.randomUUID().toString()));
}
}
}
package com.sinobase.common.utils;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.servlet.http.HttpServletRequest;
/**
* 获取IP方法
*
* @author sinobase
*/
public class IpUtils
{
public static String getIpAddr(HttpServletRequest request)
{
if (request == null)
{
return "unknown";
}
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getHeader("X-Forwarded-For");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getHeader("X-Real-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getRemoteAddr();
}
return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
}
public static boolean internalIp(String ip)
{
byte[] addr = textToNumericFormatV4(ip);
return internalIp(addr) || "127.0.0.1".equals(ip);
}
private static boolean internalIp(byte[] addr)
{
final byte b0 = addr[0];
final byte b1 = addr[1];
// 10.x.x.x/8
final byte SECTION_1 = 0x0A;
// 172.16.x.x/12
final byte SECTION_2 = (byte) 0xAC;
final byte SECTION_3 = (byte) 0x10;
final byte SECTION_4 = (byte) 0x1F;
// 192.168.x.x/16
final byte SECTION_5 = (byte) 0xC0;
final byte SECTION_6 = (byte) 0xA8;
switch (b0)
{
case SECTION_1:
return true;
case SECTION_2:
if (b1 >= SECTION_3 && b1 <= SECTION_4)
{
return true;
}
case SECTION_5:
switch (b1)
{
case SECTION_6:
return true;
}
default:
return false;
}
}
/**
* 将IPv4地址转换成字节
*
* @param text IPv4地址
* @return byte 字节
*/
public static byte[] textToNumericFormatV4(String text)
{
if (text.length() == 0)
{
return null;
}
byte[] bytes = new byte[4];
String[] elements = text.split("\\.", -1);
try
{
long l;
int i;
switch (elements.length)
{
case 1:
l = Long.parseLong(elements[0]);
if ((l < 0L) || (l > 4294967295L))
return null;
bytes[0] = (byte) (int) (l >> 24 & 0xFF);
bytes[1] = (byte) (int) ((l & 0xFFFFFF) >> 16 & 0xFF);
bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
bytes[3] = (byte) (int) (l & 0xFF);
break;
case 2:
l = Integer.parseInt(elements[0]);
if ((l < 0L) || (l > 255L))
return null;
bytes[0] = (byte) (int) (l & 0xFF);
l = Integer.parseInt(elements[1]);
if ((l < 0L) || (l > 16777215L))
return null;
bytes[1] = (byte) (int) (l >> 16 & 0xFF);
bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
bytes[3] = (byte) (int) (l & 0xFF);
break;
case 3:
for (i = 0; i < 2; ++i)
{
l = Integer.parseInt(elements[i]);
if ((l < 0L) || (l > 255L))
return null;
bytes[i] = (byte) (int) (l & 0xFF);
}
l = Integer.parseInt(elements[2]);
if ((l < 0L) || (l > 65535L))
return null;
bytes[2] = (byte) (int) (l >> 8 & 0xFF);
bytes[3] = (byte) (int) (l & 0xFF);
break;
case 4:
for (i = 0; i < 4; ++i)
{
l = Integer.parseInt(elements[i]);
if ((l < 0L) || (l > 255L))
return null;
bytes[i] = (byte) (int) (l & 0xFF);
}
break;
default:
return null;
}
}
catch (NumberFormatException e)
{
return null;
}
return bytes;
}
public static String getHostIp()
{
try
{
return InetAddress.getLocalHost().getHostAddress();
}
catch (UnknownHostException e)
{
}
return "127.0.0.1";
}
public static String getHostName()
{
try
{
return InetAddress.getLocalHost().getHostName();
}
catch (UnknownHostException e)
{
}
return "未知";
}
}
\ No newline at end of file
package com.sinobase.common.utils;
/**
* <p>Title: ������</p>
* <p>Description: �ṩһ�鳣��ȫ�ֹ��ܺ��� </p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: ����</p>
* @author ��Сƽ
* @version 1.0
*/
import java.io.*;
import java.util.*;
import java.util.zip.*;
import java.awt.*;
import java.applet.Applet;
import javax.swing.*;
//import com.borland.dx.dataset.*;
import java.math.*;
import java.sql.*;
import javax.swing.tree.*;
import java.lang.reflect.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.sql.rowset.*;
public class JUtilities {
private static Calendar staticCal;
public JUtilities() {
}
/**
* �б�һ�������Ƿ��������ͣ�������java.sql.Types�ж���
* @param type ����
* @return �Ƿ���true�����Ƿ���false
*/
public static boolean isDate(int type) {
return (type == Types.TIMESTAMP || type == Types.DATE || type == Types.TIME);
}
/**
* �б��Ƿ������ͺ���ֵ
* @param type ����
* @return �Ƿ���true�����Ƿ���false
*/
public static boolean isNumber(int type) {
return isInteger(type) || isDecimal(type);
}
/**
* �б�һ�������Ƿ��ַ���������java.sql.Types�ж���
* @param type ����
* @return �Ƿ���true�����Ƿ���false
*/
public static boolean isString(int type) {
return (type == Types.VARCHAR || type == Types.CHAR ||
type == Types.LONGVARCHAR);
}
/**
* �б�һ�������Ƿ���ֵ��������java.sql.Types�ж���
* @param type ����
* @return �Ƿ���true�����Ƿ���false
*/
public static boolean isDecimal(int type) {
return (type == Types.NUMERIC || type == Types.DECIMAL ||
type == Types.FLOAT || type == Types.DOUBLE);
}
/**
* �б�һ�������Ƿ���ֵ��������java.sql.Types�ж���
* @param type ����
* @return �Ƿ���true�����Ƿ���false
*/
public static boolean isInteger(int type) {
/*�б�һ�������Ƿ���ֵ��������java.sql.Types�ж���*/
return (type == Types.INTEGER || type == Types.SMALLINT ||
type == Types.BIGINT);
}
/**
* ��һ�������еõ��ַ���������������κΣ�������
* @param ob ����
* @return �ַ���
*/
public static final String getAsString(Object ob) { // throws Exception
if (ob == null) {
return null;
}
if (ob instanceof String) {
return (String) ob;
}
else if (ob instanceof byte[]) {
return new String( (byte[]) ob);
}
else if (ob instanceof java.io.InputStream) {
try {
return getTextFromInputStream( (java.io.InputStream) ob);
}
catch (java.io.IOException ex) {}
}
return ob.toString();
}
/**
* ������������ת�����ı�. ��InputStream����(is)�õ� java.io.InputStreamReader(InputStream is)
* �����ٴ��ж����ı�. ��һЩ�洢���ı������ݿ���ֶ��У����еõ�����InputStream������,
* ʹ�øú���ת������Ҫ���ı������ӣ�
* <blockquote><pre>
* ResultSet rs = stmt.executeQuery(sql);
* Object obj = rs.getObject(1);
* if( obj instanceof InputStream )
* return Utilities.getTextFromInputStream((InputStream)obj);
* </pre></blockquote>
* @param is ����ת�����ı���������
* @return ת���ɵ��ı�
*/
public static final String getTextFromInputStream(InputStream is) throws java.
io.IOException {
if (is == null) {
return null;
}
try {
is.reset();
}
catch (Exception ex) {}
java.io.InputStreamReader r = new java.io.InputStreamReader(is);
StringBuffer buf = new StringBuffer();
for (; ; ) {
int c = r.read();
if (c <= 0) {
break;
}
buf.append( (char) c);
}
return buf.toString();
}
/**
* �����в����ַ���
* @param a ����
* @param o Ҫ���ҵ��ַ���
* @return �ҵ������ַ����������е�λ�ã����򷵻أ�1
*/
public static int findAtStringArray(String a[], Object o) {
if (a != null) {
for (int i = 0; i < a.length; i++) {
if (o == a[i] || (o != null && o.equals(a[i]))) {
return i;
}
}
}
return -1;
}
/**
* �����в����ִ�Сд�ز����ַ���
* @param a ����
* @param o Ҫ���ҵ��ַ���
* @return �ҵ������ַ����������е�λ�ã����򷵻أ�1
*/
public static int findAtStringArrayNoCase(String a[], String o) {
if (a != null) {
for (int i = 0; i < a.length; i++) {
if (o == a[i] || (o != null && o.equalsIgnoreCase(a[i]))) {
return i;
}
}
}
return -1;
}
/**
* ����һ����������һ�������е�λ��
* @param fromArrays
* @param findArrays
* @param bNoCase
* @param bFoundOnly
* @return
*/
public final static int[] findArrayIndices(String[] fromArrays,
String[] findArrays,
boolean bNoCase,
boolean bFoundOnly) {
int Indices[] = null;
if (findArrays != null && findArrays.length > 0) {
Indices = new int[findArrays.length];
for (int i = 0; i < Indices.length; i++) {
Indices[i] = -1;
if (fromArrays != null) {
for (int j = 0; j < fromArrays.length; j++) {
if (findArrays[i] != null && fromArrays[j] != null &&
( (!bNoCase && fromArrays[j].equals(findArrays[i]) ||
(bNoCase && fromArrays[j].equalsIgnoreCase(findArrays[i]))))) {
Indices[i] = j;
break;
}
}
}
}
}
if (Indices != null && bFoundOnly) {
int factNum = 0;
int len1 = Indices.length;
for (int i = 0; i < len1; i++) {
if (Indices[i] >= 0) {
factNum++;
}
}
if (factNum < len1) {
int factIndices[] = new int[factNum];
int pos = 0;
for (int i = 0; i < len1 && pos < factNum; i++) {
if (Indices[i] >= 0) {
factIndices[pos++] = Indices[i];
}
}
return factIndices;
}
}
return Indices;
}
/**
* �����������
* @param a ����
* @param o Ҫ���ҵ�����
* @return �ҵ����������������е�λ�ã����򷵻أ�1
*/
public static int findAtIntArray(int a[], int o) {
if (a != null) {
for (int i = 0; i < a.length; i++) {
if (o == a[i]) {
return i;
}
}
}
return -1;
}
/**
* ���ļ�
* @param fileName �ļ���
* @return �������ַ���
* @throws java.io.IOException
*/
public static final String getTextFromFile(String fileName) throws java.io.
IOException {
FileInputStream fis = new FileInputStream(fileName);
try {
return getTextFromInputStream(fis);
}
finally {
try {
fis.close();
}
catch (Throwable ex) {}
}
}
public static int startWithInt(String s, char charBefore, boolean negEnable) {
int p = s.indexOf(charBefore);
if (p <= 0) {
return p;
}
int i = 0;
if (negEnable && s.charAt(0) == '-') {
i++;
}
for (; i < p; i++) {
char c = s.charAt(i);
if (c < '0' || c > '9') {
return -1;
}
}
return p;
}
/**
* ����һ���ַ�����ʾ������. 0x��Ϊǰ׺�Ŀ���16����, 0b��Ϊǰ׺�Ŀ��ɶ�����.
* ���� parseInt("0x1F") ���Ϊ 31, parseInt("0b1011011") ���Ϊ 91
*/
public static final int parseInt(String text) {
text = text.trim();
int start = 0, base = 10;
if (text.startsWith("0x") || text.startsWith("0X")) {
start = 2;
base = 16;
}
else if (text.startsWith("0b") || text.startsWith("0B")) {
start = 2;
base = 2;
}
return Integer.parseInt(text.substring(start), base);
}
/**
* �ṩ��CachedRowSet��ȡ�����ݵĺ��������Ϊnull�����ص�Ϊ����
* @param crs CachedRowSet
* @param str �ֶ������ַ���
* @return
*/
public static String getString(CachedRowSet crs, String str) {
try {
String temp = crs.getString(str);
if (temp != null && !temp.equals("null")) {
return temp;
}
else {
return "";
}
}
catch (Exception ex) {
return "";
}
}
/**
* �ṩ��CachedRowSet��ȡ�����ݵĺ��������Ϊnull�����ص�Ϊ����
* @param crs CachedRowSet
* @param index �ֶ�������λ��
* @return
*/
public static String getString(CachedRowSet crs, int index) {
try {
String temp = crs.getString(index);
if (temp != null && !temp.equals("null")) {
return temp;
}
else {
return "";
}
}
catch (Exception ex) {
return "";
}
}
public static int getInt(CachedRowSet crs, String str) {
try {
return crs.getInt(str);
}
catch (Exception ex) {
return 0;
}
}
public static int getInt(CachedRowSet crs, int index) {
try {
return crs.getInt(index);
}
catch (Exception ex) {
return 0;
}
}
public static long getLong(CachedRowSet crs, String str) {
try {
return crs.getLong(str);
}
catch (Exception ex) {
return 0;
}
}
public static long getLong(CachedRowSet crs, int index) {
try {
return crs.getLong(index);
}
catch (Exception ex) {
return 0;
}
}
public static float getFloat(CachedRowSet crs, String str) {
try {
return crs.getFloat(str);
}
catch (Exception ex) {
return 0;
}
}
public static float getFloat(CachedRowSet crs, int index) {
try {
return crs.getFloat(index);
}
catch (Exception ex) {
return 0;
}
}
public static java.sql.Date getDate(CachedRowSet crs,
String str) {
try {
return crs.getDate(str);
}
catch (Exception ex) {
return null;
}
}
public static java.sql.Date getDate(CachedRowSet crs,
int index) {
try {
return crs.getDate(index);
}
catch (Exception ex) {
return null;
}
}
public static java.sql.Timestamp getTimestamp(CachedRowSet
crs, String str) {
try {
return crs.getTimestamp(str);
}
catch (Exception ex) {
return null;
}
}
public static java.sql.Timestamp getTimestamp(CachedRowSet
crs, int index) {
try {
return crs.getTimestamp(index);
}
catch (Exception ex) {
return null;
}
}
public static Blob getBlob(CachedRowSet crs, String str) {
try {
return crs.getBlob(str);
}
catch (Exception ex) {
return null;
}
}
public static Blob getBolb(CachedRowSet crs, int index) {
try {
return crs.getBlob(index);
}
catch (Exception ex) {
return null;
}
}
public static Clob getClob(CachedRowSet crs, String str) {
try {
return crs.getClob(str);
}
catch (Exception ex) {
return null;
}
}
public static Clob getClob(CachedRowSet crs, int index) {
try {
return crs.getClob(index);
}
catch (Exception ex) {
return null;
}
}
/**
* ��request�еõ���ֵ�ĺ��������Ϊnull�����ء���
* @param request
* @param param
* @return
*/
public static String getParameter(HttpServletRequest request, String param) {
String str = request.getParameter(param);
if (str != null) {
return str.trim();
}
else {
return "";
}
}
/**
* ��Session��ȡ��������ֵ�����Ϊnull���򷵻ؿ�
* @param session HttpSession����
* @param sessionName Session��
* @return ����Sessionֵ
*/
public static String getSession(HttpSession session, String sessionName) {
String retStr = "";
try {
retStr = session.getAttribute(sessionName).toString();
}
catch (Exception e) {
retStr = "";
}
return retStr;
}
public static void setMapToMap(HashMap toMap, HashMap fromMap) {
Collection coll = fromMap.entrySet();
Iterator it = coll.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
if (entry.getKey() != null && !entry.getKey().toString().equals("")) {
toMap.put(entry.getKey(), entry.getValue());
}
}
}
public static String getNumChiness(String numStr) {
char[] charArr = numStr.toCharArray();
String str = "";
for (int i = 0; i < charArr.length; i++) {
switch (charArr[i]) {
case '0':
if (i != 0) {
str = str + "��";
}
break;
case '1':
str = str + "һ";
break;
case '2':
str = str + "��";
break;
case '3':
str = str + "��";
break;
case '4':
str = str + "��";
break;
case '5':
str = str + "��";
break;
case '6':
str = str + "��";
break;
case '7':
str = str + "��";
break;
case '8':
str = str + "��";
break;
case '9':
str = str + "��";
break;
}
}
return str;
}
public static String getNumChinesTwo(String numTwo) {
char[] charArr = numTwo.toCharArray();
int length = charArr.length;
String str = "";
for (int i = 0; i < length; i++) {
String strTemp = "";
if (length - i == 2) {
strTemp = "ʮ";
}
if (length - i == 3) {
strTemp = "��";
}
if (length - i == 4) {
strTemp = "ǧ";
}
if (length - i == 5) {
strTemp = "��";
}
switch (charArr[i]) {
case '1':
if (length == 2 && i == 0) {
str = "ʮ" + str;
}
else {
str = str + "һ" + strTemp;
}
break;
case '2':
str = str + "��" + strTemp;
break;
case '3':
str = str + "��" + strTemp;
break;
case '4':
str = str + "��" + strTemp;
break;
case '5':
str = str + "��" + strTemp;
break;
case '6':
str = str + "��" + strTemp;
break;
case '7':
str = str + "��" + strTemp;
break;
case '8':
str = str + "��" + strTemp;
break;
case '9':
str = str + "��" + strTemp;
break;
}
}
return str;
}
}
package com.sinobase.common.utils;
import java.util.LinkedList;
public class LimitQueue<E> {
private int limit;
private LinkedList<E> queue = new LinkedList<E>();
public LimitQueue(int limit){
this.limit = limit;
}
public void append(E e){
if(queue.size() >= limit){
queue.poll();
}
queue.offer(e);
}
public E get(int position) {
return queue.get(position);
}
public E getLast() {
return queue.getLast();
}
public E getFirst() {
return queue.getFirst();
}
public int getLimit() {
return limit;
}
public int size() {
return queue.size();
}
public int indexOf(E e) {
return queue.indexOf(e);
}
}
package com.sinobase.common.utils;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Map;
/**
* 处理并记录日志文件
*
* @author sinobase
*/
public class LogUtils {
public static final Logger ERROR_LOG = LoggerFactory.getLogger("sys-error");
public static final Logger ACCESS_LOG = LoggerFactory.getLogger("sys-access");
/**
* 记录访问日志
* [username][jsessionid][ip][accept][UserAgent][url][params][Referer]
*
* @param request
*/
public static void logAccess(HttpServletRequest request) {
String username = getUsername();
String jsessionId = request.getRequestedSessionId();
String ip = IpUtils.getIpAddr(request);
String accept = request.getHeader("accept");
String userAgent = request.getHeader("User-Agent");
String url = request.getRequestURI();
String params = getParams(request);
StringBuilder s = new StringBuilder();
s.append(getBlock(username));
s.append(getBlock(jsessionId));
s.append(getBlock(ip));
s.append(getBlock(accept));
s.append(getBlock(userAgent));
s.append(getBlock(url));
s.append(getBlock(params));
s.append(getBlock(request.getHeader("Referer")));
getAccessLog().info(s.toString());
}
/**
* 记录异常错误 格式 [exception]
*
* @param message
* @param e
*/
public static void logError(String message, Throwable e) {
String username = getUsername();
StringBuilder s = new StringBuilder();
s.append(getBlock("exception"));
s.append(getBlock(username));
s.append(getBlock(message));
ERROR_LOG.error(s.toString(), e);
}
/**
* 记录页面错误 错误日志记录
* [page/eception][username][statusCode][errorMessage][servletName][uri][
* exceptionName][ip][exception]
*
* @param request
*/
public static void logPageError(HttpServletRequest request) {
String username = getUsername();
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
String message = (String) request.getAttribute("javax.servlet.error.message");
String uri = (String) request.getAttribute("javax.servlet.error.request_uri");
Throwable t = (Throwable) request.getAttribute("javax.servlet.error.exception");
if (statusCode == null) {
statusCode = 0;
}
StringBuilder s = new StringBuilder();
s.append(getBlock(t == null ? "page" : "exception"));
s.append(getBlock(username));
s.append(getBlock(statusCode));
s.append(getBlock(message));
s.append(getBlock(IpUtils.getIpAddr(request)));
s.append(getBlock(uri));
s.append(getBlock(request.getHeader("Referer")));
StringWriter sw = new StringWriter();
while (t != null) {
t.printStackTrace(new PrintWriter(sw));
t = t.getCause();
}
s.append(getBlock(sw.toString()));
getErrorLog().error(s.toString());
}
public static String getBlock(Object msg) {
if (msg == null) {
msg = "";
}
return "[" + msg.toString() + "]";
}
protected static String getParams(HttpServletRequest request) {
Map<String, String[]> params = request.getParameterMap();
return JSON.toJSONString(params);
}
protected static String getUsername() {
return (String) SecurityUtils.getSubject().getPrincipal();
}
public static Logger getAccessLog() {
return ACCESS_LOG;
}
public static Logger getErrorLog() {
return ERROR_LOG;
}
}
package com.sinobase.common.utils;
import com.sinobase.framework.web.page.TableDataInfo;
import com.sinobase.project.system.portal.domain.Message;
import java.util.*;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
/**
* Map通用处理方法
*
* @author sinobase
*/
public class MapDataUtil {
public static Map<String, Object> convertDataMap(HttpServletRequest request) {
Map<String, String[]> properties = request.getParameterMap();
Map<String, Object> returnMap = new HashMap<String, Object>();
Iterator<?> entries = properties.entrySet().iterator();
Map.Entry<?, ?> entry;
String name = "";
String value = "";
while (entries.hasNext()) {
entry = (Entry<?, ?>) entries.next();
name = (String) entry.getKey();
Object valueObj = entry.getValue();
if (null == valueObj) {
value = "";
} else if (valueObj instanceof String[]) {
String[] values = (String[]) valueObj;
for (int i = 0; i < values.length; i++) {
value = values[i] + ",";
}
value = value.substring(0, value.length() - 1);
} else {
value = valueObj.toString();
}
returnMap.put(name, value);
}
return returnMap;
}
/**
* 将json对象转换成Map
* @param jsonmap
* @return
*/
@SuppressWarnings("unchecked")
public Map<String, String> jsonToMap(net.sf.json.JSONObject jsonmap) {
Map<String, String> map = new HashMap<String, String>();
Iterator<String> iterator = (Iterator<String>) jsonmap.keys();
String key = null;
String value = null;
while (iterator.hasNext()) {
key = iterator.next();
try {
value = jsonmap.getString(key);
} catch (Exception e) {
e.printStackTrace();
}
map.put(key, value);
}
return map;
}
/**
* APP数据返回封装
* @param code
* @param msg
* @param tableDataInfo 数据列表
* @return
*/
public static Map<String,Object> tableDataInfoToMap(String code, String msg, TableDataInfo tableDataInfo){
Map<String,Object> resultMap = new HashMap<>();
code = StringUtils.isNotEmpty(code) ? code : "1";
resultMap.put("code",code);
resultMap.put("msg", ("1".equals(code) ? "请求错误" : "操作成功") );
resultMap.put("data",tableDataInfo);
return resultMap;
}
/**
* APP数据返回封装
* @param code
* @param msg
* @param object 数据实体
* @return
*/
public static Map<String,Object> objectToMap(String code,String msg,Object object){
Map<String,Object> resultMap = new HashMap<>();
code = StringUtils.isNotEmpty(code) ? code : "1";
resultMap.put("code",code);
resultMap.put("msg", ("1".equals(code) ? "请求错误" : "操作成功") );
resultMap.put("data",object);
return resultMap;
}
/**
* 数据返回初始化
*
* @param list
* @param number
* @return
*/
public static Map<String, Object> initMap(List<Message> list, Integer number) {
if(number == null){
number = 0;
}
Map<String, Object> map = new HashMap<>();
if (list == null) {
map.put("data", new ArrayList<>());
map.put("number", 0);
} else {
if (number > 0) {
if (list.size() > number) {
map.put("data", list.subList(0, number));
} else {
map.put("data", list);
}
} else {
map.put("data", list);
}
map.put("number", list.size());
}
return map;
}
}
package com.sinobase.common.utils;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
public class MapUtil {
/**
*
* @Title: objectToMap
* @Description: 将object转换为map,默认不保留空值
* @param @param obj
* @return Map<String,Object> 返回类型
* @throws
*/
public static Map<String, Object> objectToMap(Object obj) {
Map<String, Object> map = new LinkedHashMap<String, Object>();
map = objectToMap(obj, false);
return map;
}
public static Map<String, Object> objectToMap(Object obj, boolean keepNullVal) {
if (obj == null) {
return null;
}
Map<String, Object> map = new HashMap<String, Object>();
try {
Field[] declaredFields = obj.getClass().getDeclaredFields();
for (Field field : declaredFields) {
field.setAccessible(true);
if (keepNullVal == true) {
map.put(field.getName(), field.get(obj));
} else {
if (field.get(obj) != null && !"".equals(field.get(obj).toString())) {
map.put(field.getName(), field.get(obj));
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
}
package com.sinobase.common.utils;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Md5加密方法
*
* @author sinobase
*/
public class Md5Utils
{
private static final Logger log = LoggerFactory.getLogger(Md5Utils.class);
private static byte[] md5(String s)
{
MessageDigest algorithm;
try
{
algorithm = MessageDigest.getInstance("MD5");
algorithm.reset();
algorithm.update(s.getBytes("UTF-8"));
byte[] messageDigest = algorithm.digest();
return messageDigest;
}
catch (Exception e)
{
log.error("MD5 Error...", e);
}
return null;
}
private static final String toHex(byte hash[])
{
if (hash == null)
{
return null;
}
StringBuffer buf = new StringBuffer(hash.length * 2);
int i;
for (i = 0; i < hash.length; i++)
{
if ((hash[i] & 0xff) < 0x10)
{
buf.append("0");
}
buf.append(Long.toString(hash[i] & 0xff, 16));
}
return buf.toString();
}
public static String hash(String s)
{
try
{
return new String(toHex(md5(s)).getBytes("UTF-8"), "UTF-8");
}
catch (Exception e)
{
log.error("not supported charset...{}", e);
return s;
}
}
public static void main(String[] args) {
String str = "53564e922d710bad7a9de6bdc5ace2a5";
String time = new SimpleDateFormat("202102031935").format(new Date());
System.out.println(time);
String dd = Md5Utils.hash(str + time);
System.out.println(dd);
}
}
package com.sinobase.common.utils;
import org.springframework.context.MessageSource;
import com.sinobase.common.utils.spring.SpringUtils;
/**
* 获取i18n资源文件
*
* @author sinobase
*/
public class MessageUtils
{
/**
* 根据消息键和参数 获取消息 委托给spring messageSource
*
* @param code 消息键
* @param args 参数
* @return
*/
public static String message(String code, Object... args)
{
MessageSource messageSource = SpringUtils.getBean(MessageSource.class);
return messageSource.getMessage(code, args, null);
}
}
package com.sinobase.common.utils;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.sinobase.common.support.Convert;
/**
* 客户端工具类
*
* @author sinobase
*/
public class ServletUtils {
public static String[] getParameters(String name) {
return getRequest().getParameterValues(name);
}
/**
* 获取String参数
*/
public static String getParameter(String name) {
return Convert.toStr(getRequest().getParameter(name), "");
}
/**
* 获取String参数
*/
public static String getParameter(String name, String defaultValue) {
return Convert.toStr(getRequest().getParameter(name), defaultValue);
}
/**
* 获取Integer参数
*/
public static Integer getParameterToInt(String name) {
return Convert.toInt(getRequest().getParameter(name));
}
/**
* 获取Integer参数
*/
public static Integer getParameterToInt(String name, Integer defaultValue) {
return Convert.toInt(getRequest().getParameter(name), defaultValue);
}
/**
* 获取Boolean参数
* @return
*/
public static Boolean getParameterToBoolean(String name) {
return Convert.toBool(getRequest().getParameter(name));
}
/**
* 获取request
*/
public static HttpServletRequest getRequest() {
return getRequestAttributes().getRequest();
}
/**
* 获取response
*/
public static HttpServletResponse getResponse() {
return getRequestAttributes().getResponse();
}
/**
* 获取session
*/
public static HttpSession getSession() {
return getRequest().getSession();
}
public static ServletRequestAttributes getRequestAttributes() {
RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
return (ServletRequestAttributes) attributes;
}
/**
* 将字符串渲染到客户端
*
* @param response 渲染对象
* @param string 待渲染的字符串
* @return null
*/
public static String renderString(HttpServletResponse response, String string) {
try {
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().print(string);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 是否是Ajax异步请求
*
* @param request
*/
public static boolean isAjaxRequest(HttpServletRequest request) {
String accept = request.getHeader("accept");
if (accept != null && accept.indexOf("application/json") != -1) {
return true;
}
String xRequestedWith = request.getHeader("X-Requested-With");
if (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") != -1) {
return true;
}
String uri = request.getRequestURI();
if (StringUtils.inStringIgnoreCase(uri, ".json", ".xml")) {
return true;
}
String ajax = request.getParameter("__ajax");
if (StringUtils.inStringIgnoreCase(ajax, "json", "xml")) {
return true;
}
return false;
}
}
package com.sinobase.common.utils;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.sinobase.common.support.StrFormatter;
/**
* 字符串工具类
*
* @author sinobase
*/
public class StringUtils extends org.apache.commons.lang3.StringUtils {
/** 空字符串 */
private static final String NULLSTR = "";
/** 下划线 */
private static final char SEPARATOR = '_';
/**
* 获取参数不为空值
*
* @param value defaultValue 要判断的value
* @return value 返回值
*/
public static <T> T nvl(T value, T defaultValue) {
return value != null ? value : defaultValue;
}
/**
* * 判断一个Collection是否为空, 包含List,Set,Queue
*
* @param coll 要判断的Collection
* @return true:为空 false:非空
*/
public static boolean isEmpty(Collection<?> coll) {
return isNull(coll) || coll.isEmpty();
}
/**
* * 判断一个Collection是否非空,包含List,Set,Queue
*
* @param coll 要判断的Collection
* @return true:非空 false:空
*/
public static boolean isNotEmpty(Collection<?> coll) {
return !isEmpty(coll);
}
/**
* * 判断一个对象数组是否为空
*
* @param objects 要判断的对象数组
** @return true:为空 false:非空
*/
public static boolean isEmpty(Object[] objects) {
return isNull(objects) || (objects.length == 0);
}
/**
* * 判断一个对象数组是否非空
*
* @param objects 要判断的对象数组
* @return true:非空 false:空
*/
public static boolean isNotEmpty(Object[] objects) {
return !isEmpty(objects);
}
/**
* * 判断一个Map是否为空
*
* @param map 要判断的Map
* @return true:为空 false:非空
*/
public static boolean isEmpty(Map<?, ?> map) {
return isNull(map) || map.isEmpty();
}
/**
* * 判断一个Map是否为空
*
* @param map 要判断的Map
* @return true:非空 false:空
*/
public static boolean isNotEmpty(Map<?, ?> map) {
return !isEmpty(map);
}
/**
* * 判断一个字符串是否为空串
*
* @param str String
* @return true:为空 false:非空
*/
public static boolean isEmpty(String str) {
return isNull(str) || NULLSTR.equals(str.trim()) || "null".equals(str.toLowerCase()) || "undefined".equals(str.toLowerCase());
}
/**
* * 判断一个字符串是否为非空串
*
* @param str String
* @return true:非空串 false:空串
*/
public static boolean isNotEmpty(String str) {
return !isEmpty(str);
}
/**
* * 判断一个对象是否为空
*
* @param object Object
* @return true:为空 false:非空
*/
public static boolean isNull(Object object) {
return object == null;
}
/**
* * 判断一个对象是否非空
*
* @param object Object
* @return true:非空 false:空
*/
public static boolean isNotNull(Object object) {
return !isNull(object);
}
/**
* * 判断一个对象是否是数组类型(Java基本型别的数组)
*
* @param object 对象
* @return true:是数组 false:不是数组
*/
public static boolean isArray(Object object) {
return isNotNull(object) && object.getClass().isArray();
}
/**
* 去空格
*/
public static String trim(String str) {
return (str == null ? "" : str.trim());
}
/**
* 去除所有特殊字符
* @param str
* @return
*/
public static String replace(String str){
if(isEmpty(str)){
return "";
}else{
Pattern p = Pattern.compile("[`~☆★!@#$%^&*()+=|{}':;,\\[\\]》·<>/?~!@#¥%……()——+|{}【】‘;:”“’。,、?]");//去除特殊字符
Matcher m = p.matcher(str);
str = m.replaceAll("").trim().replace(" ", "").replace("\\", "");//将匹配的特殊字符转变为空
return str;
}
}
/**
* 截取字符串
*
* @param str 字符串
* @param start 开始
* @return 结果
*/
public static String substring(final String str, int start) {
if (str == null) {
return NULLSTR;
}
if (start < 0) {
start = str.length() + start;
}
if (start < 0) {
start = 0;
}
if (start > str.length()) {
return NULLSTR;
}
return str.substring(start);
}
/**
* 截取字符串
*
* @param str 字符串
* @param start 开始
* @param end 结束
* @return 结果
*/
public static String substring(final String str, int start, int end) {
if (str == null) {
return NULLSTR;
}
if (end < 0) {
end = str.length();// + end;
}
if (start < 0) {
start = str.length() + start;
}
if (end > str.length()) {
end = str.length();
}
if (start > end) {
return NULLSTR;
}
if (start < 0) {
start = 0;
}
if (end < 0) {
end = 0;
}
return str.substring(start, end);
}
/**
* 格式化文本, {} 表示占位符<br>
* 此方法只是简单将占位符 {} 按照顺序替换为参数<br>
* 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可<br>
* 例:<br>
* 通常使用:format("this is {} for {}", "a", "b") -> this is a for b<br>
* 转义{}: format("this is \\{} for {}", "a", "b") -> this is \{} for a<br>
* 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>
*
* @param template 文本模板,被替换的部分用 {} 表示
* @param params 参数值
* @return 格式化后的文本
*/
public static String format(String template, Object... params) {
if (isEmpty(params) || isEmpty(template)) {
return template;
}
return StrFormatter.format(template, params);
}
/**
* 下划线转驼峰命名
*/
public static String toUnderScoreCase(String str) {
if (str == null) {
return null;
}
StringBuilder sb = new StringBuilder();
// 前置字符是否大写
boolean preCharIsUpperCase = true;
// 当前字符是否大写
boolean curreCharIsUpperCase = true;
// 下一字符是否大写
boolean nexteCharIsUpperCase = true;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (i > 0) {
preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1));
} else {
preCharIsUpperCase = false;
}
curreCharIsUpperCase = Character.isUpperCase(c);
if (i < (str.length() - 1)) {
nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1));
}
if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase) {
sb.append(SEPARATOR);
} else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase) {
sb.append(SEPARATOR);
}
sb.append(Character.toLowerCase(c));
}
return sb.toString();
}
/**
* 是否包含字符串
*
* @param str 验证字符串
* @param strs 字符串组
* @return 包含返回true
*/
public static boolean inStringIgnoreCase(String str, String... strs) {
if (str != null && strs != null) {
for (String s : strs) {
if (str.equalsIgnoreCase(trim(s))) {
return true;
}
}
}
return false;
}
public static String splitStr2Sql(String str,String symbol){
String [] arr = splitStr2Array(str,symbol);
str = "";
for (int i = 0; i < arr.length; i++) {
str += (i==0)?("'" + arr[i] + "'"):(",'" + arr[i] + "'");
}
return str;
}
/**
* 字符串切割成数组
* @param str
* @param symbol
* @return
*/
public static String[] splitStr2Array(String str,String symbol){
if(str == null || symbol == null){
return new String[0];
}
return str.split(symbol);
}
/**
* 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。
* 例如:HELLO_WORLD->HelloWorld
*
* @param name 转换前的下划线大写方式命名的字符串
* @return 转换后的驼峰式命名的字符串
*/
public static String convertToCamelCase(String name) {
StringBuilder result = new StringBuilder();
// 快速检查
if (name == null || name.isEmpty()) {
// 没必要转换
return "";
} else if (!name.contains("_")) {
// 不含下划线,仅将首字母大写
return name.substring(0, 1).toUpperCase() + name.substring(1);
}
// 用下划线将原始字符串分割
String[] camels = name.split("_");
for (String camel : camels) {
// 跳过原始字符串中开头、结尾的下换线或双重下划线
if (camel.isEmpty()) {
continue;
}
// 首字母大写
result.append(camel.substring(0, 1).toUpperCase());
result.append(camel.substring(1).toLowerCase());
}
return result.toString();
}
/**
* 字符串转数字
* @param str
* @param defaultInt
* @return
*/
public static int str2int(String str,int defaultInt){
if(isNotEmpty(str)){
try{
defaultInt = Integer.parseInt(str);
}catch(Exception e){
}
}
return defaultInt;
}
/**
* 数据转字符串
* @param arr
* @param symbol
* @return
*/
public static String array2Str(String[] arr,String symbol){
String str = "";
if(arr != null && arr.length > 0){
if(StringUtils.isEmpty(symbol)){
symbol = ",";
}
str = org.apache.commons.lang3.StringUtils.join(arr,symbol);
}
return str;
}
/**
* 两份日期比较
* @param dateStrPre
* @param dateStrBeh
* @return
*/
public static int compareDateStr(String dateStrPre, String dateStrBeh){
Date datePre = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",dateStrPre);
Date dateBeh = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",dateStrBeh);
int flag = 0;
if (datePre.after(dateBeh)){
flag = 1;
} else if (datePre.before(dateBeh)){
flag = -1;
}else {
flag = 0;
}
return flag;
}
/**
* 过滤html相关标签,保留字符文本内容
* @param inputString
* @return
*/
public static String removeHtmlTagToStr(String htmlStr){
if(isEmpty(htmlStr)){
return "";
}else{
String textStr = "";
try {
//定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script>
String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>";
htmlStr = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
//定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style>
String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>";
htmlStr = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
// 定义HTML标签的正则表达式
String regEx_html = "<[^>]+>";
htmlStr = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
textStr = htmlStr;
} catch (Exception e) {
e.printStackTrace();
return htmlStr;
}
return textStr;
}
}
}
\ No newline at end of file
package com.sinobase.common.utils;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 线程相关工具类.
*
* @author sinobase
*/
public class Threads {
private static final Logger logger = LoggerFactory.getLogger("sys-user");
/**
* sleep等待,单位为毫秒
*/
public static void sleep(long milliseconds) {
try {
Thread.sleep(milliseconds);
} catch (InterruptedException e) {
return;
}
}
/**
* 停止线程池 先使用shutdown, 停止接收新任务并尝试完成所有已存在任务. 如果超时, 则调用shutdownNow,
* 取消在workQueue中Pending的任务,并中断所有阻塞函数. 如果仍人超時,則強制退出.
* 另对在shutdown时线程本身被调用中断做了处理.
*/
public static void shutdownAndAwaitTermination(ExecutorService pool) {
if (pool != null && !pool.isShutdown()) {
pool.shutdown();
try {
if (!pool.awaitTermination(120, TimeUnit.SECONDS)) {
pool.shutdownNow();
if (!pool.awaitTermination(120, TimeUnit.SECONDS)) {
logger.info("Pool did not terminate");
}
}
} catch (InterruptedException ie) {
pool.shutdownNow();
Thread.currentThread().interrupt();
}
}
}
}
package com.sinobase.common.utils;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.sinobase.project.system.menu.domain.Menu;
/**
* 权限数据处理
*
* @author sinobase
*/
public class TreeUtils {
/**
* 根据父节点的ID获取所有子节点
*
* @param list 分类表
* @param parentId 传入的父节点ID
* @return String
*/
public static List<Menu> getChildPerms(List<Menu> list, String parentId) {
List<Menu> returnList = new ArrayList<Menu>();
for (Iterator<Menu> iterator = list.iterator(); iterator.hasNext();) {
Menu t = (Menu) iterator.next();
// 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
if (t.getParentId().equals(parentId)) {
//System.out.println((t.getUrl().indexOf("parse_tab") > -1)+"------------"+ t.getMenuName()+"--------"+ t.getUrl());
if(t.getUrl().indexOf("parse_tab") < 0){
recursionFn(list, t);
}
returnList.add(t);
}
}
return returnList;
}
/**
* 递归列表
*
* @param list
* @param t
*/
private static void recursionFn(List<Menu> list, Menu t) {
// 得到子节点列表
List<Menu> childList = getChildList(list, t);
t.setChildren(childList);
for (Menu tChild : childList) {
if (hasChild(list, tChild)) {
// 判断是否有子节点
Iterator<Menu> it = childList.iterator();
while (it.hasNext()) {
Menu n = (Menu) it.next();
recursionFn(list, n);
}
}
}
}
/**
* 得到子节点列表
*/
private static List<Menu> getChildList(List<Menu> list, Menu t) {
List<Menu> tlist = new ArrayList<Menu>();
//20200103 LoubBin 添加 模块设置 标签页面功能无效BUG
if(t.getUrl().indexOf("parse_tab") < 0 && !t.getMenuType().equals("C")){
//System.out.println(t.getMenuName() + "------------"+t.getUrl());
Iterator<Menu> it = list.iterator();
while (it.hasNext()) {
Menu n = (Menu) it.next();
if (n.getParentId().equals(t.getMenuId())) {
tlist.add(n);
}
}
}
return tlist;
}
List<Menu> returnList = new ArrayList<Menu>();
/**
* 根据父节点的ID获取所有子节点
*
* @param list 分类表
* @param typeId 传入的父节点ID
* @param prefix 子节点前缀
*/
public List<Menu> getChildPerms(List<Menu> list, int typeId, String prefix) {
if (list == null) {
return null;
}
for (Iterator<Menu> iterator = list.iterator(); iterator.hasNext();) {
Menu node = (Menu) iterator.next();
// 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
if (node.getParentId().equals(typeId)) {
recursionFn(list, node, prefix);
}
// 二、遍历所有的父节点下的所有子节点
/*
* if (node.getParentId()==0) { recursionFn(list, node); }
*/
}
return returnList;
}
private void recursionFn(List<Menu> list, Menu node, String p) {
// 得到子节点列表
List<Menu> childList = getChildList(list, node);
if (hasChild(list, node)) {
// 判断是否有子节点
returnList.add(node);
Iterator<Menu> it = childList.iterator();
while (it.hasNext()) {
Menu n = (Menu) it.next();
n.setMenuName(p + n.getMenuName());
recursionFn(list, n, p + p);
}
} else {
returnList.add(node);
}
}
/**
* 判断是否有子节点
*/
private static boolean hasChild(List<Menu> list, Menu t) {
return getChildList(list, t).size() > 0 ? true : false;
}
}
package com.sinobase.common.utils.bean;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Bean 工具类
*
* @author sinobase
*/
public class BeanUtils
{
/** Bean方法名中属性名开始的下标 */
private static final int BEAN_METHOD_PROP_INDEX = 3;
/** * 匹配getter方法的正则表达式 */
private static final Pattern GET_PATTERN = Pattern.compile("get(\\p{javaUpperCase}\\w*)");
/** * 匹配setter方法的正则表达式 */
private static final Pattern SET_PATTERN = Pattern.compile("set(\\p{javaUpperCase}\\w*)");
/**
* Bean属性复制工具方法。
*
* @param dest 目标对象
* @param src 源对象
*/
public static void copyBeanProp(Object dest, Object src)
{
List<Method> destSetters = getSetterMethods(dest);
List<Method> srcGetters = getGetterMethods(src);
try
{
for (Method setter : destSetters)
{
for (Method getter : srcGetters)
{
if (isMethodPropEquals(setter.getName(), getter.getName())
&& setter.getParameterTypes()[0].equals(getter.getReturnType()))
{
setter.invoke(dest, getter.invoke(src));
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 获取对象的setter方法。
*
* @param obj 对象
* @return 对象的setter方法列表
*/
public static List<Method> getSetterMethods(Object obj)
{
// setter方法列表
List<Method> setterMethods = new ArrayList<Method>();
// 获取所有方法
Method[] methods = obj.getClass().getMethods();
// 查找setter方法
for (Method method : methods)
{
Matcher m = SET_PATTERN.matcher(method.getName());
if (m.matches() && (method.getParameterTypes().length == 1))
{
setterMethods.add(method);
}
}
// 返回setter方法列表
return setterMethods;
}
/**
* 获取对象的getter方法。
*
* @param obj 对象
* @return 对象的getter方法列表
*/
public static List<Method> getGetterMethods(Object obj)
{
// getter方法列表
List<Method> getterMethods = new ArrayList<Method>();
// 获取所有方法
Method[] methods = obj.getClass().getMethods();
// 查找getter方法
for (Method method : methods)
{
Matcher m = GET_PATTERN.matcher(method.getName());
if (m.matches() && (method.getParameterTypes().length == 0))
{
getterMethods.add(method);
}
}
// 返回getter方法列表
return getterMethods;
}
/**
* 检查Bean方法名中的属性名是否相等。<br>
* 如getName()和setName()属性名一样,getName()和setAge()属性名不一样。
*
* @param m1 方法名1
* @param m2 方法名2
* @return 属性名一样返回true,否则返回false
*/
public static boolean isMethodPropEquals(String m1, String m2)
{
return m1.substring(BEAN_METHOD_PROP_INDEX).equals(m2.substring(BEAN_METHOD_PROP_INDEX));
}
}
package com.sinobase.common.utils.spring;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;
/**
* spring工具类 方便在非spring管理环境中获取bean
*
* @author sinobase
*/
@Component
public final class SpringUtils implements BeanFactoryPostProcessor
{
/** Spring应用上下文环境 */
private static ConfigurableListableBeanFactory beanFactory;
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException
{
SpringUtils.beanFactory = beanFactory;
}
/**
* 获取对象
*
* @param name
* @return Object 一个以所给名字注册的bean的实例
* @throws org.springframework.beans.BeansException
*
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException
{
return (T) beanFactory.getBean(name);
}
/**
* 获取类型为requiredType的对象
*
* @param clz
* @return
* @throws org.springframework.beans.BeansException
*
*/
public static <T> T getBean(Class<T> clz) throws BeansException
{
T result = (T) beanFactory.getBean(clz);
return result;
}
/**
* 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
*
* @param name
* @return boolean
*/
public static boolean containsBean(String name)
{
return beanFactory.containsBean(name);
}
/**
* 判断以给定名字注册的bean定义是一个singleton还是一个prototype。 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)
*
* @param name
* @return boolean
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
*
*/
public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException
{
return beanFactory.isSingleton(name);
}
/**
* @param name
* @return Class 注册对象的类型
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
*
*/
public static Class<?> getType(String name) throws NoSuchBeanDefinitionException
{
return beanFactory.getType(name);
}
/**
* 如果给定的bean名字在bean定义中有别名,则返回这些别名
*
* @param name
* @return
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
*
*/
public static String[] getAliases(String name) throws NoSuchBeanDefinitionException
{
return beanFactory.getAliases(name);
}
}
package com.sinobase.framework.aspectj.lang.annotation;
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 sinobase
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataScope
{
/**
* 表的别名
*/
public String tableAlias() default "";
}
package com.sinobase.framework.aspectj.lang.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 自定义导出Excel数据注解
*
* @author ruoyi
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Excel {
/**
* 导出到Excel中的名字.
*/
public String name() default "";
/**
* 日期格式, 如: yyyy-MM-dd
*/
public String dateFormat() default "";
/**
* 读取内容转表达式 (如: 0=男,1=女,2=未知)
*/
public String readConverterExp() default "";
/**
* 导出时在excel中每个列的高度 单位为字符
*/
public double height() default 14;
/**
* 导出时在excel中每个列的宽 单位为字符
*/
public double width() default 16;
/**
* 文字后缀,如% 90 变成90%
*/
public String suffix() default "";
/**
* 当值为空时,字段的默认值
*/
public String defaultValue() default "";
/**
* 提示信息
*/
public String prompt() default "";
/**
* 设置只能选择不能输入的列内容.
*/
public String[] combo() default {};
/**
* 是否导出数据,应对需求:有时我们需要导出一份模板,这是标题需要但内容需要用户手工填写.
*/
public boolean isExport() default true;
/**
* 另一个类中的属性名称,支持多级获取,以小数点隔开
*/
public String targetAttr() default "";
/**
* 字段类型(0:导出导入;1:仅导出;2:仅导入)
*/
Type type() default Type.ALL;
public enum Type {
ALL(0), EXPORT(1), IMPORT(2);
private final int value;
Type(int value) {
this.value = value;
}
public int value() {
return this.value;
}
}
}
\ No newline at end of file
package com.sinobase.framework.aspectj.lang.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Excel注解集
*
* @author ruoyi
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Excels {
Excel[] value();
}
\ No newline at end of file
package com.sinobase.framework.aspectj.lang.annotation;
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;
import com.sinobase.framework.aspectj.lang.enums.BusinessType;
import com.sinobase.framework.aspectj.lang.enums.OperatorType;
/**
* 自定义操作日志记录注解
*
* @author sinobase
*
*/
@Target({ ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log
{
/**
* 模块
*/
public String title() default "";
/**
* 功能
*/
public BusinessType businessType() default BusinessType.OTHER;
/**
* 操作人类别
*/
public OperatorType operatorType() default OperatorType.MANAGE;
/**
* 是否保存请求的参数
*/
public boolean isSaveRequestData() default true;
}
package com.sinobase.framework.aspectj.lang.enums;
/**
* 操作状态
*
* @author sinobase
*
*/
public enum BusinessStatus
{
/**
* 成功
*/
SUCCESS,
/**
* 失败
*/
FAIL,
}
package com.sinobase.framework.aspectj.lang.enums;
/**
* 业务操作类型
* @author sinobase
*
*/
public enum BusinessType{
/**
* 其它
*/
OTHER,
/**
* 新增
*/
INSERT,
/**
* 修改
*/
UPDATE,
/**
* 删除
*/
DELETE,
/**
* 授权
*/
GRANT,
/**
* 导出
*/
EXPORT,
/**
* 导入
*/
IMPORT,
/**
* 强退
*/
FORCE,
/**
* 生成代码
*/
GENCODE,
/**
* 清空数据
*/
CLEAN,
/**
* 查询
*/
QUERY,
/**
* 新增或修改
*/
SAVEORUPDATE,
}
package com.sinobase.framework.aspectj.lang.enums;
/**
* 操作人类别
*
* @author sinobase
*
*/
public enum OperatorType
{
/**
* 其它
*/
OTHER,
/**
* 后台用户
*/
MANAGE,
/**
* 手机端用户
*/
MOBILE
}
package com.sinobase.framework.web.domain;
import java.util.HashMap;
import java.util.Map;
import com.sinobase.common.utils.StringUtils;
/**
* 操作消息提醒
*/
public class AjaxResult extends HashMap<String, Object> {
private static final long serialVersionUID = 1L;
public static final String CODE_TAG = "code";
public static final String MSG_TAG = "msg";
public static final String DATA_TAG = "data";
/**
* 状态类型
*/
public enum Type {
/** 成功 */
SUCCESS(0),
/** 警告 */
WARN(301),
/** 错误 */
ERROR(500);
private final int value;
Type(int value) {
this.value = value;
}
public int value() {
return this.value;
}
}
/** 状态类型 */
private Type type;
/** 状态码 */
private int code;
/** 返回内容 */
private String msg;
/** 数据对象 */
private Object data;
/**
* 初始化一个新创建的 AjaxResult 对象,使其表示一个空消息。
*/
public AjaxResult() {
}
/**
* 初始化一个新创建的 AjaxResult 对象
*
* @param type 状态类型
* @param msg 返回内容
*/
public AjaxResult(Type type, String msg) {
super.put(CODE_TAG, type.value);
super.put(MSG_TAG, msg);
}
/**
* 初始化一个新创建的 AjaxResult 对象
*
* @param type 状态类型
* @param msg 返回内容
* @param data 数据对象
*/
public AjaxResult(Type type, String msg, Object data) {
super.put(CODE_TAG, type.value);
super.put(MSG_TAG, msg);
if (StringUtils.isNotNull(data)) {
super.put(DATA_TAG, data);
}
}
/**
* 返回错误消息
*
* @return 错误消息
*/
public static AjaxResult error() {
return error(1, "操作失败");
}
/**
* 返回错误消息
*
* @param msg 内容
* @return 错误消息
*/
public static AjaxResult error(String msg) {
return error(500, msg);
}
/**
* 返回错误消息
*
* @param code 错误码
* @param msg 内容
* @return 错误消息
*/
public static AjaxResult error(int code, String msg) {
AjaxResult json = new AjaxResult();
json.put("code", code);
json.put("msg", msg);
return json;
}
/**
* 返回成功数据
* @return 成功消息
*/
public static AjaxResult success(Object data) {
return AjaxResult.success("操作成功", data);
}
/**
* 返回成功消息
* @param msg 内容
* @return 成功消息
*/
public static AjaxResult success(String msg) {
AjaxResult json = new AjaxResult();
json.put("msg", msg);
json.put("code", 0);
return json;
}
/**
* 返回成功消息
*
* @param msg 内容
* @param map 返回的数据对象
* @return 成功消息 + data
*/
public static AjaxResult success(String msg, Map<String, Object> map) {
AjaxResult json = new AjaxResult();
json.put("msg", msg);
json.put("code", 0);
json.put("data", map);
return json;
}
/**
* 返回成功消息
*
* @param msg 返回内容
* @param data 数据对象
* @return 成功消息
*/
public static AjaxResult success(String msg, Object data) {
return new AjaxResult(Type.SUCCESS, msg, data);
}
/**
* 返回成功消息
*
* @return 成功消息
*/
public static AjaxResult success() {
return AjaxResult.success("操作成功");
}
/**
* 返回成功消息
*
* @param key 键值
* @param value 内容
* @return 成功消息
*/
@Override
public AjaxResult put(String key, Object value) {
super.put(key, value);
return this;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
package com.sinobase.framework.web.domain;
import java.io.Serializable;
import java.util.Date;
import java.util.Map;
import com.baomidou.mybatisplus.annotation.TableField;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.google.common.collect.Maps;
/**
* Entity基类
*/
public class BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
/** 搜索值 */
@TableField(exist=false)
private String searchValue;
/** 创建者 */
@TableField(exist=false)
private String createBy;
/** 创建时间 */
@TableField(exist=false)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
/** 更新者 */
@TableField(exist=false)
private String updateBy;
/** 更新时间 */
@TableField(exist=false)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")//因为我们是东八区(北京时间),所以在格式化的时候要指定时区(timezone )
private Date updateTime;
/** 备注 */
@TableField(exist=false)
private String remark;
/** 请求参数 */
@TableField(exist=false)
private Map<String, Object> params;
/**请求类型*/
@TableField(exist=false)
private String requestType;
public String getSearchValue() {
return searchValue;
}
public void setSearchValue(String searchValue) {
this.searchValue = searchValue;
}
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public Map<String, Object> getParams() {
if (params == null) {
params = Maps.newHashMap();
}
return params;
}
public void setParams(Map<String, Object> params) {
this.params = params;
}
public String getRequestType() {
return requestType;
}
public void setRequestType(String requestType) {
this.requestType = requestType;
}
}
package com.sinobase.framework.web.domain;
import java.util.Date;
public class FlowBaseEntity {
/** 创建人 */
private String creUserId;
/** 创建人名称 */
private String creUserName;
/** 创建部门id */
private String creDeptId;
/** 创建部门名称 */
private String creDeptName;
/** 创建日志 */
private Date creDate;
/** 流程标识 */
private String subflag;
/** 流程类型 */
private String flowType;
public void setCreUserId(String creUserId){
this.creUserId = creUserId;
}
public String getCreUserId(){
return creUserId;
}
public void setCreUserName(String creUserName){
this.creUserName = creUserName;
}
public String getCreUserName(){
return creUserName;
}
public void setCreDeptId(String creDeptId){
this.creDeptId = creDeptId;
}
public String getCreDeptId(){
return creDeptId;
}
public void setCreDeptName(String creDeptName){
this.creDeptName = creDeptName;
}
public String getCreDeptName(){
return creDeptName;
}
public void setCreDate(Date creDate){
this.creDate = creDate;
}
public Date getCreDate(){
return creDate;
}
public void setSubflag(String subflag){
this.subflag = subflag;
}
public String getSubflag(){
return subflag;
}
public String getFlowType() {
return flowType;
}
public void setFlowType(String flowType) {
this.flowType = flowType;
}
}
package com.sinobase.framework.web.domain;
import java.io.Serializable;
/**
* Ztree树结构实体类
*/
public class Ztree implements Serializable {
private static final long serialVersionUID = 1L;
/** 节点ID */
private Long id;
/** 节点父ID */
private Long pId;
/** 节点名称 */
private String name;
/** 节点标题 */
private String title;
/** 是否勾选 */
private boolean checked = false;
/** 是否展开 */
private boolean open = false;
/** 是否能勾选 */
private boolean nocheck = false;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getpId() {
return pId;
}
public void setpId(Long pId) {
this.pId = pId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public boolean isOpen() {
return open;
}
public void setOpen(boolean open) {
this.open = open;
}
public boolean isNocheck() {
return nocheck;
}
public void setNocheck(boolean nocheck) {
this.nocheck = nocheck;
}
}
package com.sinobase.framework.web.mapper;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
public interface BaseMapper<T> extends com.baomidou.mybatisplus.core.mapper.BaseMapper<T>{
/**
* 分页列表
* @param queryWrapper
* @return
*/
public List<T> selectPageList(Wrapper<T> queryWrapper);
}
package com.sinobase.framework.web.page;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.List;
/**
* 接口返回数据
*
* @author Mikasa33
*/
@ApiModel
public class ApiData<T> implements Serializable
{
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "状态码")
private Integer code;
@ApiModelProperty(value = "返回信息")
private String msg;
@ApiModelProperty("返回数据")
private T data; // 数据
public ApiData(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public static<T> ApiData info(Integer code, String msg, T data) {
ApiData api = new ApiData(code, msg);
api.setData(data);
return api;
}
public static ApiData info(Integer code, String msg) {
ApiData api = new ApiData(code, msg);
return api;
}
public static<T> ApiData success(T data) {
ApiData api = new ApiData(0, "success");
api.setData(data);
return api;
}
public static<T> ApiData fail(T data) {
ApiData api = new ApiData(500, "error");
api.setData(data);
return api;
}
public static ApiData success() {
ApiData api = new ApiData(200, "success");
return api;
}
public static ApiData fail() {
ApiData api = new ApiData(500, "error");
return api;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
package com.sinobase.framework.web.page;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
/**
* 接口返回列表数据
*
* @author Mikasa33
*/
@ApiModel
public class PageData<T> implements Serializable
{
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "总页数")
private long total;
@ApiModelProperty("返回数据")
private T list;
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
public T getList() {
return list;
}
public void setList(T list) {
this.list = list;
}
}
package com.sinobase.framework.web.page;
import com.sinobase.common.utils.StringUtils;
/**
* 分页数据
*
* @author sinobase
*/
public class PageDomain
{
/** 当前记录起始索引 */
private Integer pageNum;
/** 每页显示记录数 */
private Integer pageSize;
/** 排序列 */
private String orderByColumn;
/** 排序的方向 "desc" 或者 "asc". */
private String isAsc;
public String getOrderBy()
{
if (StringUtils.isEmpty(orderByColumn))
{
return "";
}
return StringUtils.toUnderScoreCase(orderByColumn) + " " + isAsc;
}
public Integer getPageNum()
{
return pageNum;
}
public void setPageNum(Integer pageNum)
{
this.pageNum = pageNum;
}
public Integer getPageSize()
{
return pageSize;
}
public void setPageSize(Integer pageSize)
{
this.pageSize = pageSize;
}
public String getOrderByColumn()
{
return orderByColumn;
}
public void setOrderByColumn(String orderByColumn)
{
this.orderByColumn = orderByColumn;
}
public String getIsAsc()
{
return isAsc;
}
public void setIsAsc(String isAsc)
{
this.isAsc = isAsc;
}
}
package com.sinobase.framework.web.page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* 表格分页数据对象
*
* @author sinobase
*/
public class TableDataInfo implements Serializable
{
private static final long serialVersionUID = 1L;
/** 总记录数 */
private long total;
/** 列表数据 */
private List<?> rows;
/** 消息状态码 */
private int code;
/**
* 表格数据对象
*/
public TableDataInfo()
{
}
/**
* 分页
*
* @param list 列表数据
* @param total 总记录数
*/
public TableDataInfo(List<?> list, int total)
{
this.rows = list;
this.total = total;
}
public long getTotal()
{
return total;
}
public void setTotal(long total)
{
this.total = total;
}
public List<?> getRows()
{
return rows;
}
public void setRows(List<?> rows)
{
this.rows = rows;
}
public int getCode()
{
return code;
}
public void setCode(int code)
{
this.code = code;
}
public TableDataInfo(IPage<?> page){
this.total = 0;
this.rows = new ArrayList<>();
this.code = 0;
if(page!=null){
this.total = page.getTotal();
this.rows = page.getRecords();
}
}
}
package com.sinobase.framework.web.page;
import com.sinobase.common.utils.ServletUtils;
import com.sinobase.common.constant.Constants;
/**
* 表格数据处理
*
* @author sinobase
*/
public class TableSupport {
/**
* 封装分页对象
*/
public static PageDomain getPageDomain() {
PageDomain pageDomain = new PageDomain();
pageDomain.setPageNum(ServletUtils.getParameterToInt(Constants.PAGE_NUM));
pageDomain.setPageSize(ServletUtils.getParameterToInt(Constants.PAGE_SIZE));
pageDomain.setOrderByColumn(ServletUtils.getParameter(Constants.ORDER_BY_COLUMN));
pageDomain.setIsAsc(ServletUtils.getParameter(Constants.IS_ASC));
return pageDomain;
}
public static PageDomain buildPageRequest() {
return getPageDomain();
}
}
package com.sinobase.project.system.dept.constant;
public class DeptConstants {
/**
* 系统信息状态:集团公司id
*/
public static String GTOUP_ID = "162812";
/**
* 系统信息状态:集团公司history_id
*/
public static String GTOUP_HISTORY_ID = "001";
}
package com.sinobase.project.system.dept.domain;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.baomidou.mybatisplus.annotation.TableField;
import com.sinobase.framework.web.domain.BaseEntity;
/**
* 部门表 sys_dept
*
* @author sinobase
*/
public class Dept extends BaseEntity {
private static final long serialVersionUID = 1L;
/**
* 职能部门
*/
public static String DEPT_UNIT_TYPE_01 = "01"; //集团
/**
* 职能部门
*/
public static String DEPT_UNIT_TYPE_02 = "02"; //职能部门
/**
* 二级公司
*/
public static String DEPT_UNIT_TYPE_03 = "03"; //二级公司
/**
* 三级公司
*/
public static String DEPT_UNIT_TYPE_04 = "04"; //三级公司
/**
* 四级公司
*/
public static String DEPT_UNIT_TYPE_05 = "05"; //四级公司
/**
* 公司类型字符串Company
*/
public static String DEPT_UNIT_TYPE_COMPANY = "03,04,05"; //公司类型字符串
/** 部门ID */
private String deptId;
/** 父部门ID */
private String parentId;
/** 祖级列表 */
private String ancestors;
/** 部门名称 */
private String deptName;
/** 显示顺序 */
private Long orderNum;
/** 负责人 */
private String leader;
/** 联系电话 */
private String phone;
/** 邮箱 */
private String email;
/** 部门状态:1正常,0停用 */
private String status;
/** 删除标志(0代表存在 2代表删除) */
private String delFlag;
/** 父部门名称 */
private String parentName;
/**
* fromUnit 类别(公司或部门)
* @return
*/
private String fromUnit;
/**
* 部门编号
* @return
*/
private String deptNumber;
/** 备注 */
private String note;
/**
* 国泰历史数据ID
* @return
*/
private String historyId;
/**
* 历史公司ID
*/
private String historyCompanyId;
/**
* 用户所在老OA大部门id,主要指老OA集团的职能部门
*/
private String historyCompanyIdDept;
/** 国泰历史数据编码 */
private String historyCode;
/** 单元类型 */
private String unitType;
/** 是否为领导部门 */
private String isZhc;
/**
* 所在公司id
*/
private String companyId;
/**
* 所在公司名称
*/
private String companyName;
/**
* 公司简称
*/
@TableField(exist = false)
private String companyShortName;
/**
* 主数据部门编码
*/
private String deptcode;
/**
* 主数据公司编码
*/
private String companycode;
/**
* 主数据父部门编码
*/
private String supercode;
/**
* 部门树的显示状态,0任何树都显示,其他表示根据实际情况判断是否在树结构上显示
*/
private String isShow;
/**
* 单位属性:全资,控股等
*/
private String deptProperty;
/**
* 部门简称,树结构一般显示简称
*/
private String deptShort;
/**
* 部门层级
*/
private String deptLevel;
/**
* 用户所在大部门id,主要指集团的职能部门
*/
private String companyIdDept;
/**
*用户所在大部门名称
*/
private String companyNameDept;
/**
*用户所在大部门简称
*/
@TableField(exist = false)
private String companyShortNameDept;
private String hasChildren;
/**
* 子部门集合
*/
@TableField(exist = false)
private String childDeptIds;
public String getHasChildren() {
return hasChildren;
}
public void setHasChildren(String hasChildren) {
this.hasChildren = hasChildren;
}
public String getDeptcode() {
return deptcode;
}
public void setDeptcode(String deptcode) {
this.deptcode = deptcode;
}
public String getCompanycode() {
return companycode;
}
public void setCompanycode(String companycode) {
this.companycode = companycode;
}
public String getSupercode() {
return supercode;
}
public void setSupercode(String supercode) {
this.supercode = supercode;
}
public String getIsShow() {
return isShow;
}
public void setIsShow(String isShow) {
this.isShow = isShow;
}
public String getDeptProperty() {
return deptProperty;
}
public void setDeptProperty(String deptProperty) {
this.deptProperty = deptProperty;
}
public String getDeptShort() {
return deptShort;
}
public void setDeptShort(String deptShort) {
this.deptShort = deptShort;
}
public String getDeptLevel() {
return deptLevel;
}
public void setDeptLevel(String deptLevel) {
this.deptLevel = deptLevel;
}
public String getCompanyId() {
return companyId;
}
public void setCompanyId(String companyId) {
this.companyId = companyId;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getIsZhc() {
return isZhc;
}
public void setIsZhc(String isZhc) {
this.isZhc = isZhc;
}
public String getDeptId() {
return deptId;
}
public void setDeptId(String deptId) {
this.deptId = deptId;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public String getAncestors() {
return ancestors;
}
public void setAncestors(String ancestors) {
this.ancestors = ancestors;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public Long getOrderNum() {
return orderNum;
}
public void setOrderNum(Long orderNum) {
this.orderNum = orderNum;
}
public String getLeader() {
return leader;
}
public void setLeader(String leader) {
this.leader = leader;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getDelFlag() {
return delFlag;
}
public void setDelFlag(String delFlag) {
this.delFlag = delFlag;
}
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
public String getFromUnit() {
return fromUnit;
}
public void setFromUnit(String fromUnit) {
this.fromUnit = fromUnit;
}
public String getDeptNumber() {
return deptNumber;
}
public void setDeptNumber(String deptNumber) {
this.deptNumber = deptNumber;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public String getHistoryId() {
return historyId;
}
public void setHistoryId(String historyId) {
this.historyId = historyId;
}
public String getHistoryCompanyId() {
return historyCompanyId;
}
public void setHistoryCompanyId(String historyCompanyId) {
this.historyCompanyId = historyCompanyId;
}
public String getHistoryCompanyIdDept() {
return historyCompanyIdDept;
}
public void setHistoryCompanyIdDept(String historyCompanyIdDept) {
this.historyCompanyIdDept = historyCompanyIdDept;
}
public String getHistoryCode() {
return historyCode;
}
public void setHistoryCode(String historyCode) {
this.historyCode = historyCode;
}
public String getUnitType() {
return unitType;
}
public void setUnitType(String unitType) {
this.unitType = unitType;
}
public String getCompanyIdDept() {
return companyIdDept;
}
public void setCompanyIdDept(String companyIdDept) {
this.companyIdDept = companyIdDept;
}
public String getCompanyNameDept() {
return companyNameDept;
}
public void setCompanyNameDept(String companyNameDept) {
this.companyNameDept = companyNameDept;
}
public String getCompanyShortName() {
return companyShortName;
}
public void setCompanyShortName(String companyShortName) {
this.companyShortName = companyShortName;
}
public String getCompanyShortNameDept() {
return companyShortNameDept;
}
public void setCompanyShortNameDept(String companyShortNameDept) {
this.companyShortNameDept = companyShortNameDept;
}
public String getChildDeptIds() {
return childDeptIds;
}
public void setChildDeptIds(String childDeptIds) {
this.childDeptIds = childDeptIds;
}
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE).append("deptId", getDeptId()).append("parentId", getParentId()).append("ancestors", getAncestors())
.append("deptName", getDeptName()).append("orderNum", getOrderNum()).append("leader", getLeader()).append("phone", getPhone()).append("email", getEmail()).append("status", getStatus())
.append("delFlag", getDelFlag()).append("createBy", getCreateBy()).append("createTime", getCreateTime()).append("updateBy", getUpdateBy()).append("updateTime", getUpdateTime())
.append("fromUnit", getFromUnit()).append("note", getNote()).append("historyId", getHistoryId()).append("deptNumber", getDeptNumber()).append("historyCode", getHistoryCode())
.append("deptcode", getDeptcode()).append("companyId", getCompanyId()).append("companycode", getCompanycode()).append("supercode", getSupercode()).append("isShow", getIsShow())
.append("deptProperty", getDeptProperty()).append("deptShort", getDeptShort()).append("deptLevel", getDeptLevel()).append("companyName", getCompanyName())
.append("unitType", getUnitType()).append("isZhc", getIsZhc()).toString();
}
}
package com.sinobase.project.system.dept.domain;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.sinobase.framework.web.domain.BaseEntity;
/**
* 部门权限表 sys_dept_permission
*
* @author LouBin
* @date 2019-07-29
*/
public class DeptPermission {
private static final long serialVersionUID = 1L;
/** 主键 */
private String id;
/** 属性 */
private String property;
/** 部门级别 */
private String deptlevel;
/** 是否显示 */
private String isshow;
/** 部门权限 */
private String deptPermission;
/** 流程权限 */
private String flowPermission;
/**创建时间**/
private String createTime;
public void setId(String id){
this.id = id;
}
public String getId(){
return id;
}
public void setProperty(String property){
this.property = property;
}
public String getProperty(){
return property;
}
public void setDeptlevel(String deptlevel){
this.deptlevel = deptlevel;
}
public String getDeptlevel(){
return deptlevel;
}
public void setIsshow(String isshow){
this.isshow = isshow;
}
public String getIsshow(){
return isshow;
}
public void setDeptPermission(String deptPermission){
this.deptPermission = deptPermission;
}
public String getDeptPermission(){
return deptPermission;
}
public void setFlowPermission(String flowPermission){
this.flowPermission = flowPermission;
}
public String getFlowPermission(){
return flowPermission;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("id", getId())
.append("property", getProperty())
.append("deptlevel", getDeptlevel())
.append("isshow", getIsshow())
.append("deptPermission", getDeptPermission())
.append("flowPermission", getFlowPermission())
.append("createTime", getCreateTime())
.toString();
}
}
package com.sinobase.project.system.dept.mapper;
import com.sinobase.datasource.aspectj.lang.annotation.DataSource;
import com.sinobase.datasource.aspectj.lang.enums.DataSourceType;
import com.sinobase.project.system.dept.domain.Dept;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* 部门管理 数据层
*
* @author sinobase
*/
public interface DeptMapper {
/**
* 查询部门人数
* @param dept 部门信息
* @return 结果
*/
public int selectDeptCount(Dept dept);
/**
* 查询部门是否存在用户
* @param deptId 部门ID
* @return 结果
*/
public int checkDeptExistUser(String deptId);
/**
* 查询部门管理数据
* @param dept 部门信息
* @return 部门信息集合
*/
public List<Dept> selectDeptList(Dept dept);
/**
* 数据列表 ==》后台管理
*/
public List<Dept> listForManage(Dept dept);
/**
* 删除部门管理信息
* @param deptId 部门ID
* @return 结果
*/
public int deleteDeptById(String deptId);
/**
* 新增部门信息
* @param dept 部门信息
* @return 结果
*/
public int insertDept(Dept dept);
/**
* 部门排序保存
* @param deptIds 部门id串
* @return
*/
public int sortSave(String[] deptIds);
/**
* 修改部门信息
* @param dept 部门信息
* @return 结果
*/
public int updateDept(Dept dept);
/**
* 修改子元素关系
* @param depts 子元素
* @return 结果
*/
public int updateDeptChildren(@Param("depts") List<Dept> depts);
/**
* 根据部门ID查询信息
* @param deptId 部门ID
* @return 部门信息
*/
public Dept selectDeptById(String deptId);
/**
* 校验部门名称是否唯一
*
* @param deptName 部门名称
* @param parentId 父部门ID
* @return 结果
*/
public Dept checkDeptNameUnique(@Param("deptName") String deptName, @Param("parentId") String parentId);
/**
* 根据角色ID查询部门
*
* @param roleId 角色ID
* @return 部门列表
*/
public List<String> selectRoleDeptTree(String roleId);
/**
* 修改所在部门的父级部门状态
*
* @param dept 部门
*/
public void updateDeptStatus(Dept dept);
/**
* 根据部门对象集合添加部门
* @param deptList
*/
public Integer insertDeptList(List<Dept> deptList);
/**
* 获取本地数据库所有部门的id
* @return
*/
public List<String> selectAllDeptId();
/**
* 查询所有部门信息
* @return
*/
public List<Dept> selectAllDept();
/**
* 根据部门id获取子部门
* @param deptId
* @return
*/
public List<Dept> selectDeptListByDeptId(@Param(value = "deptId") String deptId);
/**
* 根据部门id获取其所有子孙部门
* @param deptId
* @return
*/
public List<Dept> selectDeptListsByDeptId(@Param(value = "deptId")String deptId);
/**
* 根据部门id和权限获取部门信息
* @param auth
* @return
*/
public List<Dept> selectDeptListByDeptIdAndAuthority(@Param(value = "auth")Map<String,String> auth);
/**
* 通过sql插入信息
* @param sql
* @return
*/
public int insertDeptBySql(@Param(value = "sql") String sql);
/**
* 通过sql查询信息
* @param sql
* @return
*/
public Map<String,String> selectBySql(@Param(value = "sql") String sql);
/**
* 通过sql查询信息,获取多条数据
* @param sql
* @return
*/
public List<Map<String,String>> selectAllBySql(@Param(value = "sql") String sql);
public List<Dept> selectDeptListByPID(String parentID);
/**
* 根据部门id获取顶级部门(公司)信息
* @param deptId
* @return
*/
public Dept getCompanyId(String deptId);
/**
* 根据部门ID数组获取部门列表
* @param ids
* @return
*/
List<Dept> listDeptByDeptId(String [] ids);
/**
* 根据用户ID获取部门信息
* @param userId 用户id
* @return
*/
public List<Dept> getDeptsByUserId(String userId);
/**
* 获取当前表最大ID值
* @return
*/
public int selectMaxId();
/**
* 过去符合条件的当前部门的所有子部门
*
* @param auth
* @return
*/
public List<Map<String,Object>> getAllChildrenDept(@Param(value = "auth")Map<String,String> auth);
/**
* 根据祖级列表模糊查询部门
*
*/
public List<Dept> getDeptLikeAncestors(@Param(value = "ancestors")String ancestors);
/**
* 根据部门名称获取部门列表
* @param deptName
* @return
*/
List<Dept> listDeptForDeptName(@Param(value = "deptName") String deptName);
/**
* 获取二级子公司(from_unit = 0)
* @param ancestors
* @return
*/
Dept getDeptByAncestors(@Param("ancestors") String ancestors);
/**
* 根据类别(0:子公司 1:部门)获取dept信息
* @param fromUnit
* @return
*/
List<Dept> getDeptByFromUnit(@Param("fromUnit") String fromUnit);
/**
* 获取老OA的部门信息
* @param historyId
* @return
*/
@DataSource(DataSourceType.ORACLE)
Map<String,String> getOldDeptInfo(@Param("historyId") String historyId);
/**
* 根据部门Id获取部门名称
* @param deptIds
* @return
*/
public List<String> getDeptNamesByDeptIds(String[] deptIds);
/**
* 据类别(0:子公司 1:部门)获取dept信息(返回内容包含子部门数据)
* @param fromUnit
* @return
*/
public List<Dept> getDeptByFromUnit_childDpetIds(@Param("fromUnit")String fromUnit);
}
package com.sinobase.project.system.dept.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSONObject;
import com.sinobase.common.constant.UserConstants;
import com.sinobase.common.exception.BusinessException;
import com.sinobase.common.utils.StringUtils;
import com.sinobase.datasource.aspectj.lang.annotation.DataSource;
import com.sinobase.datasource.aspectj.lang.enums.DataSourceType;
import com.sinobase.framework.aspectj.lang.annotation.DataScope;
import com.sinobase.framework.aspectj.lang.annotation.Log;
import com.sinobase.framework.aspectj.lang.enums.BusinessType;
import com.sinobase.project.system.dept.domain.Dept;
import com.sinobase.project.system.dept.mapper.DeptMapper;
import com.sinobase.project.system.role.domain.Role;
/**
* 部门管理 服务实现
*
* @author sinobase
*/
@Service
public class DeptServiceImpl implements IDeptService {
@Autowired
private DeptMapper deptMapper;
@Value("${environment}")
private String environment;
/**
* 查询部门管理数据
* @param dept 部门信息
* @return 部门信息集合
*/
@Override
@DataScope(tableAlias = "d")
public List<Dept> selectDeptList(Dept dept) {
return deptMapper.listForManage(dept);
}
public List<Map<String, Object>> treeForManage(){
return getTrees(deptMapper.listForManage(new Dept()), false, null);
}
/**
* 查询部门管理树
* @param dept 部门信息
* @return 所有部门信息
*/
@Override
@DataScope(tableAlias = "d")
public List<Map<String, Object>> selectDeptTree(Dept dept) {
List<Map<String, Object>> trees = new ArrayList<Map<String, Object>>();
List<Dept> deptList = deptMapper.selectDeptList(dept);
trees = getTrees(deptList, false, null);
return trees;
}
/**
* 根据角色ID查询部门(数据权限)
*
* @param role 角色对象
* @return 部门列表(数据权限)
*/
@Override
public List<Map<String, Object>> roleDeptTreeData(Role role) {
String roleId = role.getRoleId();
List<Map<String, Object>> trees = new ArrayList<Map<String, Object>>();
List<Dept> deptList = selectDeptList(new Dept());
if (StringUtils.isNotNull(roleId)) {
List<String> roleDeptList = deptMapper.selectRoleDeptTree(roleId);
trees = getTrees(deptList, true, roleDeptList);
} else {
trees = getTrees(deptList, false, null);
}
return trees;
}
/**
* 对象转部门树
*
* @param deptList 部门列表
* @param isCheck 是否需要选中
* @param roleDeptList 角色已存在菜单列表
* @return
*/
public List<Map<String, Object>> getTrees(List<Dept> deptList, boolean isCheck, List<String> roleDeptList) {
List<Map<String, Object>> trees = new ArrayList<Map<String, Object>>();
for (Dept dept : deptList) {
if (UserConstants.DEPT_NORMAL.equals(dept.getStatus())) {
Map<String, Object> deptMap = new HashMap<String, Object>();
deptMap.put("id", dept.getDeptId());
deptMap.put("pId", dept.getParentId());
deptMap.put("historyId",dept.getHistoryId());
deptMap.put("name", dept.getDeptName());
deptMap.put("title", dept.getDeptName());
if (isCheck) {
deptMap.put("checked", roleDeptList.contains(dept.getDeptId() + dept.getDeptName()));
} else {
deptMap.put("checked", false);
}
trees.add(deptMap);
}
}
return trees;
}
/**
* 查询部门人数
* @param parentId 部门ID
* @return 结果
*/
@Override
public int selectDeptCount(String parentId) {
Dept dept = new Dept();
dept.setParentId(parentId);
return deptMapper.selectDeptCount(dept);
}
/**
* 查询部门是否存在用户
*
* @param deptId 部门ID
* @return 结果 true 存在 false 不存在
*/
@Override
public boolean checkDeptExistUser(String deptId) {
int result = deptMapper.checkDeptExistUser(deptId);
return result > 0 ? true : false;
}
/**
* 删除部门管理信息
*
* @param deptId 部门ID
* @return 结果
*/
@Override
@Log(title = "部门管理", businessType = BusinessType.DELETE)
public int deleteDeptById(String deptId) {
return deptMapper.deleteDeptById(deptId);
}
/**
* 新增保存部门信息
*
* @param dept 部门信息
* @return 结果
*/
@Override
@Log(title = "部门管理", businessType = BusinessType.INSERT)
public int insertDept(Dept dept) {
Dept info = deptMapper.selectDeptById(dept.getParentId());
// 如果父节点不为"正常"状态,则不允许新增子节点
if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
throw new BusinessException("部门停用,不允许新增");
}
//TODO 获取名称信息,暂时取消在controller中调用
//dept.setCreateBy(ShiroUtils.getLoginName());
dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
return deptMapper.insertDept(dept);
}
/**
* 修改保存部门信息
*
* @param dept 部门信息
* @return 结果
*/
@Override
@Log(title = "部门管理", businessType = BusinessType.UPDATE)
public int updateDept(Dept dept) {
Dept info = deptMapper.selectDeptById(dept.getParentId());
if (StringUtils.isNotNull(info)) {
String ancestors = info.getAncestors() + "," + info.getDeptId();
dept.setAncestors(ancestors);
updateDeptChildren(dept.getDeptId(), ancestors);
}
//TODO 获取名称信息,暂时取消在controller中调用
//dept.setUpdateBy(ShiroUtils.getLoginName());
int result = deptMapper.updateDept(dept);
if (UserConstants.DEPT_NORMAL.equals(dept.getStatus())) {
// 如果该部门是启用状态,则启用该部门的所有上级部门
updateParentDeptStatus(dept);
}
return result;
}
/**
* 修改该部门的父级部门状态
* @param dept 当前部门
*/
private void updateParentDeptStatus(Dept dept) {
String updateBy = dept.getUpdateBy();
dept = deptMapper.selectDeptById(dept.getDeptId());
dept.setUpdateBy(updateBy);
deptMapper.updateDeptStatus(dept);
}
/**
* 修改子元素关系
* @param deptId 部门ID
* @param ancestors 元素列表
*/
public void updateDeptChildren(String deptId, String ancestors) {
Dept dept = new Dept();
dept.setParentId(deptId);
List<Dept> childrens = deptMapper.selectDeptList(dept);
for (Dept children : childrens) {
children.setAncestors(ancestors + "," + dept.getParentId());
}
if (childrens.size() > 0) {
deptMapper.updateDeptChildren(childrens);
}
}
/**
* 根据部门ID查询信息(包含部门所有的公司id,名称)
* @param deptId 部门ID
* @return 部门信息
*/
@Override
public Dept selectDeptById(String deptId) {
Dept dept = deptMapper.selectDeptById(deptId);
Dept company = getCompanyByParentId(dept.getParentId());
dept.setCompanyShortName(company.getDeptShort());
dept.setCompanyId(company.getDeptId());
dept.setCompanyName(company.getDeptName());
//历史公司ID(非外网情况去查询老部门ID)
if(StringUtils.isNotEmpty(environment)&&!environment.equals("extranet")){
String historyCompanyId = this.getHistoryCompanyId(dept.getHistoryId());
dept.setHistoryCompanyId(historyCompanyId);
}
//历史companyIdDept
String historyCompanyIdDept = "";
if(StringUtils.isNotEmpty(dept.getHistoryId()) && dept.getHistoryId().length()>6){
historyCompanyIdDept = dept.getHistoryId().substring(0,6);
}else{
historyCompanyIdDept = dept.getHistoryId();
}
dept.setHistoryCompanyIdDept(historyCompanyIdDept);
return dept;
}
/**
* 根据部门ID查询信息(不含部门所有的公司id,名称)
* @param deptId 部门ID
* @return 部门信息
*/
@Override
public Dept selectDeptByIdNoCompany(String deptId) {
Dept dept = deptMapper.selectDeptById(deptId);
return dept;
}
/**
* 校验部门名称是否唯一
* @param dept 部门信息
* @return 结果
*/
@Override
public String checkDeptNameUnique(Dept dept) {
String deptId = StringUtils.isNull(dept.getDeptId()) ? "-1" : dept.getDeptId();
Dept info = deptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId());
if (StringUtils.isNotNull(info) && !info.getDeptId().equals(deptId)) {
return UserConstants.DEPT_NAME_NOT_UNIQUE;
}
return UserConstants.DEPT_NAME_UNIQUE;
}
public List<Dept> getDeptsByUserId(String userId) {
List<Dept> depts = deptMapper.getDeptsByUserId(userId);
for (Dept dept : depts) {
String companyId="companyId",companyName="系统管部门";
if(!userId.equals("1")){
Dept item = getCompanyByParentId(dept.getParentId());
companyId = item.getDeptId();
companyName = item.getDeptName();
}
dept.setCompanyId(companyId);
dept.setCompanyName(companyName);
}
return depts;
}
/**
* 根据部门父级id获取部门所在的公司
* @param parentId
* @return
*/
public Dept getCompanyByParentId(String parentId){
Dept dept = new Dept();
if(StringUtils.isNotEmpty(parentId) && !"0".equals(parentId)){
dept = deptMapper.selectDeptById(parentId);
String unitType = dept.getUnitType()==null?"":dept.getUnitType();
if(Dept.DEPT_UNIT_TYPE_COMPANY.indexOf(unitType) < 0 && !Dept.DEPT_UNIT_TYPE_01.equals(unitType)){
dept = getCompanyByParentId(dept.getParentId());
}
}
return dept;
}
/******************************** 添加的代码 *******************************/
/**
* 根据部门对象集合添加部门
*
* @return 结果
*/
@Override
@Transactional
public Integer insertDeptList(List<Dept> deptList) {
return deptMapper.insertDeptList(deptList);
}
/**
* 获取本地数据库所有部门的id
*
* @return
*/
@Override
@Transactional
public List<String> selectAllDeptId() {
return deptMapper.selectAllDeptId();
}
/**
* 查询所有部门信息
*
* @return
*/
@Override
public List<Dept> selectAlldept() {
return deptMapper.selectAllDept();
}
/**
* 获取子部门信息
* @param rootId
* @return
*/
@Override
public List<Dept> selectDeptListByDeptId(String rootId) {
return deptMapper.selectDeptListByDeptId(rootId);
}
/**
* 根据部门id获取其所有子孙部门
* @param deptId
* @return
*/
@Override
public List<Dept> selectDeptListsByDeptId(String deptId) {
return deptMapper.selectDeptListsByDeptId(deptId);
}
/**
* 获取部门树信息
* @param deptId
* @return
*/
@Override
public List<Map<String, Object>> getDeptTree(String deptId) {
List<Dept> deptList = deptMapper.selectDeptListsByDeptId(deptId);
List<Map<String, Object>> list = new LinkedList<Map<String, Object>>();
for (Dept dept : deptList) {
Map<String, Object> map = new HashMap<String, Object>();
//获取部门下的用户信息
map.put("id", dept.getDeptId());
map.put("historyId", dept.getHistoryId());
map.put("parentId", dept.getParentId());
map.put("name", dept.getDeptName());
map.put("fromUnit", dept.getFromUnit());
map.put("hasChildren", dept.getHasChildren());
list.add(map);
}
return list;
}
/**
* 获取部门树信息
* @param rootId 根节点部门 id
* @param deptId 部门 id
* @authority 部门权限信息
* @returndeptId
*/
@Override
public List getDeptTree(String rootId, String deptId, JSONObject authority) {
String id = null;
if (deptId != null && !"".equals(deptId)) {
id = deptId;
} else {
id = rootId;
}
Map<String,String> auth = new HashMap<String, String>();
auth.put("deptId", id);
if(authority!=null) {
auth.put("property", authority.getString("authority"));
auth.put("deptlevel", authority.getString("deptlevel"));
auth.put("isshow", authority.getString("isshow"));
}
Map<String,Object> res = new LinkedHashMap<String,Object>();
if (deptId == null || "".equals(deptId)) {
//获取部门信息
Dept dept = deptMapper.selectDeptById(id);
if(dept!=null) {
res.put("id", dept.getDeptId());
res.put("historyId", dept.getHistoryId());
res.put("name", dept.getDeptShort());
res.put("parentId", dept.getParentId());
res.put("isParent", dept.getHasChildren());
res.put("isLeaf", false);
res.put("disabled", false);
res.put("iconSkin", "dept");
res.put("fromUnit", dept.getFromUnit());
}
}
//获取子部门信息
List<Dept> deptList = deptMapper.selectDeptListByDeptIdAndAuthority(auth);
List<Map<String,Object>> deptlistMap = new LinkedList<Map<String,Object>>();
for (Dept depttemp : deptList) {
Map<String,Object> map = new HashMap<String, Object>();
map.put("id", depttemp.getDeptId());
map.put("historyId", depttemp.getHistoryId());
map.put("name", depttemp.getDeptShort());
map.put("parentId", depttemp.getParentId());
map.put("isParent", depttemp.getHasChildren());
map.put("isLeaf", depttemp.getHasChildren() != null && depttemp.getHasChildren().equals("true") ? false : true);
map.put("iconSkin", "dept");
map.put("fromUnit", depttemp.getFromUnit());
deptlistMap.add(map);
}
List list = new ArrayList();
if (deptId == null || "".equals(deptId)) {
res.put("children", deptlistMap);
list.add(res);
} else {
list = deptlistMap;
}
return list;
}
/**
* 通过sql插入信息
* @param sql
* @return
*/
//@DataSource(value = DataSourceType.SLAVE) //使用从数据库
@Log(title = "部门管理", businessType = BusinessType.INSERT)
@Override
public int insertDeptBySql(String sql) {
return deptMapper.insertDeptBySql(sql);
}
/**
* 得到当前用户所在的公司或大部门信息
* @param deptId
* @param unitType
* @param deptflag
* @return
*/
@Override
public Map<String, String> getCompanyInfoByDeptId(String deptId, String unitType, String deptflag) {
String t = "";
if ("03".equals(unitType)) {
t = deptId.substring(0, 6);
} else if ("04".equals(unitType)) {
t = deptId.substring(0, 9);
} else if ("02".equals(unitType)) {
if ("1".equals(deptflag)) {
t = deptId.substring(0, 6);
} else {
t = deptId.substring(0, 3);
}
}else if ("05".equals(unitType)) {
t = deptId.substring(0, 12);
}
Map<String, String> map = deptMapper.selectBySql("select dept_id, dept_name,dept_short from sys_dept where history_id= '"+ t +"'");
return map;
}
@Override
public List<Dept> listDeptByDeptId(String[] ids) {
return deptMapper.listDeptByDeptId(ids);
}
@Override
public List<Dept> selectDeptList(String parentID) {
return deptMapper.selectDeptListByPID(parentID);
}
@Override
public int sortSave(String[] deptIds) {
return deptMapper.sortSave(deptIds);
}
@Override
public List<Map<String,Object>> getDeptSearch(String deptId, String deptname,JSONObject json) {
Map<String,String> auth = new HashMap<String, String>();
Dept dept = deptMapper.selectDeptById(deptId);
auth.put("deptId", deptId);
auth.put("ancestors", dept.getAncestors());
auth.put("deptname", deptname);
if(json!=null) {
auth.put("property", json.getString("authority"));
auth.put("deptlevel", json.getString("deptlevel"));
auth.put("isshow", json.getString("isshow"));
}
List<Map<String,Object>> deptList = deptMapper.getAllChildrenDept(auth);
List<Map<String,Object>> deptlistMap = new LinkedList<Map<String,Object>>();
for (Map<String,Object> depttemp : deptList) {
if (!depttemp.get("dept_id").toString().equals(deptId)) {
Map<String,Object> map = new HashMap<String, Object>();
map.put("id", depttemp.get("dept_id").toString());
map.put("historyId", depttemp.get("history_id").toString());
map.put("name", depttemp.get("dept_short").toString());
map.put("deptName", depttemp.get("company_name") != null ? depttemp.get("company_name").toString() : "");
map.put("fullName", depttemp.get("dept_short").toString() + (depttemp.get("company_name") != null ? "/" + depttemp.get("company_name").toString() : ""));
map.put("parentId", depttemp.get("parent_id").toString());
map.put("isLeaf", true);
map.put("iconSkin", "dept");
deptlistMap.add(map);
}
}
return deptlistMap;
}
/**
* 根据类别(0:子公司 1:部门)获取dept信息
* @param fromUnit
* @return
*/
public List<Dept> getDeptByFromUnit(String fromUnit){
return deptMapper.getDeptByFromUnit(fromUnit);
}
@Override
public List<Dept> getDeptLikeAncestors(String ancestors) {
return deptMapper.getDeptLikeAncestors(ancestors);
}
@Override
public List<Dept> listDeptForDeptName(String deptName) {
return deptMapper.listDeptForDeptName(deptName);
}
public Dept getDeptByAncestors(String ancestors){
return deptMapper.getDeptByAncestors(ancestors);
}
/**
* 获取集团下属所有部门的id和parentid,用于会签过程中的排序
*
*/
@Override
public List<Map<String, String>> getDeptIdAndParentId() {
return deptMapper.selectAllBySql("select dept_id,parent_id from sys_dept where status ='1' and unit_type in ('02','03')");
}
/**
* 获取公司ID
* @param historyId
* @return
*/
public String getHistoryCompanyId(String historyId){
System.out.println("historyId "+historyId);
String deptId = "";
if(StringUtils.isNotEmpty(historyId)&&!historyId.equals("null")){
deptId = this.getCompanyId(historyId);
}
System.out.println("deptId "+deptId);
return deptId;
}
public String getCompanyId(String historyId){
String result = "";
System.out.println("historyId "+historyId);
Map<String,String> dept = deptMapper.getOldDeptInfo(historyId);
if(dept.get("DEPTID")!=null){
String fromUnit = dept.get("FROM_UNIT")!=null?dept.get("FROM_UNIT").toString():"";
String deptId = dept.get("DEPTID")!=null?dept.get("DEPTID").toString():"";
String superId = dept.get("SUPER_ID")!=null?dept.get("SUPER_ID").toString():"";
System.out.println("fromUnit "+fromUnit);
if(fromUnit.equals("1")){
if(StringUtils.isNotEmpty(superId)&&!superId.equals("null")&&!superId.equals("0")){
result = this.getCompanyId(superId);
}else{
result = deptId;
}
}else{
result = deptId;
}
}
return result;
}
@Override
@DataSource(DataSourceType.ORACLE)
public Map<String,String> getHistoryDeptInfo(String historyId){
System.out.println("historyId "+historyId);
Map<String,String> dept = deptMapper.getOldDeptInfo(historyId);
return dept;
}
@Override
public List<String> getDeptNamesByDeptIds(String[] deptIds) {
List<String> deptNames = new LinkedList<String>();
if(deptIds.length>0) {
deptNames = deptMapper.getDeptNamesByDeptIds(deptIds);
}
return deptNames;
}
@Override
public List<Dept> getDeptByFromUnit_childDpetIds(String fromUnit) {
return deptMapper.getDeptByFromUnit_childDpetIds(fromUnit);
}
}
package com.sinobase.project.system.dept.service;
import java.util.List;
import com.sinobase.project.system.dept.domain.DeptPermission;
/**
* 部门权限 服务层
*
* @author LouBin
* @date 2019-07-29
*/
public interface IDeptPermissionService {
/**
* 查询部门权限信息
* @param id 部门权限ID
* @return 部门权限信息
*/
public DeptPermission selectDeptPermissionById(String id);
/**
* 查询部门权限列表
* @param deptPermission 部门权限信息
* @return 部门权限集合
*/
public List<DeptPermission> selectDeptPermissionList(DeptPermission deptPermission);
/**
* 新增部门权限
* @param deptPermission 部门权限信息
* @return 结果
*/
public int insertDeptPermission(DeptPermission deptPermission);
/**
* 修改部门权限
* @param deptPermission 部门权限信息
* @return 结果
*/
public int updateDeptPermission(DeptPermission deptPermission);
/**
* 删除部门权限信息
* @param ids 需要删除的数据ID
* @return 结果
*/
public int deleteDeptPermissionByIds(String ids);
}
package com.sinobase.project.system.dept.service;
import com.alibaba.fastjson.JSONObject;
import com.sinobase.project.system.dept.domain.Dept;
import com.sinobase.project.system.role.domain.Role;
import java.util.List;
import java.util.Map;
/**
* 部门管理 服务层
*
* @author sinobase
*/
public interface IDeptService {
/**
* 查询部门管理数据
* @param dept 部门信息
* @return 部门信息集合
*/
List<Dept> selectDeptList(Dept dept);
/**
* 数据列表 ==》后台管理
*/
List<Map<String, Object>> treeForManage();
/**
* 根据父级ID获取下一级所有部门信息数据
* @param parentID 父级ID
* @return
*/
List<Dept> selectDeptList(String parentID);
/**
* 查询部门管理树
*
* @param dept 部门信息
* @return 所有部门信息
*/
List<Map<String, Object>> selectDeptTree(Dept dept);
/**
* 根据角色ID查询菜单
*
* @param role 角色对象
* @return 菜单列表
*/
List<Map<String, Object>> roleDeptTreeData(Role role);
/**
* 查询部门人数
*
* @param parentId 父部门ID
* @return 结果
*/
int selectDeptCount(String parentId);
/**
* 查询部门是否存在用户
*
* @param deptId 部门ID
* @return 结果 true 存在 false 不存在
*/
boolean checkDeptExistUser(String deptId);
/**
* 删除部门管理信息
*
* @param deptId 部门ID
* @return 结果
*/
int deleteDeptById(String deptId);
/**
* 新增保存部门信息
*
* @param dept 部门信息
* @return 结果
*/
int insertDept(Dept dept);
/**
* 修改保存部门信息
*
* @param dept 部门信息
* @return 结果
*/
int updateDept(Dept dept);
/**
* 根据部门ID查询信息
*
* @param deptId 部门ID
* @return 部门信息
*/
Dept selectDeptById(String deptId);
/**
* 根据部门ID查询信息,不包含公司信息
*
* @param deptId 部门ID
* @return 部门信息
*/
Dept selectDeptByIdNoCompany(String deptId);
/**
* 校验部门名称是否唯一
*
* @param dept 部门信息
* @return 结果
*/
String checkDeptNameUnique(Dept dept);
/**
* 排序保存
* @deptIds 部门id串
* @return
*/
int sortSave(String[] deptIds);
/**
* 根据用户ID获取部门信息(已经将部门所在公司装入)
* @param userId 用户id
* @return
*/
List<Dept> getDeptsByUserId(String userId);
/**
* 根据部门父级id获取部门所在的公司
* @param parentId
* @return
*/
Dept getCompanyByParentId(String parentId);
/****************************** 添加的代码 *******************************/
/**
* 根据部门对象集合添加部门
*/
Integer insertDeptList(List<Dept> deptList);
/**
* 获取本地数据库所有部门的id
* @return
*/
List<String> selectAllDeptId();
/**
* 查询所有部门信息
* @return
*/
List<Dept> selectAlldept();
/**
* 根据部门id获取其所有子孙部门
* @param rootId
* @return
*/
List<Dept> selectDeptListByDeptId(String rootId);
/**
* 根据部门id获取其所有子孙部门
* @param deptId
* @return
*/
List<Dept> selectDeptListsByDeptId(String deptId);
/**
* 获取部门树信息
* @param rootId 根节点部门 id
* @param deptId 部门 id
* @authority 部门权限信息
* @return
*/
List getDeptTree(String rootId, String deptId, JSONObject authority);
/**
* 获取部门树信息
* @param deptId
* @return
*/
List<Map<String, Object>> getDeptTree(String deptId);
/**
* 通过sql插入部门信息
* @param sql
* @return
*/
int insertDeptBySql(String sql);
/**
* 得到当前用户所在的公司或大部门信息
* @param deptId
* @param unitType
* @param deptflag
* @return
*/
Map<String, String> getCompanyInfoByDeptId(String deptId, String unitType, String deptflag);
/**
* 根据部门ID数组获取部门列表
* @param ids
* @return
*/
List<Dept> listDeptByDeptId(String [] ids);
/**
*
* 查询出当前部门的所有子部门
* @param deptId
* @param json
* @return
*/
List<Map<String, Object>> getDeptSearch(String deptId, String deptname,JSONObject json);
/**
* 根据祖级列表模糊查询部门
*
*/
List<Dept> getDeptLikeAncestors(String ancestors);
/**
* 根据部门名称获取部门列表
* @param deptName
* @return
*/
List<Dept> listDeptForDeptName(String deptName);
/**
* 获取二级子公司(from_unit = 0)
* @param ancestors
* @return
*/
Dept getDeptByAncestors(String ancestors);
/**
* 根据类别(0:子公司 1:部门)获取dept信息
* @param fromUnit
* @return
*/
public List<Dept> getDeptByFromUnit(String fromUnit);
/**
* 据类别(0:子公司 1:部门)获取dept信息(返回内容包含子部门数据)
* @param fromUnit
* @return
*/
public List<Dept> getDeptByFromUnit_childDpetIds(String fromUnit);
public List<Map<String, String>> getDeptIdAndParentId();
public String getHistoryCompanyId(String historyId);
/**
* 获取老OA部门信息
* @param historyId
* @return
*/
public Map<String,String> getHistoryDeptInfo(String historyId);
/**
* 根据部门Id获取部门名称
* @param deptIds
* @return
*/
public List<String> getDeptNamesByDeptIds(String[] deptIds);
}
package com.sinobase.project.system.menu.domain;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.sinobase.framework.web.domain.BaseEntity;
/**
* 菜单权限表 sys_menu
* @author sinobase
*/
public class Menu extends BaseEntity {
private static final long serialVersionUID = 1L;
/**
* 资源类型:标签解析页
*/
public static final String TYPE_TAB = "C";
/**
* 资源类型:标签解析页
*/
public static final String TYPE_MODULE = "M";
/**
* 资源类型:独立的首页
*/
public static final String TYPE_INDEX = "I";
/**
* 资源类型:按钮
*/
public static final String TYPE_BUTTON = "F";
/** 菜单ID */
private String menuId;
/** 菜单名称 */
private String menuName;
/** 父菜单名称 */
private String parentName;
/** 父菜单ID */
private String parentId;
/** 显示顺序 */
private String orderNum;
/** 菜单URL */
private String url;
/** 类型:0目录,1菜单,2按钮 <2019-3-21 loubin ,修改:菜单类型<M:模块,C:标签,F:按钮>> */
private String menuType;
/** 菜单状态:0显示,1隐藏 */
private String visible;
/** 权限字符串 */
private String perms;
/** 菜单图标 */
private String icon;
/** 子菜单 */
private List<Menu> children = new ArrayList<Menu>();
public String getMenuId() {
return menuId;
}
public void setMenuId(String menuId) {
this.menuId = menuId;
}
public String getMenuName() {
return menuName;
}
public void setMenuName(String menuName) {
this.menuName = menuName;
}
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public String getOrderNum() {
return orderNum;
}
public void setOrderNum(String orderNum) {
this.orderNum = orderNum;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getMenuType() {
return menuType;
}
public void setMenuType(String menuType) {
this.menuType = menuType;
}
public String getVisible() {
return visible;
}
public void setVisible(String visible) {
this.visible = visible;
}
public String getPerms() {
return perms;
}
public void setPerms(String perms) {
this.perms = perms;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public List<Menu> getChildren() {
return children;
}
public void setChildren(List<Menu> children) {
this.children = children;
}
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE).append("menuId", getMenuId())
.append("menuName", getMenuName()).append("parentId", getParentId()).append("orderNum", getOrderNum())
.append("url", getUrl()).append("menuType", getMenuType()).append("visible", getVisible())
.append("perms", getPerms()).append("icon", getIcon()).append("createBy", getCreateBy())
.append("createTime", getCreateTime()).append("updateBy", getUpdateBy())
.append("updateTime", getUpdateTime()).append("remark", getRemark()).toString();
}
}
package com.sinobase.project.system.menu.mapper;
import java.util.HashMap;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.sinobase.project.system.menu.domain.Menu;
/**
* 菜单表 数据层
*
* @author sinobase
*/
public interface MenuMapper {
/**
* 查询系统所有菜单(含按钮)
*
* @return 菜单列表
*/
public List<Menu> selectMenuAll();
/**
* 查询系统正常显示菜单(按钮类型)
* @param map
* @return 菜单列表
*/
public List<Menu> selectMenuNormalAll(HashMap<String, Object> map);
/**
* 根据用户ID查询菜单
* @param userId 用户ID
* @param meunType 菜单类型
* @param parentId 父节点ID
* @return 菜单列表
*/
public List<Menu> selectMenusByUserId(@Param("userId") String userId, @Param("menuType") String meunType, @Param("parentId") String parentId);
/**
* 根据用户ID查询权限
*
* @param userId 用户ID
* @return 权限列表
*/
public List<String> selectPermsByUserId(String userId);
/**
* 根据角色ID查询菜单
*
* @param roleId 角色ID
* @return 菜单列表
*/
public List<String> selectMenuTree(String roleId);
/**
* 查询系统菜单列表
*
* @param menu 菜单信息
* @return 菜单列表
*/
public List<Menu> selectMenuList(Menu menu);
/**
* 删除菜单管理信息
*
* @param menuId 菜单ID
* @return 结果
*/
public int deleteMenuById(String menuId);
/**
* 根据菜单ID查询信息
*
* @param menuId 菜单ID
* @return 菜单信息
*/
public Menu selectMenuById(String menuId);
/**
* 查询菜单数量
*
* @param parentId 菜单父ID
* @return 结果
*/
public int selectCountMenuByParentId(String parentId);
/**
* 新增菜单信息
*
* @param menu 菜单信息
* @return 结果
*/
public int insertMenu(Menu menu);
/**
* 修改菜单信息
*
* @param menu 菜单信息
* @return 结果
*/
public int updateMenu(Menu menu);
/**
* 校验菜单名称是否唯一
*
* @param menuName 菜单名称
* @param parentId 父菜单ID
* @return 结果
*/
public Menu checkMenuNameUnique(@Param("menuName") String menuName, @Param("parentId") String parentId);
/**
* 获取当前表最大ID值
* @return
*/
public int selectMaxId();
}
package com.sinobase.project.system.menu.service;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.sinobase.project.system.menu.domain.Menu;
import com.sinobase.project.system.role.domain.Role;
import com.sinobase.project.system.user.domain.User;
/**
* 菜单 业务层
*
* @author sinobase
*/
public interface IMenuService {
/**
* 根据用户ID查询菜单
* @param user 用户信息
* @param menuType 菜单类型<M:模块,C:标签,F:按钮>
* @param parentId 父级ID
* @return 菜单列表
*/
public List<Menu> selectMenusByUser(User user, String menuType,String parentId);
/**
* 查询系统菜单列表
* @param menu 菜单信息
* @return 菜单列表
*/
public List<Menu> selectMenuList(Menu menu);
/**
* 查询菜单集合
*
* @return 所有菜单信息
*/
public List<Menu> selectMenuAll();
/**
* 根据用户ID查询权限
*
* @param userId
* 用户ID
* @return 权限列表
*/
public Set<String> selectPermsByUserId(String userId);
/**
* 根据角色ID查询菜单
*
* @param role
* 角色对象
* @return 菜单列表
*/
public List<Map<String, Object>> roleMenuTreeData(Role role);
/**
* 查询所有菜单信息
*
* @return 菜单列表
*/
public List<Map<String, Object>> menuTreeData();
/**
* 查询系统所有权限
*
* @return 权限列表
*/
public Map<String, String> selectPermsAll();
/**
* 删除菜单管理信息
*
* @param menuId
* 菜单ID
* @return 结果
*/
public int deleteMenuById(String menuId);
/**
* 根据菜单ID查询信息
*
* @param menuId
* 菜单ID
* @return 菜单信息
*/
public Menu selectMenuById(String menuId);
/**
* 查询菜单数量
*
* @param parentId
* 菜单父ID
* @return 结果
*/
public int selectCountMenuByParentId(String parentId);
/**
* 查询菜单使用数量
*
* @param menuId
* 菜单ID
* @return 结果
*/
public int selectCountRoleMenuByMenuId(String menuId);
/**
* 新增保存菜单信息
*
* @param menu
* 菜单信息
* @return 结果
*/
public int insertMenu(Menu menu);
/**
* 修改保存菜单信息
*
* @param menu
* 菜单信息
* @return 结果
*/
public int updateMenu(Menu menu);
/**
* 校验菜单名称是否唯一
*
* @param menu
* 菜单信息
* @return 结果
*/
public String checkMenuNameUnique(Menu menu);
/**
* 获取当前表最大ID值
* @return
*/
public int selectMaxId();
}
package com.sinobase.project.system.menu.service;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sinobase.common.constant.UserConstants;
import com.sinobase.common.utils.StringUtils;
import com.sinobase.common.utils.TreeUtils;
import com.sinobase.project.system.menu.domain.Menu;
import com.sinobase.project.system.menu.mapper.MenuMapper;
import com.sinobase.project.system.role.domain.Role;
import com.sinobase.project.system.role.mapper.RoleMenuMapper;
import com.sinobase.project.system.user.domain.User;
/**
* 菜单 业务层处理
*
* @author sinobase
*/
@Service
public class MenuServiceImpl implements IMenuService {
public static final String PREMISSION_STRING = "perms[\"{0}\"]";
@Autowired
private MenuMapper menuMapper;
@Autowired
private RoleMenuMapper roleMenuMapper;
/**
* 根据用户查询菜单
*
* @param user 用户信息
* @param menuType 菜单类型
* @param parentId
* @return 菜单列表
*/
@Override
public List<Menu> selectMenusByUser(User user, String menuType, String parentId) {
List<Menu> menus = new LinkedList<Menu>();
try {
if (user.isAdmin()) {// 管理员显示所有菜单信息
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("menuType", menuType);
map.put("parentId", parentId);
menus = menuMapper.selectMenuNormalAll(map);
} else {
menus = menuMapper.selectMenusByUserId(user.getUserId(), menuType, parentId);
}
} catch (Exception e) {
throw new RuntimeException(e); // 平台SSO过期以后,这里会报NullPointerException.因为以后从直接从系统里读取资源,这个方法可能不会用,所以暂时不找原因。
}
if (Menu.TYPE_TAB.equals(menuType)) {
return menus;
} else {
return TreeUtils.getChildPerms(menus, "0");
}
}
/**
* 查询菜单集合
*
* @return 所有菜单信息
*/
@Override
public List<Menu> selectMenuList(Menu menu) {
return menuMapper.selectMenuList(menu);
}
/**
* 查询菜单集合
*
* @return 所有菜单信息
*/
@Override
public List<Menu> selectMenuAll() {
return menuMapper.selectMenuAll();
}
/**
* 根据用户ID查询权限
*
* @param userId 用户ID
* @return 权限列表
*/
@Override
public Set<String> selectPermsByUserId(String userId) {
List<String> perms = menuMapper.selectPermsByUserId(userId);
Set<String> permsSet = new HashSet<>();
for (String perm : perms) {
if (StringUtils.isNotEmpty(perm)) {
permsSet.addAll(Arrays.asList(perm.trim().split(",")));
}
}
return permsSet;
}
/**
* 根据角色ID查询菜单
*
* @param role 角色对象
* @return 菜单列表
*/
@Override
public List<Map<String, Object>> roleMenuTreeData(Role role) {
String roleId = role.getRoleId();
List<Map<String, Object>> trees = new ArrayList<Map<String, Object>>();
List<Menu> menuList = menuMapper.selectMenuAll();
if (StringUtils.isNotNull(roleId)) {
List<String> roleMenuList = menuMapper.selectMenuTree(roleId);
trees = getTrees(menuList, true, roleMenuList, true);
} else {
trees = getTrees(menuList, false, null, true);
}
return trees;
}
/**
* 查询所有菜单
*
* @return 菜单列表
*/
@Override
public List<Map<String, Object>> menuTreeData() {
List<Map<String, Object>> trees = new ArrayList<Map<String, Object>>();
List<Menu> menuList = menuMapper.selectMenuAll();
trees = getTrees(menuList, false, null, false);
return trees;
}
/**
* 查询系统所有权限
*
* @return 权限列表
*/
@Override
public LinkedHashMap<String, String> selectPermsAll() {
LinkedHashMap<String, String> section = new LinkedHashMap<>();
List<Menu> permissions = menuMapper.selectMenuAll();
if (StringUtils.isNotEmpty(permissions)) {
for (Menu menu : permissions) {
section.put(menu.getUrl(), MessageFormat.format(PREMISSION_STRING, menu.getPerms()));
}
}
return section;
}
/**
* 对象转菜单树
*
* @param menuList 菜单列表
* @param isCheck 是否需要选中
* @param roleMenuList 角色已存在菜单列表
* @param permsFlag 是否需要显示权限标识
* @return
*/
public List<Map<String, Object>> getTrees(List<Menu> menuList, boolean isCheck, List<String> roleMenuList,
boolean permsFlag) {
List<Map<String, Object>> trees = new ArrayList<Map<String, Object>>();
for (Menu menu : menuList) {
Map<String, Object> deptMap = new HashMap<String, Object>();
deptMap.put("id", menu.getMenuId());
deptMap.put("pId", menu.getParentId());
deptMap.put("name", transMenuName(menu, roleMenuList, permsFlag));
deptMap.put("title", menu.getMenuName());
if (isCheck) {
deptMap.put("checked", roleMenuList.contains(menu.getMenuId() + menu.getPerms()));
} else {
deptMap.put("checked", false);
}
trees.add(deptMap);
}
return trees;
}
public String transMenuName(Menu menu, List<String> roleMenuList, boolean permsFlag) {
StringBuffer sb = new StringBuffer();
sb.append(menu.getMenuName());
if (permsFlag) {
sb.append("<font color=\"#888\">&nbsp;&nbsp;&nbsp;" + menu.getPerms() + "</font>");
}
return sb.toString();
}
/**
* 删除菜单管理信息
*
* @param menuId 菜单ID
* @return 结果
*/
@Override
public int deleteMenuById(String menuId) {
//TODO 获取名称信息,暂时取消在controller中调用
//ShiroUtils.clearCachedAuthorizationInfo();
return menuMapper.deleteMenuById(menuId);
}
/**
* 根据菜单ID查询信息
*
* @param menuId 菜单ID
* @return 菜单信息
*/
@Override
public Menu selectMenuById(String menuId) {
return menuMapper.selectMenuById(menuId);
}
/**
* 查询子菜单数量
*
* @param parentId 菜单ID
* @return 结果
*/
@Override
public int selectCountMenuByParentId(String parentId) {
return menuMapper.selectCountMenuByParentId(parentId);
}
/**
* 查询菜单使用数量
*
* @param menuId 菜单ID
* @return 结果
*/
@Override
public int selectCountRoleMenuByMenuId(String menuId) {
return roleMenuMapper.selectCountRoleMenuByMenuId(menuId);
}
/**
* 新增保存菜单信息
*
* @param menu 菜单信息
* @return 结果
*/
@Override
public int insertMenu(Menu menu) {
menu.setMenuId((menuMapper.selectMaxId() + 1) + "");
//TODO 获取名称信息,暂时取消在controller中调用
//menu.setCreateBy(ShiroUtils.getLoginName());
//ShiroUtils.clearCachedAuthorizationInfo();
return menuMapper.insertMenu(menu);
}
/**
* 修改保存菜单信息
*
* @param menu 菜单信息
* @return 结果
*/
@Override
public int updateMenu(Menu menu) {
//TODO 获取名称信息,暂时取消在controller中调用
//menu.setUpdateBy(ShiroUtils.getLoginName());
//ShiroUtils.clearCachedAuthorizationInfo();
return menuMapper.updateMenu(menu);
}
/**
* 校验菜单名称是否唯一
*
* @param menu 菜单信息
* @return 结果
*/
@Override
public String checkMenuNameUnique(Menu menu) {
String menuId = StringUtils.isNull(menu.getMenuId()) ? "-1" : menu.getMenuId();
Menu info = menuMapper.checkMenuNameUnique(menu.getMenuName(), menu.getParentId());
if (StringUtils.isNotNull(info) && !menuId.equals(info.getMenuId())) {
return UserConstants.MENU_NAME_NOT_UNIQUE;
}
return UserConstants.MENU_NAME_UNIQUE;
}
/**
* 获取当前表最大ID值
* @return
*/
@Override
public int selectMaxId() {
return menuMapper.selectMaxId();
}
}
package com.sinobase.project.system.portal.constant;
/**
* @author WangSJ
* @ClassName MessageConstants
* @Description 系统信息静态类
* @Date 2019/5/16 10:05
* @Version 1.0
*/
public class MessageConstants {
/**
* 系统信息状态:正常
*/
public static String MESSAGE_STATE_NORMAL = "normal";
/**
* 系统信息状态:过期
*/
public static String MESSAGE_STATE_ENDED = "ended";
/**
* 系统信息级别:普通事件
*/
public static String MESSAGE_LEVEL_ORDINARY = "ordinary";
/**
* 系统信息级别:紧急事件
*/
public static String MESSAGE_LEVEL_URGENT = "urgent";
/**
* 系统信息级别:重大事件
*/
public static String MESSAGE_LEVEL_MAJOR = "major";
/**
* 系统信息来源:本系统
*/
public static String DATA_SOURCE_LOCAL = "local";
/**
* 系统信息来源:第三方
*/
public static String DATA_SOURCE_THIRDPARTY = "thirdParty";
/**
* 系统信息类型:信息通知 -- TODO 弃用
*/
public static String MESSAGE_TYPE_INFO = "1";
/**
* 系统信息类型:待办-- TODO 弃用
*/
public static String MESSAGE_TYPE_HANDEL = "2";
/**
* 系统信息类型:待阅 -- TODO 弃用
*/
public static String MESSAGE_TYPE_READ = "3";
/**
* 系统信息类型:流程事件 -- TODO 弃用
*/
public static String MESSAGE_TYPE_FLOW = "4";
/**
* 系统信息类型:流程事件 -- 老OA平台 -- TODO 弃用
*/
public static String MESSAGE_TYPE_OLD_FLOW = "5";
/**
* 系统信息类型:流程待办通知
*/
public static String MESSAGE_TYPE_WORK_FLOW_WRITE = "workFlowWrite";
/**
* 系统信息类型:流程待办 第三方
*/
public static String MESSAGE_TYPE_THIRD_PARTY_WORK_FLOW_WRITE = "thirdPartyWorkFlowWrite";
/**
* 系统信息类型:流程已办通知
*/
public static String MESSAGE_TYPE_WORK_FLOW_READ = "workFlowRead";
/**
* 系统信息类型:待阅、已阅通知
*/
public static String MESSAGE_TYPE_DOC_SEND = "docSend";
/**
* 系统信息类型:待阅通知
*/
public static String MESSAGE_TYPE_DOC_SEND_WAIT="docSendWait";
/**
* 系统信息类型:已阅通知
*/
public static String MESSAGE_TYPE_DOC_SEND_READ="docSendRead";
/**
* 系统信息类型:会议通知
*/
public static String MESSAGE_TYPE_MEETING ="meeting";
/**
* 系统信息类型:信息通知 -- 包含会议等等所有的通知信息
*/
public static String MESSAGE_TYPE_MESSAGE = "message";
}
package com.sinobase.project.system.portal.domain;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.sinobase.common.utils.StringUtils;
import com.sinobase.framework.web.domain.BaseEntity;
/**
* @author WangSJ
* @ClassName Message
* @Description
* @Date 2019/5/14 10:24
* @Version 1.0
*/
@TableName(value = "sys_message")
public class Message extends BaseEntity {
private static final long serialVersionUID = 1L;
/**
* 主键ID
*/
private String id;
/**
* 信息类别 请查询 MessageConstants
*/
private String messageType;
/**
* 标题
*/
private String title;
/**
* 信息内容
*/
private String content;
/**
* 办理路径
*/
private String url;
/**
* 进度
*/
@TableField(exist = false)
private String progress;
/**
* 主办部门
*/
@TableField(exist = false)
private String deptName;
/**
* 接收时间/创建时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date receiveTime;
/**
* 过期时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date expirationTime;
/**
* 信息等级 ordinary:普通事件,urgent:紧急事件,major:重大事件
*/
private String level;
/**
* 数据来源 local:本系统 ,thirdParty:第三方 可以传入相应的系统名称
*/
private String dataSource;
/**
* 数据来源人ID (发送人)
*/
private String fromUserId;
/**
* 数据来源人姓名 (发送人)
*/
private String fromUserName;
/**
* 数据来源人所在部门ID (创建人部门ID)
*/
private String fromDeptId;
/**
* 数据来源人所在部门名称 (创建人部门名称)
*/
private String fromDeptName;
/**
* 信息查看授权人员ID (接收人)
*/
private String grantUserId;
/**
* 信息查看授权人员 (接收人)
*/
private String grantUserName;
/**
* 信息查看授权部门ID
*/
private String grantDeptId;
/**
* 信息查看授权部门
*/
private String grantDeptName;
/**
* 已阅读人员ID
*/
private String readUserId;
/**
* 状态 normal:正常 ,ended:过期
*/
private String status;
/**
* 是否为旧数据库数据 yes - 是 no - 否
*/
@TableField("is_old_oa_data")
private String isOldOAData;
/**
* 待办事项数据库表名
*/
@TableField("wait_handle_table_name")
private String waitHandleTableName;
/**
* 待办事项数据库主键名称
*/
@TableField("wait_handle_primary_key_name")
private String waitHandlePrimaryKeyName;
/**
* 待办事项数据库主键值
*/
@TableField("wait_handle_primary_key_value")
private String waitHandlePrimaryKeyValue;
/**
* 二级分类 如系统通知下的收文通知、发文通知
*/
@TableField("category_types")
private String categoryTypes;
/**
* 所属业务表主键ID值 :
* 此属性应用于一直属性 和 waitHandlePrimaryKeyValue 的区别在于
* waitHandlePrimaryKeyValue是和老平台数据进行兼容而预留出来的字段 可能没有保存实际数据
* subordinateId 一定会保留业务表主键ID
*/
@TableField("subordinate_id")
private String subordinateId;
/**
*
* 新版工作流实例id,主要是新版工作流在提交过程中更新待办所需要的id
*
*/
@TableField("workflow_info_id")
private String workflowInfoId;
@TableField("doc_id")
private String docId;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMessageType() {
return messageType;
}
public void setMessageType(String messageType) {
this.messageType = messageType;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
// -TODO 字段长度过长直接进行截取
if(StringUtils.isNotEmpty(title) && title.length() > 200 ){
this.title = title.substring(0,200);
}else{
this.title = title;
}
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Date getReceiveTime() {
return receiveTime;
}
public void setReceiveTime(Date receiveTime) {
this.receiveTime = receiveTime;
}
public Date getExpirationTime() {
return expirationTime;
}
public void setExpirationTime(Date expirationTime) {
this.expirationTime = expirationTime;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public String getDataSource() {
return dataSource;
}
public void setDataSource(String dataSource) {
this.dataSource = dataSource;
}
public String getFromUserId() {
return fromUserId;
}
public void setFromUserId(String fromUserId) {
this.fromUserId = fromUserId;
}
public String getFromUserName() {
return fromUserName;
}
public void setFromUserName(String fromUserName) {
this.fromUserName = fromUserName;
}
public String getFromDeptId() {
return fromDeptId;
}
public void setFromDeptId(String fromDeptId) {
this.fromDeptId = fromDeptId;
}
public String getFromDeptName() {
return fromDeptName;
}
public void setFromDeptName(String fromDeptName) {
this.fromDeptName = fromDeptName;
}
public String getGrantUserId() {
return grantUserId;
}
public void setGrantUserId(String grantUserId) {
this.grantUserId = grantUserId;
}
public String getGrantUserName() {
return grantUserName;
}
public void setGrantUserName(String grantUserName) {
this.grantUserName = grantUserName;
}
public String getGrantDeptId() {
return grantDeptId;
}
public void setGrantDeptId(String grantDeptId) {
this.grantDeptId = grantDeptId;
}
public String getGrantDeptName() {
return grantDeptName;
}
public void setGrantDeptName(String grantDeptName) {
this.grantDeptName = grantDeptName;
}
public String getReadUserId() {
return readUserId;
}
public void setReadUserId(String readUserId) {
this.readUserId = readUserId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getIsOldOAData() {
return isOldOAData;
}
public void setIsOldOAData(String isOldOAData) {
this.isOldOAData = isOldOAData;
}
public String getWaitHandleTableName() {
return waitHandleTableName;
}
public void setWaitHandleTableName(String waitHandleTableName) {
this.waitHandleTableName = waitHandleTableName;
}
public String getWaitHandlePrimaryKeyName() {
return waitHandlePrimaryKeyName;
}
public void setWaitHandlePrimaryKeyName(String waitHandlePrimaryKeyName) {
this.waitHandlePrimaryKeyName = waitHandlePrimaryKeyName;
}
public String getWaitHandlePrimaryKeyValue() {
return waitHandlePrimaryKeyValue;
}
public void setWaitHandlePrimaryKeyValue(String waitHandlePrimaryKeyValue) {
this.waitHandlePrimaryKeyValue = waitHandlePrimaryKeyValue;
}
public String getCategoryTypes() {
return categoryTypes;
}
public void setCategoryTypes(String categoryTypes) {
this.categoryTypes = categoryTypes;
}
public String getSubordinateId() {
return subordinateId;
}
public void setSubordinateId(String subordinateId) {
this.subordinateId = subordinateId;
}
public String getWorkflowInfoId() {
return workflowInfoId;
}
public void setWorkflowInfoId(String workflowInfoId) {
this.workflowInfoId = workflowInfoId;
}
public String getDocId() {
return docId;
}
public void setDocId(String docId) {
this.docId = docId;
}
public String getProgress() {
return progress;
}
public void setProgress(String progress) {
this.progress = progress;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
@Override
public String toString() {
return "Message{" +
"id='" + id + '\'' +
", messageType='" + messageType + '\'' +
", title='" + title + '\'' +
", content='" + content + '\'' +
", url='" + url + '\'' +
", receiveTime=" + receiveTime +
", expirationTime=" + expirationTime +
", level='" + level + '\'' +
", dataSource='" + dataSource + '\'' +
", fromUserId='" + fromUserId + '\'' +
", fromUserName='" + fromUserName + '\'' +
", fromDeptId='" + fromDeptId + '\'' +
", fromDeptName='" + fromDeptName + '\'' +
", grantUserId='" + grantUserId + '\'' +
", grantUserName='" + grantUserName + '\'' +
", grantDeptId='" + grantDeptId + '\'' +
", grantDeptName='" + grantDeptName + '\'' +
", readUserId='" + readUserId + '\'' +
", status='" + status + '\'' +
", isOldOAData='" + isOldOAData + '\'' +
", waitHandleTableName='" + waitHandleTableName + '\'' +
", waitHandlePrimaryKeyName='" + waitHandlePrimaryKeyName + '\'' +
", waitHandlePrimaryKeyValue='" + waitHandlePrimaryKeyValue + '\'' +
", categoryTypes='" + categoryTypes + '\'' +
", subordinateId='" + subordinateId + '\'' +
", workflowInfoId='" + workflowInfoId + '\'' +
", docId='" + docId + '\'' +
'}';
}
}
\ No newline at end of file
package com.sinobase.project.system.portal.domain;
import java.util.LinkedHashMap;
import java.util.Map;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
/**
* 快捷方式
* @author LouBin
*/
@TableName(value = "sys_shortcut")
public class Shortcut {
/**
* 类别:OA系统
*/
@TableField(exist = false)
public static String CATEGORY_OA = "OA";
/**
* 类别:第三方系统
*/
@TableField(exist = false)
public static String CATEGORY_THIRDPARTY= "THIRDPARTY";
/**
* 类别:个人配置
*/
@TableField(exist = false)
public static String CATEGORY_PERSON= "PERSON";
@TableField(exist = false)
public static Map<String, String> TYPE_ARRAY = new LinkedHashMap<String, String>();
static{
TYPE_ARRAY.put("SC-QB","签报");
TYPE_ARRAY.put("SC-SF","收发文");
TYPE_ARRAY.put("SC-HYJY","会议纪要");
TYPE_ARRAY.put("SC-DAILY","日常");
TYPE_ARRAY.put("SC-OTHER","其他");
}
private String id;
private String name;
private String url;
private String ico;
private String type;
private String category;
private String status;
private int orderNum;
private String companyId;
private String remark;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getOrderNum() {
return orderNum;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public void setOrderNum(int orderNum) {
this.orderNum = orderNum;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getIco() {
return ico;
}
public void setIco(String ico) {
this.ico = ico;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCompanyId() {
return companyId;
}
public void setCompanyId(String companyId) {
this.companyId = companyId;
}
}
package com.sinobase.project.system.portal.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.sinobase.project.system.portal.domain.Message;
/**
* @author WangSJ
* @ClassName MessageMapper
* @Description
* @Date 2019/5/14 10:24
* @Version 1.0
*/
@Repository
public interface MessageMapper extends BaseMapper<Message> {
/**
* 获取系统信息列表
* @param message
* @return
*/
List<Message> listMessage(Message message);
/**
* 根据系统信息所属的业务表数据主键ID进行删除
* @param ids
*/
void delMessageForSubordinateIds (String [] ids);
/**
* 批量插入
* @param list
*/
void saveMessages(@Param( "list" ) List<Message> list);
/**
*
* 根据流程实例修改待办数据为已办
* @param workflowInfoId
*/
void updateMessageByWorkflowInfoId(String workflowInfoId);
/**
*
* 根据流程实例删除待办数据
* @param workflowInfoId
*/
void deleteMessageByWorkflowInfoId(String workflowInfoId);
/**
* 根据当前用户的信息删除,删除sys_message表中的当前人对应的旧oa的待办信息
*
*
* @param grantUserId
*/
int deleteMessageByOldOAWriteMessage(String grantUserId);
/**
* 根据待办ID修改待办数据为已办
* @param workitemId
*/
void updateMessageByWorkitemId(String workitemId);
/**
* 不走流程的待办信息删除,
* subordinateId 业务表主键id
*/
int deleteNotWorkFlowMessage(String subordinateId);
/**
*
* @param userId 代办人id
* @param url 链接(模糊查询)
* @param id 业务表id
* @return
*/
int deleteNotWorkFlowMessageByMany(@Param("userId") String userId, @Param("url") String url, @Param("id") String id);
/**
*
* @param superviseFiletypeIds 督办流程ID
* @return
*/
public List<Message> listSuperviseBacklog(@Param("message") Message message, @Param("superviseFiletypeIds") List<String> superviseFiletypeIds, @Param("sysUserId")String sysUserId);
/**
* 删除待办数据
* @param recordid
* @return
*/
int deleteSysMessageByRecordId(@Param("recordid")String recordid);
/**
* 删除已办数据
* @param recordid
* @return
*/
int deleteFlowReadNewByRecordId(@Param("recordid")String recordid);
/**
* 删除新OA待办数据
* @param recordid
* @return
*/
int deleteNewFlowWriteByRecordId(@Param("recordid")String recordid);
/**
* 删除老OA待办数据
* @param recordid
* @return
*/
int deleteFlowWriteByRecordId(@Param("recordid")String recordid);
/**
* 删除老OA流程日志数据
* @param recordid
* @return
*/
int deleteFlowWflogByRecordId(@Param("recordid")String recordid);
/**
* 删除老OA已办数据
* @param recordid
* @return
*/
int deleteFlowReadByRecordId(@Param("recordid")String recordid);
}
package com.sinobase.project.system.portal.mapper;
import org.springframework.stereotype.Repository;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.sinobase.project.system.portal.domain.Shortcut;
@Repository
public interface ShortcutMapper extends BaseMapper<Shortcut> {
}
package com.sinobase.project.system.post.domain;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.sinobase.framework.aspectj.lang.annotation.Excel;
import com.sinobase.framework.web.domain.BaseEntity;
/**
* 岗位表 sys_post
*
* @author sinobase
*/
public class Post extends BaseEntity {
private static final long serialVersionUID = 1L;
/** 岗位序号 */
@Excel(name = "岗位序号")
private Long postId;
/** 岗位编码 */
@Excel(name = "岗位编码")
private String postCode;
/** 岗位名称 */
@Excel(name = "岗位名称")
private String postName;
/** 岗位排序 */
@Excel(name = "岗位排序")
private String postSort;
/** 状态(0正常 1停用) */
@Excel(name = "状态", readConverterExp = "0=正常,1=停用")
private String status;
/** 用户是否存在此岗位标识 默认不存在 */
private boolean flag = false;
public Long getPostId()
{
return postId;
}
public void setPostId(Long postId)
{
this.postId = postId;
}
public String getPostCode()
{
return postCode;
}
public void setPostCode(String postCode)
{
this.postCode = postCode;
}
public String getPostName()
{
return postName;
}
public void setPostName(String postName)
{
this.postName = postName;
}
public String getPostSort()
{
return postSort;
}
public void setPostSort(String postSort)
{
this.postSort = postSort;
}
public String getStatus()
{
return status;
}
public void setStatus(String status)
{
this.status = status;
}
public boolean isFlag()
{
return flag;
}
public void setFlag(boolean flag)
{
this.flag = flag;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("postId", getPostId())
.append("postCode", getPostCode())
.append("postName", getPostName())
.append("postSort", getPostSort())
.append("status", getStatus())
.append("createBy", getCreateBy())
.append("createTime", getCreateTime())
.append("updateBy", getUpdateBy())
.append("updateTime", getUpdateTime())
.append("remark", getRemark())
.toString();
}
}
package com.sinobase.project.system.post.mapper;
import java.util.List;
import com.sinobase.project.system.post.domain.Post;
/**
* 岗位信息 数据层
*
* @author sinobase
*/
public interface PostMapper{
/**
* 查询岗位数据集合
*
* @param post 岗位信息
* @return 岗位数据集合
*/
public List<Post> selectPostList(Post post);
/**
* 查询所有岗位
*
* @return 岗位列表
*/
public List<Post> selectPostAll();
/**
* 根据用户ID查询岗位
*
* @param userId 用户ID
* @return 岗位列表
*/
public List<Post> selectPostsByUserId(String userId);
/**
* 通过岗位ID查询岗位信息
*
* @param postId 岗位ID
* @return 角色对象信息
*/
public Post selectPostById(Long postId);
/**
* 批量删除岗位信息
*
* @param ids 需要删除的数据ID
* @return 结果
*/
public int deletePostByIds(Long[] ids);
/**
* 修改岗位信息
*
* @param post 岗位信息
* @return 结果
*/
public int updatePost(Post post);
/**
* 新增岗位信息
*
* @param post 岗位信息
* @return 结果
*/
public int insertPost(Post post);
/**
* 校验岗位名称
*
* @param postName 岗位名称
* @return 结果
*/
public Post checkPostNameUnique(String postName);
/**
* 校验岗位编码
*
* @param postCode 岗位编码
* @return 结果
*/
public Post checkPostCodeUnique(String postCode);
}
package com.sinobase.project.system.post.service;
import java.util.List;
import com.sinobase.project.system.post.domain.Post;
/**
* 岗位信息 服务层
*
* @author sinobase
*/
public interface IPostService {
/**
* 查询岗位信息集合
*
* @param post 岗位信息
* @return 岗位信息集合
*/
public List<Post> selectPostList(Post post);
/**
* 查询所有岗位
*
* @return 岗位列表
*/
public List<Post> selectPostAll();
/**
* 根据用户ID查询岗位
*
* @param userId 用户ID
* @return 岗位列表
*/
public List<Post> selectPostsByUserId(String userId);
/**
* 通过岗位ID查询岗位信息
*
* @param postId 岗位ID
* @return 角色对象信息
*/
public Post selectPostById(Long postId);
/**
* 批量删除岗位信息
*
* @param ids 需要删除的数据ID
* @return 结果
* @throws Exception 异常
*/
public int deletePostByIds(String ids) throws Exception;
/**
* 新增保存岗位信息
*
* @param post 岗位信息
* @return 结果
*/
public int insertPost(Post post);
/**
* 修改保存岗位信息
*
* @param post 岗位信息
* @return 结果
*/
public int updatePost(Post post);
/**
* 通过岗位ID查询岗位使用数量
*
* @param postId 岗位ID
* @return 结果
*/
public int countUserPostById(Long postId);
/**
* 校验岗位名称
*
* @param post 岗位信息
* @return 结果
*/
public String checkPostNameUnique(Post post);
/**
* 校验岗位编码
*
* @param post 岗位信息
* @return 结果
*/
public String checkPostCodeUnique(Post post);
}
package com.sinobase.project.system.post.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sinobase.common.constant.UserConstants;
import com.sinobase.common.exception.BusinessException;
import com.sinobase.common.support.Convert;
import com.sinobase.common.utils.StringUtils;
import com.sinobase.project.system.post.domain.Post;
import com.sinobase.project.system.post.mapper.PostMapper;
import com.sinobase.project.system.user.mapper.UserPostMapper;
/**
* 岗位信息 服务层处理
*
* @author sinobase
*/
@Service
public class PostServiceImpl implements IPostService
{
@Autowired
private PostMapper postMapper;
@Autowired
private UserPostMapper userPostMapper;
/**
* 查询岗位信息集合
*
* @param post 岗位信息
* @return 岗位信息集合
*/
@Override
public List<Post> selectPostList(Post post)
{
return postMapper.selectPostList(post);
}
/**
* 查询所有岗位
*
* @return 岗位列表
*/
@Override
public List<Post> selectPostAll()
{
return postMapper.selectPostAll();
}
/**
* 根据用户ID查询岗位
*
* @param userId 用户ID
* @return 岗位列表
*/
@Override
public List<Post> selectPostsByUserId(String userId)
{
List<Post> userPosts = postMapper.selectPostsByUserId(userId);
List<Post> posts = postMapper.selectPostAll();
for (Post post : posts)
{
for (Post userRole : userPosts)
{
if (post.getPostId().longValue() == userRole.getPostId().longValue())
{
post.setFlag(true);
break;
}
}
}
return posts;
}
/**
* 通过岗位ID查询岗位信息
*
* @param postId 岗位ID
* @return 角色对象信息
*/
@Override
public Post selectPostById(Long postId)
{
return postMapper.selectPostById(postId);
}
/**
* 批量删除岗位信息
*
* @param ids 需要删除的数据ID
* @throws Exception
*/
@Override
public int deletePostByIds(String ids) throws BusinessException
{
Long[] postIds = Convert.toLongArray(ids);
for (Long postId : postIds)
{
Post post = selectPostById(postId);
if (countUserPostById(postId) > 0)
{
throw new BusinessException(String.format("%1$s已分配,不能删除", post.getPostName()));
}
}
return postMapper.deletePostByIds(postIds);
}
/**
* 新增保存岗位信息
*
* @param post 岗位信息
* @return 结果
*/
@Override
public int insertPost(Post post)
{
//TODO 获取名称信息,暂时取消在controller中调用
//post.setCreateBy(ShiroUtils.getLoginName());
return postMapper.insertPost(post);
}
/**
* 修改保存岗位信息
*
* @param post 岗位信息
* @return 结果
*/
@Override
public int updatePost(Post post)
{
//TODO 获取名称信息,暂时取消在controller中调用
//post.setUpdateBy(ShiroUtils.getLoginName());
return postMapper.updatePost(post);
}
/**
* 通过岗位ID查询岗位使用数量
*
* @param postId 岗位ID
* @return 结果
*/
@Override
public int countUserPostById(Long postId)
{
return userPostMapper.countUserPostById(postId);
}
/**
* 校验岗位名称是否唯一
*
* @param post 岗位信息
* @return 结果
*/
@Override
public String checkPostNameUnique(Post post)
{
Long postId = StringUtils.isNull(post.getPostId()) ? -1L : post.getPostId();
Post info = postMapper.checkPostNameUnique(post.getPostName());
if (StringUtils.isNotNull(info) && info.getPostId().longValue() != postId.longValue())
{
return UserConstants.POST_NAME_NOT_UNIQUE;
}
return UserConstants.POST_NAME_UNIQUE;
}
/**
* 校验岗位编码是否唯一
*
* @param post 岗位信息
* @return 结果
*/
@Override
public String checkPostCodeUnique(Post post)
{
Long postId = StringUtils.isNull(post.getPostId()) ? -1L : post.getPostId();
Post info = postMapper.checkPostCodeUnique(post.getPostCode());
if (StringUtils.isNotNull(info) && info.getPostId().longValue() != postId.longValue())
{
return UserConstants.POST_CODE_NOT_UNIQUE;
}
return UserConstants.POST_CODE_UNIQUE;
}
}
package com.sinobase.project.system.role.domain;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.sinobase.framework.aspectj.lang.annotation.Excel;
import com.sinobase.framework.web.domain.BaseEntity;
/**
* 角色表 sys_role
*
* @author ruoyi
*/
public class Role extends BaseEntity {
private static final long serialVersionUID = 1L;
/** 角色ID */
@Excel(name = "角色序号")
private String roleId;
/** 角色名称 */
@Excel(name = "角色名称")
private String roleName;
/** 角色权限 */
@Excel(name = "角色权限")
private String roleKey;
/** 角色排序 */
@Excel(name = "角色排序")
private String roleSort;
/** 数据范围(1:所有数据权限;2:自定义数据权限) */
@Excel(name = "数据范围", readConverterExp = "1=所有数据权限,2=自定义数据权限")
private String dataScope;
/** 角色状态(0正常 1停用) */
@Excel(name = "角色状态", readConverterExp = "1=正常,0=停用")
private String status;
/** 删除标志(0代表存在 2代表删除) */
private String delFlag;
/** 用户是否存在此角色标识 默认不存在 */
private boolean flag = false;
/** 菜单组 */
private String[] menuIds;
/** 部门组(数据权限) */
private String[] deptIds;
public String getRoleId() {
return roleId;
}
public void setRoleId(String roleId) {
this.roleId = roleId;
}
public String getDataScope() {
return dataScope;
}
public void setDataScope(String dataScope) {
this.dataScope = dataScope;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getRoleKey() {
return roleKey;
}
public void setRoleKey(String roleKey) {
this.roleKey = roleKey;
}
public String getRoleSort() {
return roleSort;
}
public void setRoleSort(String roleSort) {
this.roleSort = roleSort;
}
public String getStatus() {
return status;
}
public String getDelFlag() {
return delFlag;
}
public void setDelFlag(String delFlag) {
this.delFlag = delFlag;
}
public void setStatus(String status) {
this.status = status;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public String[] getMenuIds() {
return menuIds;
}
public void setMenuIds(String[] menuIds) {
this.menuIds = menuIds;
}
public String[] getDeptIds() {
return deptIds;
}
public void setDeptIds(String[] deptIds) {
this.deptIds = deptIds;
}
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE).append("roleId", getRoleId())
.append("roleName", getRoleName()).append("roleKey", getRoleKey()).append("roleSort", getRoleSort())
.append("dataScope", getDataScope()).append("status", getStatus()).append("delFlag", getDelFlag())
.append("createBy", getCreateBy()).append("createTime", getCreateTime())
.append("updateBy", getUpdateBy()).append("updateTime", getUpdateTime()).append("remark", getRemark())
.toString();
}
}
package com.sinobase.project.system.role.domain;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
/**
* 角色和部门关联 sys_role_dept
*
* @author sinobase
*/
public class RoleDept {
/** 角色ID */
private String roleId;
/** 部门ID */
private String deptId;
public String getRoleId() {
return roleId;
}
public void setRoleId(String roleId) {
this.roleId = roleId;
}
public String getDeptId() {
return deptId;
}
public void setDeptId(String deptId) {
this.deptId = deptId;
}
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE).append("roleId", getRoleId())
.append("deptId", getDeptId()).toString();
}
}
package com.sinobase.project.system.role.domain;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
/**
* 角色和菜单关联 sys_role_menu
*/
public class RoleMenu {
/** 角色ID */
private String roleId;
/** 菜单ID */
private String menuId;
public String getRoleId() {
return roleId;
}
public void setRoleId(String roleId) {
this.roleId = roleId;
}
public String getMenuId() {
return menuId;
}
public void setMenuId(String menuId) {
this.menuId = menuId;
}
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE).append("roleId", getRoleId())
.append("menuId", getMenuId()).toString();
}
}
package com.sinobase.project.system.role.mapper;
import java.util.List;
import com.sinobase.project.system.role.domain.RoleDept;
/**
* 角色与部门关联表 数据层
*
* @author sinobase
*/
public interface RoleDeptMapper {
/**
* 通过角色ID删除角色和部门关联
*
* @param roleId 角色ID
* @return 结果
*/
public int deleteRoleDeptByRoleId(String roleId);
/**
* 批量删除角色部门关联信息
*
* @param ids 需要删除的数据ID
* @return 结果
*/
public int deleteRoleDept(String[] ids);
/**
* 查询部门使用数量
*
* @param deptId 部门ID
* @return 结果
*/
public int selectCountRoleDeptByDeptId(String deptId);
/**
* 批量新增角色部门信息
*
* @param roleDeptList 角色部门列表
* @return 结果
*/
public int batchRoleDept(List<RoleDept> roleDeptList);
}
package com.sinobase.project.system.role.mapper;
import java.util.List;
import com.sinobase.project.system.role.domain.Role;
/**
* 角色表 数据层
*
* @author sinobase
*/
public interface RoleMapper {
/**
* 根据条件分页查询角色数据
*
* @param role 角色信息
* @return 角色数据集合信息
*/
public List<Role> selectRoleList(Role role);
/**
* 根据用户ID查询角色
*
* @param userId 用户ID
* @return 角色列表
*/
public List<Role> selectRolesByUserId(String userId);
/**
* 通过角色ID查询角色
*
* @param roleId 角色ID
* @return 角色对象信息
*/
public Role selectRoleById(String roleId);
/**
* 通过角色ID删除角色
*
* @param roleId 角色ID
* @return 结果
*/
public int deleteRoleById(String roleId);
/**
* 批量角色用户信息
*
* @param ids 需要删除的数据ID
* @return 结果
*/
public int deleteRoleByIds(String[] ids);
/**
* 修改角色信息
*
* @param role 角色信息
* @return 结果
*/
public int updateRole(Role role);
/**
* 新增角色信息
*
* @param role 角色信息
* @return 结果
*/
public int insertRole(Role role);
/**
* 校验角色名称是否唯一
*
* @param roleName 角色名称
* @return 角色信息
*/
public Role checkRoleNameUnique(String roleName);
/**
* 校验角色权限是否唯一
*
* @param roleKey 角色权限
* @return 角色信息
*/
public Role checkRoleKeyUnique(String roleKey);
/**
* 获取角色最新ID(role_id列最大值+1)
* @return
*/
public String getID();
}
package com.sinobase.project.system.role.mapper;
import java.util.List;
import com.sinobase.project.system.role.domain.RoleMenu;
/**
* 角色与菜单关联表 数据层
*
* @author sinobase
*/
public interface RoleMenuMapper {
/**
* 通过角色ID删除角色和菜单关联
*
* @param roleId 角色ID
* @return 结果
*/
public int deleteRoleMenuByRoleId(String roleId);
/**
* 批量删除角色菜单关联信息
*
* @param ids 需要删除的数据ID
* @return 结果
*/
public int deleteRoleMenu(String[] ids);
/**
* 查询菜单使用数量
*
* @param menuId 菜单ID
* @return 结果
*/
public int selectCountRoleMenuByMenuId(String menuId);
/**
* 批量新增角色菜单信息
*
* @param roleMenuList 角色菜单列表
* @return 结果
*/
public int batchRoleMenu(List<RoleMenu> roleMenuList);
}
package com.sinobase.project.system.role.service;
import java.util.List;
import java.util.Set;
import com.sinobase.project.system.role.domain.Role;
import com.sinobase.project.system.user.domain.UserRole;
/**
* 角色业务层
*/
public interface IRoleService {
/**
* 根据条件分页查询角色数据
* @param role 角色信息
* @return 角色数据集合信息
*/
public List<Role> selectRoleList(Role role);
/**
* 根据用户ID查询角色
*
* @param userId 用户ID
* @return 权限列表
*/
public Set<String> selectRoleKeys(String userId);
/**
* 根据用户ID查询角色
*
* @param userId 用户ID
* @return 角色列表
*/
public List<Role> selectRolesByUserId(String userId);
/**
* 查询所有角色
* @return 角色列表
*/
public List<Role> selectRoleAll();
/**
* 通过角色ID查询角色
* @param roleId 角色ID
* @return 角色对象信息
*/
public Role selectRoleById(String roleId);
/**
* 通过角色ID删除角色
*
* @param roleId 角色ID
* @return 结果
*/
public boolean deleteRoleById(String roleId);
/**
* 批量删除角色用户信息
* @param ids 需要删除的数据ID
* @return 结果
* @throws Exception 异常
*/
public int deleteRoleByIds(String ids) throws Exception;
/**
* 新增保存角色信息
*
* @param role 角色信息
* @return 结果
*/
public int insertRole(Role role);
/**
* 修改保存角色信息
* @param role 角色信息
* @return 结果
*/
public int updateRole(Role role);
/**
* 修改数据权限信息
*
* @param role 角色信息
* @return 结果
*/
public int updateRule(Role role);
/**
* 校验角色名称是否唯一
* @param role 角色信息
* @return 结果
*/
public String checkRoleNameUnique(Role role);
/**
* 校验角色权限是否唯一
*
* @param role 角色信息
* @return 结果
*/
public String checkRoleKeyUnique(Role role);
/**
* 通过角色ID查询角色使用数量
* @param roleId 角色ID
* @return 结果
*/
public int countUserRoleByRoleId(String roleId);
/**
* 角色状态修改
* @param role 角色信息
* @return 结果
*/
public int changeStatus(Role role);
/**
* 获取角色最新ID(role_id列最大值+1)
* @return
*/
public String getID();
/**
* 取消授权用户角色
*
* @param userRole 用户和角色关联信息
* @return 结果
*/
public int deleteAuthUser(UserRole userRole);
/**
* 批量取消授权用户角色
*
* @param roleId 角色ID
* @param userIds 需要删除的用户数据ID
* @return 结果
*/
public int deleteAuthUsers(String roleId, String userIds);
/**
* 批量选择授权用户角色
*
* @param roleId 角色ID
* @param userIds 需要删除的用户数据ID
* @return 结果
*/
public int insertAuthUsers(String roleId, String userIds);
}
package com.sinobase.project.system.role.service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.sinobase.common.constant.UserConstants;
import com.sinobase.common.exception.BusinessException;
import com.sinobase.common.support.Convert;
import com.sinobase.common.utils.StringUtils;
import com.sinobase.framework.aspectj.lang.annotation.DataScope;
import com.sinobase.project.system.role.domain.Role;
import com.sinobase.project.system.role.domain.RoleDept;
import com.sinobase.project.system.role.domain.RoleMenu;
import com.sinobase.project.system.role.mapper.RoleDeptMapper;
import com.sinobase.project.system.role.mapper.RoleMapper;
import com.sinobase.project.system.role.mapper.RoleMenuMapper;
import com.sinobase.project.system.user.domain.UserRole;
import com.sinobase.project.system.user.mapper.UserRoleMapper;
/**
* 角色 业务层处理
*
* @author sinobase
*/
@Service
public class RoleServiceImpl implements IRoleService {
@Autowired
private RoleMapper roleMapper;
@Autowired
private RoleMenuMapper roleMenuMapper;
@Autowired
private UserRoleMapper userRoleMapper;
@Autowired
private RoleDeptMapper roleDeptMapper;
/**
* 根据条件分页查询角色数据
*
* @param role 角色信息
* @return 角色数据集合信息
*/
@Override
@DataScope(tableAlias = "u")
public List<Role> selectRoleList(Role role) {
return roleMapper.selectRoleList(role);
}
/**
* 根据用户ID查询权限
*
* @param userId 用户ID
* @return 权限列表
*/
@Override
public Set<String> selectRoleKeys(String userId) {
List<Role> perms = roleMapper.selectRolesByUserId(userId);
Set<String> permsSet = new HashSet<>();
for (Role perm : perms) {
if (StringUtils.isNotNull(perm)) {
permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
}
}
return permsSet;
}
/**
* 根据用户ID查询角色
*
* @param userId 用户ID
* @return 角色列表
*/
@Override
public List<Role> selectRolesByUserId(String userId) {
List<Role> userRoles = roleMapper.selectRolesByUserId(userId);
List<Role> roles = selectRoleAll();
for (Role role : roles) {
for (Role userRole : userRoles) {
if (role.getRoleId().equals(userRole.getRoleId())) {
role.setFlag(true);
break;
}
}
}
return roles;
}
/**
* 查询所有角色
*
* @return 角色列表
*/
@Override
public List<Role> selectRoleAll() {
return selectRoleList(new Role());
}
/**
* 通过角色ID查询角色
*
* @param roleId 角色ID
* @return 角色对象信息
*/
@Override
public Role selectRoleById(String roleId) {
return roleMapper.selectRoleById(roleId);
}
/**
* 通过角色ID删除角色
*
* @param roleId 角色ID
* @return 结果
*/
@Override
public boolean deleteRoleById(String roleId) {
return roleMapper.deleteRoleById(roleId) > 0 ? true : false;
}
/**
* 批量删除角色信息
*
* @param ids 需要删除的数据ID
* @throws Exception
*/
@Override
public int deleteRoleByIds(String ids) throws BusinessException {
String[] roleIds = Convert.toStrArray(ids);
for (String roleId : roleIds) {
Role role = selectRoleById(roleId);
if (countUserRoleByRoleId(roleId) > 0) {
throw new BusinessException(String.format("%1$s已分配,不能删除", role.getRoleName()));
}
}
return roleMapper.deleteRoleByIds(roleIds);
}
/**
* 新增保存角色信息
*
* @param role 角色信息
* @return 结果
*/
@Override
@Transactional
public int insertRole(Role role) {
//TODO 获取名称信息,暂时取消在controller中调用
//role.setCreateBy(ShiroUtils.getLoginName());
if (StringUtils.isEmpty(role.getRoleId())) {
role.setRoleId(roleMapper.getID());
}
// 新增角色信息
roleMapper.insertRole(role);
//ShiroUtils.clearCachedAuthorizationInfo();
return insertRoleMenu(role);
}
/**
* 修改保存角色信息
*
* @param role 角色信息
* @return 结果
*/
@Override
@Transactional
public int updateRole(Role role) {
//TODO 获取名称信息,暂时取消在controller中调用
//role.setUpdateBy(ShiroUtils.getLoginName());
// 修改角色信息
roleMapper.updateRole(role);
//ShiroUtils.clearCachedAuthorizationInfo();
// 删除角色与菜单关联
roleMenuMapper.deleteRoleMenuByRoleId(role.getRoleId());
return insertRoleMenu(role);
}
/**
* 修改数据权限信息
*
* @param role 角色信息
* @return 结果
*/
@Override
@Transactional
public int updateRule(Role role) {
//TODO 获取名称信息,暂时取消在controller中调用
//role.setUpdateBy(ShiroUtils.getLoginName());
// 修改角色信息
roleMapper.updateRole(role);
// 删除角色与部门关联
roleDeptMapper.deleteRoleDeptByRoleId(role.getRoleId());
// 新增角色和部门信息(数据权限)
return insertRoleDept(role);
}
/**
* 新增角色菜单信息
*
* @param role 角色对象
*/
public int insertRoleMenu(Role role) {
int rows = 1;
// 新增用户与角色管理
List<RoleMenu> list = new ArrayList<RoleMenu>();
for (String menuId : role.getMenuIds()) {
RoleMenu rm = new RoleMenu();
rm.setRoleId(role.getRoleId());
rm.setMenuId(menuId);
list.add(rm);
}
if (list.size() > 0) {
rows = roleMenuMapper.batchRoleMenu(list);
}
return rows;
}
/**
* 新增角色部门信息(数据权限)
*
* @param role 角色对象
*/
public int insertRoleDept(Role role) {
int rows = 1;
// 新增角色与部门(数据权限)管理
List<RoleDept> list = new ArrayList<RoleDept>();
for (String deptId : role.getDeptIds()) {
RoleDept rd = new RoleDept();
rd.setRoleId(role.getRoleId());
rd.setDeptId(deptId);
list.add(rd);
}
if (list.size() > 0) {
rows = roleDeptMapper.batchRoleDept(list);
}
return rows;
}
/**
* 校验角色名称是否唯一
*
* @param role 角色信息
* @return 结果
*/
@Override
public String checkRoleNameUnique(Role role) {
String roleId = StringUtils.isNull(role.getRoleId()) ? "" : role.getRoleId();
Role info = roleMapper.checkRoleNameUnique(role.getRoleName());
if (StringUtils.isNotNull(info) && !roleId.equals(info.getRoleId())) {
return UserConstants.ROLE_NAME_NOT_UNIQUE;
}
return UserConstants.ROLE_NAME_UNIQUE;
}
/**
* 校验角色权限是否唯一
*
* @param role 角色信息
* @return 结果
*/
@Override
public String checkRoleKeyUnique(Role role) {
String roleId = StringUtils.isNull(role.getRoleId()) ? "" : role.getRoleId();
Role info = roleMapper.checkRoleKeyUnique(role.getRoleKey());
if (StringUtils.isNotNull(info) && !roleId.equals(info.getRoleId())) {
return UserConstants.ROLE_KEY_NOT_UNIQUE;
}
return UserConstants.ROLE_KEY_UNIQUE;
}
/**
* 通过角色ID查询角色使用数量
*
* @param roleId 角色ID
* @return 结果
*/
@Override
public int countUserRoleByRoleId(String roleId) {
return userRoleMapper.countUserRoleByRoleId(roleId);
}
/**
* 角色状态修改
*
* @param role 角色信息
* @return 结果
*/
@Override
public int changeStatus(Role role) {
return roleMapper.updateRole(role);
}
@Override
public String getID() {
return roleMapper.getID();
}
/**
* 取消授权用户角色
*
* @param userRole 用户和角色关联信息
* @return 结果
*/
@Override
public int deleteAuthUser(UserRole userRole) {
return userRoleMapper.deleteUserRoleInfo(userRole);
}
/**
* 批量取消授权用户角色
*
* @param roleId 角色ID
* @param userIds 需要删除的用户数据ID
* @return 结果
*/
public int deleteAuthUsers(String roleId, String userIds) {
return userRoleMapper.deleteUserRoleInfos(roleId, Convert.toStrArray(userIds));
}
/**
* 批量选择授权用户角色
*
* @param roleId 角色ID
* @param userIds 需要删除的用户数据ID
* @return 结果
*/
public int insertAuthUsers(String roleId, String userIds) {
String[] users = Convert.toStrArray(userIds);
// 新增用户与角色管理
List<UserRole> list = new ArrayList<UserRole>();
for (String userId : users) {
UserRole ur = new UserRole();
ur.setUserId(userId);
ur.setRoleId(roleId);
list.add(ur);
}
return userRoleMapper.batchUserRole(list);
}
}
# 用户信息
这个文件是我 *(韩冬冬)* 在2020.07.02 时开发位于首页的 **用户登录人数统计** 功能的代码时新添加的文档。
## 系统在线人数
* Controller: `com.sinobase.project.system.user.controller.IndexController.java`
* 页面: `/sinobase-web/src/main/resources/templates/workbench/index.html`
* 登录记录查询Mapper类:`/sinobase-web/src/main/java/com/sinobase/project/system/user/mapper/LoginHistoryLogMapper.java`
* Service接口:`com.sinobase.project.system.user.service.ILoginHistoryLogService.java`
* Service实现类:`com.sinobase.project.system.user.service.LoginHistoryLogServiceImpl.java`
Controller中的代码:
```
@GetMapping("/workbench/index")
public String workbench(ModelMap mmap){
//这个类是之前就有的,只是在这里调用了查询在线和登录人数的信息
}
```
实现思路:
1. 页面中直接通过 *thymeleaf标签* 从request中读取数据。
2.`IndexController.java` 类中注入Shiro的 `SessionDAO`对象,然后获取所有的session数量,也就是在线人数。
3. 因为有老系统的历史记录,登录的历史记录由老系统写入到Oracle数据库。当前系统只从Oracle的 `login_history_log` 表读取数据,不负责记录。
> 因为系统采用nginx反向代码实现负载,所以要保证数据相对准确,请使用Redis做为ShiroSessionDao的缓存。
\ No newline at end of file
package com.sinobase.project.system.user.domain;
import com.sinobase.framework.aspectj.lang.annotation.Excel;
import com.sinobase.framework.web.domain.BaseEntity;
import com.sinobase.project.system.dept.domain.Dept;
import com.sinobase.project.system.menu.domain.Menu;
import com.sinobase.project.system.role.domain.Role;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* 用户对象 sys_user
* @author sinobase
*/
public class User extends BaseEntity {
private static final long serialVersionUID = 1L;
//------ 单体应用用开始 ------------
/** 角色ID */
private String roleId;
//------ 单体应用用结束 ------------
/** 所在公司id **/
private String companyId;
/** 所在公司名称 **/
private String companyName;
/** 个人快捷方式 **/
private String shortcut;
/** 身份证号码 **/
private String idNo;
/** 用户ID */
@Excel(name = "用户序号")
private String userId;
/** 部门ID */
private String deptId;
/** 部门名称 */
private String deptName;
/** 登录名称 */
@Excel(name = "登录名称")
private String loginName;
/** 用户名称 */
@Excel(name = "用户名称")
private String userName;
/** 用户邮箱 */
@Excel(name = "用户邮箱")
private String email;
/** 手机号码 */
@Excel(name = "手机号码")
private String phonenumber;
//用户座机号码
private String tel;
/** 用户性别 */
@Excel(name = "用户性别", readConverterExp = "0=男,1=女,2=未知")
private String sex;
/** 用户头像 */
private String avatar;
/** 密码 */
private String password;
/** 盐加密 */
private String salt;
/** 帐号状态(0正常 1停用) */
@Excel(name = "帐号状态", readConverterExp = "1=正常,0=停用")
private String status;
/** 删除标志(0代表存在 2代表删除) */
private String delFlag;
/** 最后登陆IP */
@Excel(name = "最后登陆IP")
private String loginIp;
/** 最后登陆时间 */
@Excel(name = "最后登陆时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss")
private Date loginDate;
/** 部门对象 */
@Excel(name = "部门名称", targetAttr = "deptName")
private Dept dept;
/** 国泰历史用户数据id */
private String historyId;
/** 用户身份 */
private String userStatus;
/**手机imei码*/
private String phoneImei;
/**组织编码*/
private String masterCode;
/**部门对象*/
private List<Dept> depts;
/**
*员工编号,统一认证后可能需要员工编号进行登录
*/
private String userCode;
/**
* 身份证
*/
private String idcNumber;
/** 角色集合 */
private List<Role> roles;
/** 系统角色组,以","号分割 */
private String roleIds;
/** 岗位组 */
private Long[] postIds;
/** 业务角色集合 */
private List<Map<String,String>> flowRoles;
/** 系统角色组,以","号分割 */
private String flowRoleIds;
/** 资源集合(从平台获取的资源存放在这个属性中) */
private List<Menu> menus;
public String getUserCode() {
return userCode;
}
public void setUserCode(String userCode) {
this.userCode = userCode;
}
public String getIdcNumber() {
return idcNumber;
}
public void setIdcNumber(String idcNumber) {
this.idcNumber = idcNumber;
}
public List<Dept> getDepts() {
return depts;
}
public void setDepts(List<Dept> depts) {
this.depts = depts;
}
public String getCompanyId() {
return companyId;
}
public void setCompanyId(String companyId) {
this.companyId = companyId;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getIdNo() {
return idNo;
}
public void setIdNo(String idNo) {
this.idNo = idNo;
}
public List<Menu> getMenus() {
return menus;
}
public void setMenus(List<Menu> menus) {
this.menus = menus;
}
public String getHistoryId() {
return historyId;
}
public void setHistoryId(String historyId) {
this.historyId = historyId;
}
public String getUserStatus() {
return userStatus;
}
public void setUserStatus(String userStatus) {
this.userStatus = userStatus;
}
public String getPhoneImei() {
return phoneImei;
}
public void setPhoneImei(String phoneImei) {
this.phoneImei = phoneImei;
}
public String getMasterCode() {
return masterCode;
}
public void setMasterCode(String masterCode) {
this.masterCode = masterCode;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public boolean isAdmin() {
return isAdmin(this.userId);
}
public static boolean isAdmin(String userId) {
return userId != null && userId.equals("1".toString());
}
public String getDeptId() {
return deptId;
}
public void setDeptId(String deptId) {
this.deptId = deptId;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhonenumber() {
return phonenumber;
}
public void setPhonenumber(String phonenumber) {
this.phonenumber = phonenumber;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
/**
* 生成随机盐
*/
public void randomSalt() {
// 一个Byte占两个字节,此处生成的3字节,字符串长度为6
SecureRandomNumberGenerator secureRandom = new SecureRandomNumberGenerator();
String hex = secureRandom.nextBytes(3).toHex();
setSalt(hex);
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getDelFlag() {
return delFlag;
}
public void setDelFlag(String delFlag) {
this.delFlag = delFlag;
}
public String getLoginIp() {
return loginIp;
}
public void setLoginIp(String loginIp) {
this.loginIp = loginIp;
}
public Date getLoginDate() {
return loginDate;
}
public void setLoginDate(Date loginDate) {
this.loginDate = loginDate;
}
public Dept getDept() {
return dept;
}
public void setDept(Dept dept) {
this.dept = dept;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public String getRoleIds() {
return roleIds;
}
public void setRoleIds(String roleIds) {
this.roleIds = roleIds;
}
public Long[] getPostIds() {
return postIds;
}
public void setPostIds(Long[] postIds) {
this.postIds = postIds;
}
public List<Map<String, String>> getFlowRoles() {
return flowRoles;
}
public void setFlowRoles(List<Map<String, String>> flowRoles) {
this.flowRoles = flowRoles;
}
public String getFlowRoleIds() {
return flowRoleIds;
}
public void setFlowRoleIds(String flowRoleIds) {
this.flowRoleIds = flowRoleIds;
}
public String getShortcut() {
return shortcut;
}
public void setShortcut(String shortcut) {
this.shortcut = shortcut;
}
@Override
public String toString() {
return "User{" +
"userId='" + userId + '\'' +
", deptId='" + deptId + '\'' +
", deptName='" + deptName + '\'' +
", loginName='" + loginName + '\'' +
", userName='" + userName + '\'' +
", email='" + email + '\'' +
", phonenumber='" + phonenumber + '\'' +
", sex='" + sex + '\'' +
", avatar='" + avatar + '\'' +
", password='" + password + '\'' +
", salt='" + salt + '\'' +
", status='" + status + '\'' +
", delFlag='" + delFlag + '\'' +
", loginIp='" + loginIp + '\'' +
", loginDate=" + loginDate +
", dept=" + dept +
", historyId='" + historyId + '\'' +
", userStatus='" + userStatus + '\'' +
", phoneImei='" + phoneImei + '\'' +
", masterCode='" + masterCode + '\'' +
", depts=" + depts +
", roles=" + roles +
", roleIds='" + roleIds + '\'' +
", postIds=" + Arrays.toString(postIds) +
", menus=" + menus +
", userCode=" + userCode +
", idcNumber=" + idcNumber +
'}';
}
public String getRoleId() {
return roleId;
}
public void setRoleId(String roleId) {
this.roleId = roleId;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
}
package com.sinobase.project.system.user.domain;
import java.io.Serializable;
import com.baomidou.mybatisplus.annotation.TableName;
/**
* 用户部门关系表
* @author LouBin
*/
@TableName(value = "sys_user_dprb")
public class UserDprb implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String userId;
private String deptId;
private int orderNo;
private String status;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getDeptId() {
return deptId;
}
public void setDeptId(String deptId) {
this.deptId = deptId;
}
public int getOrderNo() {
return orderNo;
}
public void setOrderNo(int orderNo) {
this.orderNo = orderNo;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
package com.sinobase.project.system.user.domain;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
/**
* 用户和岗位关联 sys_user_post
*
* @author sinobase
*/
public class UserPost
{
/** 用户ID */
private String userId;
/** 岗位ID */
private Long postId;
public String getUserId()
{
return userId;
}
public void setUserId(String userId)
{
this.userId = userId;
}
public Long getPostId()
{
return postId;
}
public void setPostId(Long postId)
{
this.postId = postId;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("userId", getUserId())
.append("postId", getPostId())
.toString();
}
}
package com.sinobase.project.system.user.domain;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
/**
* 用户和角色关联 sys_user_role
*
* @author sinobase
*/
public class UserRole {
/** 用户ID */
private String userId;
/** 角色ID */
private String roleId;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getRoleId() {
return roleId;
}
public void setRoleId(String roleId) {
this.roleId = roleId;
}
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE).append("userId", getUserId())
.append("roleId", getRoleId()).toString();
}
}
package com.sinobase.project.system.user.domain;
/**
* 用户状态
*
* @author sinobase
*
*/
public enum UserStatus
{
OK("1", "正常"), DISABLE("0", "停用"), DELETED("2", "删除");
private final String code;
private final String info;
UserStatus(String code, String info)
{
this.code = code;
this.info = info;
}
public String getCode()
{
return code;
}
public String getInfo()
{
return info;
}
}
package com.sinobase.project.system.user.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface LoginHistoryLogMapper {
/**
* 获取所有的登录次数
* @return 表中数据的条数,每登录一次就会产生一条记录。
*/
public long getLoginTimesAll();
/**
* 获取某天的登录次数,yyyy-MM-dd
* @return 根据时间获取某天的登录条数
*/
public long getLoginTimesOfday( @Param("date") String date);
}
package com.sinobase.project.system.user.mapper;
import com.sinobase.framework.web.mapper.BaseMapper;
import com.sinobase.project.system.user.domain.UserDprb;
/**
* 用户部门关系
* @author LouBin
*/
public interface UserDprbMapper extends BaseMapper<UserDprb>{
/**
* 获取用户排序号
* @param deptId 部门id
* @return
*/
public int getOrderNum(String deptId);
}
package com.sinobase.project.system.user.mapper;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import com.sinobase.project.system.user.domain.User;
/**
* 用户表 数据层
*
* @author sinobase
*/
@Mapper
public interface UserMapper{
/**
* 根据条件分页查询用户对象
* @param user 用户信息
* @return 用户信息集合信息
*/
public List<User> selectUserList(User user);
/**
* 集成公司平台专用:根据条件分页查询用户对象
* @param user 用户信息
* @return 用户信息集合信息
*/
public List<User> selectUserListForPlatform(User user);
/**
* 通过用户名查询用户
* @param userName 用户名
* @return 用户对象信息
*/
public User selectUserByLoginName(String userName);
public User selectUserByLoginNameAndStatus(String userName);
/**
* 通过手机号码查询用户
*
* @param phoneNumber 手机号码
* @return 用户对象信息
*/
public User selectUserByPhoneNumber(String phoneNumber);
/**
* 用户排序
* @param ids
* @return
*/
public int sortSave(String[] ids);
/**
* 通过邮箱查询用户
*
* @param email 邮箱
* @return 用户对象信息
*/
public User selectUserByEmail(String email);
/**
* 通过用户ID查询用户,不暴露隐私数据
*
* @param userId 用户ID
* @return 用户对象信息
*/
public User selectUserById(String userId);
/**
* 通过用户ID查询用户(部门以列表形式返回)
*
* @param userId 用户ID
* @return 用户对象信息
*/
public User selectUserInfoDeptsRolesByUserId(String userId);
/**
* 通过用户ID删除用户
*
* @param userId 用户ID
* @return 结果
*/
public int deleteUserById(String userId);
/**
* 批量删除用户信息
*
* @param ids 需要删除的数据ID
* @return 结果
*/
public int deleteUserByIds(String[] ids);
/**
* 修改用户信息
*
* @param user 用户信息
* @return 结果
*/
public int updateUser(User user);
/**
* 新增用户信息
*
* @param user 用户信息
* @return 结果
*/
public int insertUser(User user);
/**
* 校验用户名称是否唯一
*
* @param user 用户信息
* @return 结果
*/
public int checkLoginNameUnique(User user);
/**
* 校验手机号码是否唯一
*
* @param phonenumber 手机号码
* @return 结果
*/
public User checkPhoneUnique(String phonenumber);
/**
* 校验email是否唯一
*
* @param email 用户邮箱
* @return 结果
*/
public User checkEmailUnique(String email);
/**
* 获取当前表最大ID值
* @return
*/
public int selectMaxId();
/**
* 根据部门ID数组所有所有用户
* @param ids
* @return
*/
public List<User> listUserDetIds(String[] ids);
public List<Map<String,String>> selectUserForSort(String ids);
/** 以下为添加的代码 */
/**
* 将用户添加到本地数据库中
* @param userList
* @return
*/
Integer insertUserByList(List<User> userList);
/**
* 获取当前部门下的用户信息
* @param deptId
* @return
*/
List<User> selectUserListByDeptId(String deptId);
/**
* 根据条件分页查询用户对象
*
* @param user 用户信息
* @return 用户信息集合信息
*/
public List<User> selectUserListByHtml(User user);
/**
* 获取所有用户信息
* @return
*/
List<Map<String, Object>> getAllUser();
/**
* 根据sql添加用户信息
* @param sql
* @return
*/
int insertUserBySql(@Param(value = "sql") String sql);
/**
* 根据用户ID数组获取用户列表
* @param ids
* @return
*/
List<User> listUserByUserId(String [] ids);
/**
* 获取当前部门以及子部门的所有用户信息
* @param username
*
* @param deptId
* @return
*/
public List<Map<String, Object>> getAllChildren(@Param(value = "ancestors")String ancestors, @Param(value = "username")String username);
/**
* 根据条件分页查询未已配用户角色列表
*
* @param user 用户信息
* @return 用户信息集合信息
*/
public List<User> selectAllocatedList(User user);
/**
* 根据条件分页查询未分配用户角色列表
*
* @param user 用户信息
* @return 用户信息集合信息
*/
public List<User> selectUnallocatedList(User user);
/**
* 通过八位码查询用户
* @param masterCode
* @return
*/
User selectUserByMasterCode(@Param("masterCode")String masterCode);
/**
* 根据部门简称获取部门下相关综合账号信息
* @param deptShort
* @return list map-key=[ u.user_id,u.dept_id,u.login_name,u.user_name,d.parent_id,d.dept_short,d.dept_name,d.note,de.dept_short as parent_short ]
*/
public List<Map<String, String>> getUserZHByDeptShort(@Param("deptShort")String deptShort);
/**
* 根据部门简称获取部门下相关综合账号信息
* @param deptShort
* @return list map-key=[ u.user_id,u.dept_id,u.login_name,u.user_name,d.parent_id,d.dept_short,d.dept_name,d.note,de.dept_short as parent_short ]
*/
public List<Map<String, String>> getUserZHByDeptShorts(@Param("deptShorts")String[] deptShorts);
}
package com.sinobase.project.system.user.mapper;
import com.sinobase.project.system.user.domain.UserPost;
import java.util.List;
/**
* 用户与岗位 表 数据层
*
* @author sinobase
*/
public interface UserPostMapper {
/**
* 通过用户ID删除用户和岗位关联
*
* @param userId 用户ID
* @return 结果
*/
public int deleteUserPostByUserId(String userId);
/**
* 通过岗位ID查询岗位使用数量
*
* @param postId 岗位ID
* @return 结果
*/
public int countUserPostById(Long postId);
/**
* 批量删除用户和岗位关联
*
* @param ids 需要删除的数据ID
* @return 结果
*/
public int deleteUserPost(String[] ids);
/**
* 批量新增用户岗位信息
*
* @param userPostList 用户角色列表
* @return 结果
*/
public int batchUserPost(List<UserPost> userPostList);
}
package com.sinobase.project.system.user.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.sinobase.project.system.user.domain.UserRole;
/**
* 用户表 数据层
*
* @author sinobase
*/
public interface UserRoleMapper {
/**
* 通过用户ID删除用户和角色关联
*
* @param userId 用户ID
* @return 结果
*/
public int deleteUserRoleByUserId(String userId);
/**
* 批量删除用户和角色关联
*
* @param ids 需要删除的数据ID
* @return 结果
*/
public int deleteUserRole(String[] ids);
/**
* 通过角色ID查询角色使用数量
*
* @param roleId 角色ID
* @return 结果
*/
public int countUserRoleByRoleId(String roleId);
/**
* 批量新增用户角色信息
*
* @param userRoleList 用户角色列表
* @return 结果
*/
public int batchUserRole(List<UserRole> userRoleList);
/**
* 删除用户和角色关联信息
*
* @param userRole 用户和角色关联信息
* @return 结果
*/
public int deleteUserRoleInfo(UserRole userRole);
/**
* 批量取消授权用户角色
*
* @param roleId 角色ID
* @param userIds 需要删除的用户数据ID
* @return 结果
*/
public int deleteUserRoleInfos(@Param("roleId") String roleId, @Param("userIds") String[] userIds);
}
package com.sinobase.project.system.user.service;
public interface ILoginHistoryLogService {
public long getLoginTimesAll();
public long getLoginTimesToday();
}
package com.sinobase.project.system.user.service;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;
import com.sinobase.project.system.user.domain.User;
/**
* 用户 业务层
*
* @author sinobase
*/
public interface IUserService {
/**
* 根据条件分页查询用户对象
* @param user 用户信息
* @return 用户信息集合信息
*/
public List<User> selectUserList(User user);
/**
* 查询用户
* @param user
* @return
*/
public List<User> selectUsers(User user);
/**
* 通过用户名查询用户
*
* @param userName 用户名
* @return 用户对象信息
*/
public User selectUserByLoginName(String userName);
public User selectUserByLoginNameAndStatus(String userName);
/**
* 通过手机号码查询用户
*
* @param phoneNumber 手机号码
* @return 用户对象信息
*/
public User selectUserByPhoneNumber(String phoneNumber);
/**
* 通过邮箱查询用户
*
* @param email 邮箱
* @return 用户对象信息
*/
public User selectUserByEmail(String email);
/**
* 通过用户ID查询用户
*
* @param userId 用户ID
* @return 用户对象信息
*/
public User selectUserById(String userId);
/**
* 通过用户ID查询用户(部门以列表形式返回,不暴露隐私数据)
*
* @param userId 用户ID
* @return 用户对象信息
*/
public User selectUserInfoDeptsRolesByUserId(String userId);
/**
* 通过用户ID删除用户
*
* @param userId 用户ID
* @return 结果
*/
public int deleteUserById(String userId);
/**
* 批量删除用户信息
*
* @param ids 需要删除的数据ID
* @return 结果
* @throws Exception 异常
*/
public int deleteUserByIds(String ids) throws Exception;
/**
* 保存用户信息
*
* @param user 用户信息
* @return 结果
*/
public int insertUser(User user);
/**
* 保存用户信息
*
* @param user 用户信息
* @return 结果
*/
public int updateUser(User user);
/**
* 修改用户详细信息
*
* @param user 用户信息
* @return 结果
*/
public int updateUserInfo(User user);
/**
* 修改用户密码信息
*
* @param user 用户信息
* @return 结果
*/
public int resetUserPwd(User user);
/**
* 校验用户名称是否唯一
*
* @param User user
* @return 结果
*/
public String checkLoginNameUnique(User user);
/**
* 校验手机号码是否唯一
*
* @param user 用户信息
* @return 结果
*/
public String checkPhoneUnique(User user);
/**
* 校验email是否唯一
*
* @param user 用户信息
* @return 结果
*/
public String checkEmailUnique(User user);
/**
* 根据用户ID查询用户所属角色组
*
* @param userId 用户ID
* @return 结果
*/
public String selectUserRoleGroup(String userId);
/**
* 根据用户ID查询用户所属岗位组
*
* @param userId 用户ID
* @return 结果
*/
public String selectUserPostGroup(String userId);
/**
* 获取排序用户
* @param dpetId
* @return
*/
public List<Map<String,String>> selectUserForSort(String dpetId);
/**
* 根据部门ID获取所有用户
* @param ids
* @return
*/
public List<User> listUserDetIds(String[] ids);
/**
* 获取用户树信息
* @param rootId 根节点部门 id
* @param deptId 部门 id
* @return
*/
public List getUserTree(String rootId, String deptId);
/**
* 根据条件分页查询用户对象
*
* @param user 用户信息
* @return 用户信息集合信息
*/
public List<User> selectUserListByHtml(User user);
/**
* 获取所有用户信息 包含部门id
* @return
*/
List<Map<String, Object>> getAllUser();
/**
* 获取部门下的用户信息
* @param deptId
* @return
*/
List<User> selectUserListByDeptId(String deptId);
/**
* 用户排序
* @param ids 用户id
*/
int sortSave(String[] ids);
/**
* 添加用户信息
* @param insertList(用户集合)
* @return
*/
int insertUserByList(List insertList);
/**
* 根据sql添加用户信息
* @param sql
* @return
*/
int insertUserBySql(String sql);
/**
* 根据用户ID数组获取用户信息
* @param ids
* @return
*/
List<User> listUserByUserId(String [] ids);
/**
* 获取当前部门,以及子部门的所有人员信息
*
* @param deptId
* @param json
* @return
*/
public List<Map<String, Object>> getUserSearch(String deptId, String username,JSONObject json);
/**
* 根据条件分页查询已分配用户角色列表
*
* @param user 用户信息
* @return 用户信息集合信息
*/
public List<User> selectAllocatedList(User user);
/**
* 根据条件分页查询未分配用户角色列表
*
* @param user 用户信息
* @return 用户信息集合信息
*/
public List<User> selectUnallocatedList(User user);
/**
* 通过八位码获取 用户信息
* @param masterCode
* @return
*/
User selectUserByMasterCode(String masterCode);
}
package com.sinobase.project.system.user.service;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sinobase.datasource.aspectj.lang.annotation.DataSource;
import com.sinobase.datasource.aspectj.lang.enums.DataSourceType;
import com.sinobase.project.system.user.mapper.LoginHistoryLogMapper;
@Service
@DataSource(DataSourceType.ORACLE)
public class LoginHistoryLogServiceImpl implements ILoginHistoryLogService {
@Autowired
private LoginHistoryLogMapper loginHistoryMapper;
@Override
public long getLoginTimesAll() {
return loginHistoryMapper.getLoginTimesAll();
}
@Override
public long getLoginTimesToday() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(new Date());
// date = "2017-07-03"; //测试数据,因为互联网开发环境没有数据
return loginHistoryMapper.getLoginTimesOfday(date);
}
}
package com.sinobase.project.system.user.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSONObject;
import com.sinobase.common.constant.UserConstants;
import com.sinobase.common.exception.BusinessException;
import com.sinobase.common.utils.IdUtils;
import com.sinobase.common.utils.StringUtils;
import com.sinobase.datasource.aspectj.lang.annotation.DataSource;
import com.sinobase.datasource.aspectj.lang.enums.DataSourceType;
import com.sinobase.framework.aspectj.lang.annotation.DataScope;
import com.sinobase.project.system.dept.domain.Dept;
import com.sinobase.project.system.dept.mapper.DeptMapper;
import com.sinobase.project.system.post.domain.Post;
import com.sinobase.project.system.post.mapper.PostMapper;
import com.sinobase.project.system.role.domain.Role;
import com.sinobase.project.system.role.mapper.RoleMapper;
import com.sinobase.project.system.user.domain.User;
import com.sinobase.project.system.user.domain.UserDprb;
import com.sinobase.project.system.user.domain.UserPost;
import com.sinobase.project.system.user.domain.UserRole;
import com.sinobase.project.system.user.mapper.UserDprbMapper;
import com.sinobase.project.system.user.mapper.UserMapper;
import com.sinobase.project.system.user.mapper.UserPostMapper;
import com.sinobase.project.system.user.mapper.UserRoleMapper;
/**
* 用户 业务层处理
*
* @author sinobase
*/
@Service
@EnableTransactionManagement
public class UserServiceImpl implements IUserService {
@Autowired
private UserMapper userMapper;
@Autowired
private RoleMapper roleMapper;
@Autowired
private PostMapper postMapper;
@Autowired
private UserPostMapper userPostMapper;
@Autowired
private UserRoleMapper userRoleMapper;
@Autowired
private DeptMapper deptMapper;
@Autowired
private UserDprbMapper dprbMapper;
/**
* 根据条件分页查询用户对象
* @param user 用户信息
* @return 用户信息集合信息
*/
@Override
@DataScope(tableAlias = "u")
public List<User> selectUserList(User user) {
// 生成数据权限过滤条件
// return userMapper.selectUserList(user);
return userMapper.selectUserListForPlatform(user);
/**
* if(SinoBaseConfig.isPlatform()){ return
* userMapper.selectUserListForPlatform(user); }else{ return
* userMapper.selectUserList(user); }
**/
}
@Override
@DataScope(tableAlias = "u")
@DataSource(DataSourceType.MASTER)
public List<User> selectUsers(User user) {
// 生成数据权限过滤条件
return userMapper.selectUserListForPlatform(user);
}
/**
* 通过用户名查询用户
* @param userName 用户名
* @return 用户对象信息
*/
@Override
@DataSource(DataSourceType.MASTER)
public User selectUserByLoginName(String userName) {
return userMapper.selectUserByLoginName(userName);
}
@Override
public User selectUserByLoginNameAndStatus(String userName) {
return userMapper.selectUserByLoginNameAndStatus(userName);
}
/**
* 通过手机号码查询用户
* @param phoneNumber 手机号码
* @return 用户对象信息
*/
@Override
public User selectUserByPhoneNumber(String phoneNumber) {
return userMapper.selectUserByPhoneNumber(phoneNumber);
}
@Override
public List<Map<String, String>> selectUserForSort(String dpetId) {
return userMapper.selectUserForSort(dpetId);
}
/**
* 用户排序
*/
public int sortSave(String[] ids) {
return userMapper.sortSave(ids);
}
/**
* 通过邮箱查询用户
* @param email 邮箱
* @return 用户对象信息
*/
@Override
public User selectUserByEmail(String email) {
return userMapper.selectUserByEmail(email);
}
/**
* 通过用户ID查询用户
* @param userId 用户ID
* @return 用户对象信息
*/
@Override
public User selectUserById(String userId) {
return userMapper.selectUserById(userId);
}
/**
* 通过用户ID查询用户(部门以列表形式返回,不暴露隐私数据)
*
* @param userId 用户ID
* @return 用户对象信息
*/
@Override
public User selectUserInfoDeptsRolesByUserId(String userId) {
return userMapper.selectUserInfoDeptsRolesByUserId(userId);
}
/**
* 通过用户ID删除用户
* @param userId 用户ID
* @return 结果
*/
@Override
public int deleteUserById(String userId) {
/*
* // 删除用户与角色关联 userRoleMapper.deleteUserRoleByUserId(userId); //
* 删除用户与岗位表 userPostMapper.deleteUserPostByUserId(userId);
*/
return userMapper.deleteUserById(userId);
}
/**
* 批量删除用户信息
* @param ids 需要删除的数据ID
* @return 结果
*/
@Override
public int deleteUserByIds(String ids) throws BusinessException {
String[] userIds = StringUtils.splitStr2Array(ids, ",");
for (String userId : userIds) {
if (User.isAdmin(userId)) {
throw new BusinessException("不允许删除超级管理员用户");
}
}
return userMapper.deleteUserByIds(userIds);
}
/**
* 新增保存用户信息
* @param user 用户信息
* @return 结果
*/
@Override
public int insertUser(User user) {
user.randomSalt();
//TODO 获取名称信息,暂时取消在controller中调用,密码也暂时不需要
user.setUserId((userMapper.selectMaxId() + 1) + "");
//user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
//user.setCreateBy(ShiroUtils.getLoginName());
UserDprb rel = new UserDprb();
rel.setId(IdUtils.getIdByTime());
rel.setUserId(user.getUserId());
rel.setDeptId(user.getDept().getDeptId());
rel.setOrderNo(dprbMapper.getOrderNum(rel.getDeptId()));
rel.setStatus("1");
int rows = userMapper.insertUser(user); // 新增用户信息
dprbMapper.insert(rel); // 用户部门关系表
insertUserPost(user); // 新增用户岗位关联
insertUserRole(user); // 新增用户与角色管理
return rows;
}
/**
* 修改保存用户信息
* @param user 用户信息
* @return 结果
*/
@Override
public int updateUser(User user) {
String userId = user.getUserId();
//TODO 获取名称信息,暂时取消在controller中调用
//user.setUpdateBy(ShiroUtils.getLoginName());
// 删除用户与角色关联
userRoleMapper.deleteUserRoleByUserId(userId);
// 新增用户与角色管理
insertUserRole(user);
// 删除用户与岗位关联
userPostMapper.deleteUserPostByUserId(userId);
// 新增用户与岗位管理
insertUserPost(user);
return userMapper.updateUser(user);
}
/**
* 修改用户个人详细信息
* @param user 用户信息
* @return 结果
*/
@Override
public int updateUserInfo(User user) {
return userMapper.updateUser(user);
}
/**
* 修改用户密码
* @param user 用户信息
* @return 结果
*/
@Override
public int resetUserPwd(User user) {
user.randomSalt();
//TODO 获取名称信息,暂时取消在controller中调用.密码暂时也不需要
//user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
return updateUserInfo(user);
}
/**
* 新增用户角色信息
* @param user 用户对象
*/
public void insertUserRole(User user) {
// 新增用户与角色管理
List<UserRole> list = new ArrayList<UserRole>();
String[] roles = StringUtils.splitStr2Array(user.getRoleIds(), ",");
for (String role : roles) {
UserRole ur = new UserRole();
ur.setUserId(user.getUserId());
ur.setRoleId(role);
list.add(ur);
}
if (list.size() > 0) {
userRoleMapper.batchUserRole(list);
}
}
/**
* 新增用户岗位信息
* @param user 用户对象
*/
public void insertUserPost(User user) {
// 新增用户与岗位管理
List<UserPost> list = new ArrayList<UserPost>();
for (Long postId : user.getPostIds()) {
UserPost up = new UserPost();
up.setUserId(user.getUserId());
up.setPostId(postId);
list.add(up);
}
if (list.size() > 0) {
userPostMapper.batchUserPost(list);
}
}
/**
* 校验用户名称是否唯一
* @param loginName 用户名
* @return
*/
@Override
public String checkLoginNameUnique(User user) {
int count = userMapper.checkLoginNameUnique(user);
if (count > 0) {
return UserConstants.USER_NAME_NOT_UNIQUE;
}
return UserConstants.USER_NAME_UNIQUE;
}
/**
* 校验用户名称是否唯一
* @param user 用户信息
* @return
*/
@Override
public String checkPhoneUnique(User user) {
String userId = StringUtils.isNull(user.getUserId()) ? "-1" : user.getUserId();
User info = userMapper.checkPhoneUnique(user.getPhonenumber());
if (StringUtils.isNotNull(info) && !info.getUserId().equals(userId)) {
return UserConstants.USER_PHONE_NOT_UNIQUE;
}
return UserConstants.USER_PHONE_UNIQUE;
}
/**
* 校验email是否唯一
* @param user 用户信息
* @return
*/
@Override
public String checkEmailUnique(User user) {
String userId = StringUtils.isNull(user.getUserId()) ? "-1" : user.getUserId();
User info = userMapper.checkEmailUnique(user.getEmail());
if (StringUtils.isNotNull(info) && !info.getUserId().equals(userId)) {
return UserConstants.USER_EMAIL_NOT_UNIQUE;
}
return UserConstants.USER_EMAIL_UNIQUE;
}
/**
* 查询用户所属角色组
* @param userId 用户ID
* @return 结果
*/
@Override
public String selectUserRoleGroup(String userId) {
List<Role> list = roleMapper.selectRolesByUserId(userId);
StringBuffer idsStr = new StringBuffer();
for (Role role : list) {
idsStr.append(role.getRoleName()).append(",");
}
if (StringUtils.isNotEmpty(idsStr.toString())) {
return idsStr.substring(0, idsStr.length() - 1);
}
return idsStr.toString();
}
/**
* 查询用户所属岗位组
* @param userId 用户ID
* @return 结果
*/
@Override
public String selectUserPostGroup(String userId) {
List<Post> list = postMapper.selectPostsByUserId(userId);
StringBuffer idsStr = new StringBuffer();
for (Post post : list) {
idsStr.append(post.getPostName()).append(",");
}
if (StringUtils.isNotEmpty(idsStr.toString())) {
return idsStr.substring(0, idsStr.length() - 1);
}
return idsStr.toString();
}
@Override
public List<User> listUserDetIds(String[] ids) {
return userMapper.listUserDetIds(ids);
}
/**
* 根据条件分页查询用户对象
* @param user 用户信息
* @return 用户信息集合信息
*/
@Override
@DataScope(tableAlias = "u")
public List<User> selectUserListByHtml(User user) {
// 生成数据权限过滤条件
return userMapper.selectUserListByHtml(user);
}
/************************************ 添加的代码 ******************************/
/**
* 添加用户信息
* @param insertList(用户集合)
* @return
*/
@Override
@Transactional
public int insertUserByList(List insertList) {
return userMapper.insertUserByList(insertList);
}
/**
* 获取用户树信息
* @param rootId 根节点部门 id
* @param deptId 部门 id
* @return
*/
@Override
public List getUserTree(String rootId, String deptId) {
String id = null;
if (deptId != null && !"".equals(deptId)) {
id = deptId;
} else {
id = rootId;
}
Map<String, Object> res = new LinkedHashMap<String, Object>();
if (deptId == null || "".equals(deptId)) {
// 获取部门信息
Dept dept = deptMapper.selectDeptById(id);
if (dept != null) {
res.put("id", dept.getDeptId());
res.put("historyId", dept.getHistoryId());
res.put("name", dept.getDeptShort());
res.put("parentId", dept.getParentId());
res.put("isParent", dept.getHasChildren());
res.put("isLeaf", false);
res.put("iconSkin", "dept");
res.put("nocheck", true);
res.put("fromUnit", dept.getFromUnit());
}
}
List<Map<String, Object>> list = new LinkedList<Map<String, Object>>();
// 获取子部门信息
List<Dept> deptList = deptMapper.selectDeptListsByDeptId(id);
// if (deptList.size() > 0) {
for (Dept depttemp : deptList) {
// List<Dept> childrenDepts =
// deptMapper.selectDeptListsByDeptId(depttemp.getDeptId());
if ("true".equals(depttemp.getHasChildren())) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", depttemp.getDeptId());
map.put("historyId", depttemp.getHistoryId());
map.put("name", depttemp.getDeptShort());
map.put("parentId", depttemp.getParentId());
map.put("isParent", "true");
map.put("isLeaf", false);
map.put("iconSkin", "dept");
map.put("nocheck", true);
map.put("fromUnit", depttemp.getFromUnit());
list.add(map);
}
}
// } else {g
// 获取部门下的用户信息
List<User> userList = userMapper.selectUserListByDeptId(id);
if (userList.size() > 0) {
for (User user : userList) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", user.getUserId());
map.put("historyId", user.getHistoryId());
map.put("name", user.getUserName());
map.put("parentId", id);
map.put("isLeaf", true);
map.put("iconSkin", "user");
list.add(map);
}
}
// }
List result = new ArrayList();
if (deptId == null || "".equals(deptId)) {
res.put("children", list);
result.add(res);
} else {
result = list;
}
return result;
}
/**
* 获取本地所有用户信息系
* @return
*/
@Override
public List<Map<String, Object>> getAllUser() {
return userMapper.getAllUser();
}
/**
* 获取部门下的用户信息
* @param deptId
* @return
*/
@Override
public List<User> selectUserListByDeptId(String deptId) {
return userMapper.selectUserListByDeptId(deptId);
}
/**
* 根据sql添加用户信息
*/
@Override
@DataSource(value = DataSourceType.SLAVE) // 使用从数据库
public int insertUserBySql(String sql) {
return userMapper.insertUserBySql(sql);
}
/************************* wsj **************************/
@Override
public List<User> listUserByUserId(String[] ids) {
return userMapper.listUserByUserId(ids);
}
@Override
public List<Map<String, Object>> getUserSearch(String deptId, String username, JSONObject json) {
Dept dept = deptMapper.selectDeptById(deptId);
List<Map<String, Object>> list = new LinkedList<Map<String, Object>>();
List<Map<String, Object>> users = userMapper.getAllChildren(dept.getAncestors(), username);
if (users.size() > 0) {
for (Map<String, Object> user : users) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", user.get("user_id").toString());
map.put("historyId", user.get("history_id").toString());
map.put("name", user.get("user_name").toString());
map.put("deptName", user.get("dept_name").toString());
map.put("companyName", user.get("company_name") != null ? user.get("company_name").toString() : "");
map.put("fullName", user.get("user_name").toString() + '/' + user.get("dept_short").toString());
map.put("parentId", user.get("dept_id").toString());
map.put("isLeaf", true);
map.put("iconSkin", "user");
list.add(map);
}
}
return list;
}
/**
* 根据条件分页查询已分配用户角色列表
*
* @param user 用户信息
* @return 用户信息集合信息
*/
public List<User> selectAllocatedList(User user) {
return userMapper.selectAllocatedList(user);
}
/**
* 根据条件分页查询未分配用户角色列表
*
* @param user 用户信息
* @return 用户信息集合信息
*/
public List<User> selectUnallocatedList(User user) {
return userMapper.selectUnallocatedList(user);
}
@Override
public User selectUserByMasterCode(String masterCode)
{
return userMapper.selectUserByMasterCode(masterCode);
}
}
package com.sinobase.project.system.user.utils;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Calendar;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
@Component
public class BitchUtil {
private static final Logger log = LoggerFactory.getLogger(BitchUtil.class);
String ssoService;
public String getSsoService() {
return ssoService;
}
public void setSsoService(String ssoService) {
this.ssoService = ssoService;
}
public void setCookie(HttpServletRequest request, HttpServletResponse response, String profiles) throws Exception {
if ("0".equals(request.getParameter("expiry"))) {
CookieUtil.removeCookie(response, "SSOID");
CookieUtil.removeCookie(response, "app_t");
} else {
Boolean flag = setTicket(request, response);
// 票据设置成功
if (flag) {
String gotoURL = request.getParameter("gotoURL");
String ticket = request.getParameter("ticket");
JSONObject userinfo = getUserInfoByTK(ticket);
gotoURL = gotoURL != null ? java.net.URLDecoder.decode(gotoURL, "UTF-8") : gotoURL;
if (gotoURL != null) {
// 如果是开发环境,并且是移动端登录(统一使用 localhost)
if ("dev".equals(profiles)) {
gotoURL = gotoURL.replace("http://localhost:8500/oa/app", "http://localhost:8888");
}
UsernamePasswordToken token = new UsernamePasswordToken(userinfo.getString("username") + "","111111", false);
Subject subject = SecurityUtils.getSubject();
subject.login(token);
response.sendRedirect(gotoURL);
}
}
}
}
public Boolean setTicket(HttpServletRequest request, HttpServletResponse response) throws Exception {
Long currTime = Calendar.getInstance().getTimeInMillis();
System.out.println("ssoService==="+ssoService);
String ticket = request.getParameter("ticket");
JSONObject userinfo = getUserInfoByTK(ticket);
Boolean flag = false;
if (userinfo != null) {
Integer expiry = Integer.parseInt(request.getParameter("expiry"));
String userid = userinfo.get("userid").toString();
String username = userinfo.get("username").toString();
String appTicket = currTime + "-" + userid;
// appTicket = AesUtil.cbcEncrypt(appTicket);
CookieUtil.setCookie(response, "app_t", appTicket, -1);
CookieUtil.setCookie(response, "USER_NAME", URLEncoder.encode(username, "utf-8"), -1);
CookieUtil.setCookie(response, "SSOID", ticket, -1);
flag = true;
}
return flag;
}
public JSONObject getUserInfoByTK(String ticket) throws JSONException, IOException, ServletException {
JSONObject userinfo = null;
NameValuePair[] params = new NameValuePair[2];
params[0] = new NameValuePair("action", "authTicket");
params[1] = new NameValuePair("cookieName", ticket);
log.info("ticket: " + ticket);
JSONObject result = post(params);
if (result.getBoolean("error")) {// 验证票据失败
return userinfo;
}
userinfo = result.getJSONObject("user");
return userinfo;
}
public void doLogout(HttpServletRequest request, HttpServletResponse response, String ticket)
throws IOException, ServletException {
NameValuePair[] params = new NameValuePair[2];
// 访问统一登录的参数
params[0] = new NameValuePair("action", "doLogout");
// 令牌参数
params[1] = new NameValuePair("cookieName", ticket);
try {
post(params);
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
public JSONObject post(NameValuePair[] params) throws IOException, ServletException, JSONException {
if (ssoService.indexOf("https") != -1) {// https 请求
String requestUrl = ssoService + "/" + params[0].getValue() + "?" + params[1].getName() + "=" + params[1].getValue();
String json = HttpRequestUtil.httpsRequest(requestUrl,HttpRequestUtil.POST).toJSONString();
return new JSONObject().fromObject(json);
} else {// http请求
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(ssoService + "/" + params[0].getValue());
postMethod.addParameters(params);
log.info("uri: "+postMethod.getURI().toString());
int resultCode = httpClient.executeMethod(postMethod);
log.info("resultCode: " + resultCode);
switch (resultCode) {
case HttpStatus.SC_OK:
return new JSONObject().fromObject(postMethod.getResponseBodyAsString());
default:
// 其它处理
return null;
}
}
}
}
/**
* Copyright 2016 SinoSoft. All Rights Reserved.
* 傻逼平台组代码,直接挪过来了
*/
package com.sinobase.project.system.user.utils;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
/**
* <B>系统名称:</B><BR>
* <B>模块名称:</B><BR>
* <B>中文类名:</B><BR>
* <B>概要说明:</B><BR>
*
* @since 2016年11月23日
*/
public class CookieUtil {
private static final String DOMAIN = "";
/**
*
* <B>方法名称:setCookie</B><BR>
* <B>概要说明:建立会话cookie</B><BR>
*
* @param response
* @param cookieName cookie名
* @param cookieValue cookie值
*/
public static void setCookie(HttpServletResponse response, String cookieName,
String cookieValue) {
Cookie cookie = new Cookie(cookieName, cookieValue);
cookie.setMaxAge(-1);
cookie.setPath("/");
if (StringUtils.isNotBlank(DOMAIN)) {
cookie.setDomain(DOMAIN);
}
response.addCookie(cookie);
}
/**
*
* <B>方法名称:setCookie</B><BR>
* <B>概要说明:建立固定生命周期的cookie</B><BR>
*
* @param response
* @param cookieName cookie名
* @param cookieValue cookie值
* @param expiry 生存时间
*/
public static void setCookie(HttpServletResponse response, String cookieName,
String cookieValue, int expiry) {
Cookie cookie = new Cookie(cookieName, cookieValue);
cookie.setMaxAge(expiry);
cookie.setPath("/");
if (StringUtils.isNotBlank(DOMAIN)) {
cookie.setDomain(DOMAIN);
}
response.addCookie(cookie);
}
/**
*
* <B>方法名称:removeCookie</B><BR>
* <B>概要说明:删除cookie</B><BR>
*
* @param response
* @param cookieName cookie名
*/
public static void removeCookie(HttpServletResponse response, String cookieName) {
Cookie cookie = new Cookie(cookieName, null);
cookie.setMaxAge(0);
cookie.setPath("/");
if (StringUtils.isNotBlank(DOMAIN)) {
cookie.setDomain(DOMAIN);
}
cookie.setSecure(false);
response.addCookie(cookie);
}
/**
*
* <B>方法名称:getCookie</B><BR>
* <B>概要说明:获取cookie的值</B><BR>
*
* @param request
* @param cookieName cookie名
* @return String cookie值
*/
public static String getCookie(HttpServletRequest request, String cookieName) {
Cookie[] cookies = request.getCookies();
String cookieValue = null;
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(cookieName)) {
cookieValue = cookie.getValue();
break;
}
}
}
return cookieValue;
}
/**
*
* <B>方法名称:返回当前登录的用户的user_id</B><BR>
* <B>概要说明:</B><BR>
*
* @param request
* @return 返回类型为String
*/
public static String getUserID(HttpServletRequest request) {
String str = request.getAttribute("userid").toString();
if (StringUtils.isNotBlank(str)) {
return str;
}
return null;
}
/**
*
* <B>方法名称:返回当前登录的用户的user_id</B><BR>
* <B>概要说明:</B><BR>
*
* @param request
* @return 返回类型为Long
*/
public static Long getUserid(HttpServletRequest request) {
String str = request.getAttribute("userid").toString();
if (StringUtils.isNotBlank(str)) {
//String uid =AesUtil.cbcDecrypt(str);
return Long.parseLong(str);
}
return null;
}
/**
*
* <B>方法名称:返回当前登录的用户的userNm</B><BR>
* <B>概要说明:</B><BR>
*
* @param request
* @return 返回类型为String
*/
public static String getUserName(HttpServletRequest request) {
String str = getCookie(request, "USER_NAME");
if (StringUtils.isNotBlank(str)) {
try {
str = URLDecoder.decode(str, "UTF-8");
return str;
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
return null;
}
/**
*
* <B>方法名称:返回当前登录的用户的userNm</B><BR>
* <B>概要说明:</B><BR>
*
* @param request
* @return 返回类型为String
*/
public static String getDeptName(HttpServletRequest request) {
String str = getCookie(request, "deptnm");
if (StringUtils.isNotBlank(str)) {
try {
str = URLDecoder.decode(str, "UTF-8");
return str;
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
return null;
}
/**
*
* <B>方法名称:返回当前登录的用户的sysId</B><BR>
* <B>概要说明:</B><BR>
*
* @param request
* @return 返回类型为String
*/
public static String getSysId(HttpServletRequest request) {
String str = getCookie(request, "sysid");
if (StringUtils.isNotBlank(str)) {
return str;
}
return null;
}
/**
*
* <B>方法名称:返回当前登录的用户的orgId</B><BR>
* <B>概要说明:</B><BR>
*
* @param request
* @return 返回类型为String
*/
public static String getOrgId(HttpServletRequest request) {
String str = getCookie(request, "orgid");
if (StringUtils.isNotBlank(str)) {
return str;
}
return null;
}
}
package com.sinobase.project.system.user.utils;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Map;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSONObject;
public class HttpRequestUtil {
public static final String POST = "POST";
public static final String GET = "GET";
public static final String DEFAULT_CHARSET = "UTF-8";
private static Log log = LogFactory.getLog(HttpRequestUtil.class);
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
// 默认统一对参数进行encode编码
return sendGetReq(url, param, true);
}
/**
* 向指定URL发送GET方法的请求,不进行转码
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式,若请求参数不是规范格式请提前对参数进行转码处理
* @return URL 所代表远程资源的响应结果
*/
public static String sendGetNoEncode(String url, String param) {
// 默认统一对参数进行encode编码
return sendGetReq(url, param, false);
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
// 默认统一对参数进行encode编码
return sendPostReq(url, param, true);
}
/**
* 向指定URL发送POST方法的请求,不进行转码
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式,若请求参数不是规范格式请提前对参数进行转码处理
* @return URL 所代表远程资源的响应结果
*/
public static String sendPostNoEncode(String url, String param) {
// 默认统一对参数进行encode编码
return sendPostReq(url, param, false);
}
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @param isEncode
* 是否要对参数进行 Encode 处理, true 进行处理 false 不进行处理
* @return URL 所代表远程资源的响应结果
*/
private static String sendGetReq(String url, String param, Boolean isEncode) {
String result = "";
InputStreamReader reader = null;
try {
String urlNameString = url;
if (StringUtils.isNotBlank(param) && isEncode) {
urlNameString = urlNameString + "?" + settingPar(param);
}
else {
urlNameString = urlNameString + "?" + param;
}
log.debug("接口请求路径:" + urlNameString);
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.setRequestProperty("Accept-Charset", DEFAULT_CHARSET);
connection.setRequestProperty("Content-Type", "text/plain;charset=UTF-8");
connection.setReadTimeout(10000);//设置读取超时时间
connection.setConnectTimeout(10000);//设置连接超时时间
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
log.debug(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
reader = new InputStreamReader(connection.getInputStream(), DEFAULT_CHARSET);
result = reader2String(reader);
}
catch (Exception e) {
log.error("发送GET请求出现异常!", e);
}
// 使用finally块来关闭输入流
finally {
try {
if (reader != null) {
reader.close();
}
}
catch (Exception e2) {
return "";
}
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @param isEncode
* 是否要对参数进行 Encode 处理, true 进行处理 false 不进行处理
*
* @return 所代表远程资源的响应结果
*/
private static String sendPostReq(String url, String param, Boolean isEncode) {
log.debug("begin post service url:" + url);
log.debug("begin post service param:" + param);
PrintWriter out = null;
BufferedReader in = null;
InputStreamReader reader = null;
String result = "";
InputStream input = null;
try {
String urlNameString = url;
if (StringUtils.isNotBlank(param) && isEncode) {
// param = settingPar(param);
urlNameString = urlNameString + "?" + settingPar(param);
}
else {
urlNameString = urlNameString + "?" + param;
}
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", DEFAULT_CHARSET);
conn.setRequestProperty("Content-Type", "text/plain;charset=UTF-8");
conn.setReadTimeout(10000);//设置读取超时时间
conn.setConnectTimeout(10000);//设置连接超时时间
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), DEFAULT_CHARSET));
// 发送请求参数
//out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
input = conn.getInputStream();
reader = new InputStreamReader(input, DEFAULT_CHARSET);
return reader2String(reader);
}
catch (Exception e) {
log.error("发送 POST 请求出现异常!", e);
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (input != null) {
input.close();
}
if (reader != null) {
reader.close();
}
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
}
catch (IOException ex) {
return "";
}
}
return result;
}
/**
* 流转字符串
*
* @param reader
* @return
* @throws IOException
*/
private static String reader2String(Reader reader) throws IOException {
int len = 0;
char[] buf = new char[1024];
StringBuilder sb = new StringBuilder();
while ((len = reader.read(buf)) != -1) {
sb.append(new String(buf, 0, len));
}
return sb.toString();
}
/**
*
* <B>方法名称:</B><BR>
* <B>概要说明:对参数值进行转码</B><BR>
*
* @author:pangxj
* @cretetime:2018年1月11日 上午11:00:08
* @param par
* @return
* @throws UnsupportedEncodingException String
*/
private static String settingPar(String par) throws UnsupportedEncodingException {
if (StringUtils.isNotBlank(par)) {
String[] pars = par.split("&");
StringBuffer sb = new StringBuffer();
for (String pa : pars) {
String[] tempPar = pa.split("=");
if (sb.length() > 0) {
sb.append("&");
}
sb.append(tempPar[0].trim());
sb.append("=");
if (tempPar.length > 1) {
sb.append(URLEncoder.encode(tempPar[1].trim(), DEFAULT_CHARSET));
}
}
return sb.toString();
}
return "";
}
/**
*
* <B>方法名称:发起POST请求</B><BR>
* <B>概要说明:</B><BR>
*
* @param url
* 请求地址
* @param params
* 传递的参数
* @param charset
* 字符集
* @return
*/
public static String sendPost(String url, Map<String, String> params, String charset) {
String result = "";
HttpClient client = new HttpClient();
HttpMethod method = new PostMethod(url);
method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
method.setRequestHeader("Cookie", "special-cookie=value");
// method.setRequestHeader("", "");
// 设置Http Post数据
if (params != null) {
HttpMethodParams p = new HttpMethodParams();
for (Map.Entry<String, String> entry : params.entrySet()) {
p.setParameter(entry.getKey(), entry.getValue());
}
method.setParams(p);
}
// List<NameValuePair> nvps = new ArrayList<NameValuePair>();
// nvps.add(new BasicNameValuePair("signature", ""));
// method.setEntity(new UrlEncodedFormEntity(nvps));
try {
client.executeMethod(method);
if (method.getStatusCode() == HttpStatus.SC_OK) {
InputStream in = method.getResponseBodyAsStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, charset));
result = reader2String(reader);
in.close();
reader.close();
}
}
catch (IOException e) {
log.error("执行HTTP Post请求" + url + "时,发生异常!", e);
}
finally {
method.releaseConnection();
}
return result;
}
/**
*
* <B>方法名称:</B><BR>
* <B>概要说明:发JSON报文用此方法</B><BR>
*
* @param url
* @param data
* @return
*/
public static String sendPostUrl(String url, String data) {
String response = null;
try {
CloseableHttpClient httpclient = null;
CloseableHttpResponse httpresponse = null;
try {
httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url);
StringEntity stringentity = new StringEntity(data, ContentType.create("text/json", DEFAULT_CHARSET));
stringentity.setContentEncoding(DEFAULT_CHARSET);
httppost.setEntity(stringentity);
httpresponse = httpclient.execute(httppost);
response = EntityUtils.toString(httpresponse.getEntity(), DEFAULT_CHARSET);
}
finally {
if (httpclient != null) {
httpclient.close();
}
if (httpresponse != null) {
httpresponse.close();
}
}
}
catch (Exception e) {
log.error("发JSON报文错误", e);
}
return response;
}
/**
*
* <B>方法名称:</B><BR>
* <B>概要说明:发JSON报文用此方法</B><BR>
*
* @param url
* @param data
* @return
*/
public static String sendGetUrl(String url) {
String response = null;
try {
CloseableHttpClient httpclient = null;
CloseableHttpResponse httpresponse = null;
try {
httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet(url);
httpresponse = httpclient.execute(httpget);
response = EntityUtils.toString(httpresponse.getEntity(), DEFAULT_CHARSET);
}
finally {
if (httpclient != null) {
httpclient.close();
}
if (httpresponse != null) {
httpresponse.close();
}
}
}
catch (Exception e) {
log.error("发JSON报文错误", e);
}
return response;
}
// 发送请求
public static JSONObject httpsRequest(String requestUrl, String requestMethod) {
return httpsRequest(requestUrl, requestMethod, null);
}
public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
return JSONObject.parseObject(httpsRequestString(requestUrl, requestMethod, outputStr));
}
public static String httpsRequestString(String requestUrl, String requestMethod) {
return httpsRequestString(requestUrl, requestMethod, null);
}
public static String httpsRequestString(String requestUrl, String requestMethod, String outputStr) {
String result = "";
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
try {
TrustManager[] tm = { new JEEX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.setSSLSocketFactory(ssf);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod(requestMethod);
if (null != outputStr) {
OutputStream outputStream = conn.getOutputStream();
outputStream.write(outputStr.getBytes(DEFAULT_CHARSET));
outputStream.close();
}
inputStream = conn.getInputStream();
inputStreamReader = new InputStreamReader(inputStream, DEFAULT_CHARSET);
bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
conn.disconnect();
result = buffer.toString();
}
catch (Exception e) {
log.error(e);
}
finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (inputStreamReader != null) {
inputStreamReader.close();
}
if (inputStream != null) {
inputStream.close();
}
}
catch (IOException ex) {
//ex.printStackTrace();
}
}
return result;
}
public static byte[] httpsRequestByte(String requestUrl, String requestMethod) {
return httpsRequestByte(requestUrl, requestMethod, null);
}
public static byte[] httpsRequestByte(String requestUrl, String requestMethod, String outputStr) {
try {
TrustManager[] tm = { new JEEX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod(requestMethod);
if (null != outputStr) {
OutputStream outputStream = conn.getOutputStream();
outputStream.write(outputStr.getBytes(DEFAULT_CHARSET));
outputStream.close();
}
InputStream inputStream = conn.getInputStream();
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int n = 0;
if (inputStream != null) {
while (-1 != (n = inputStream.read(buffer))) {
output.write(buffer, 0, n);
}
inputStream.close();
}
byte[] res = new byte[output.toByteArray().length];
res = output.toByteArray();
output.close();
return res;
}
catch (Exception e) {
log.error(e);
}
return null;
}
public static String urlEnodeUTF8(String str) {
String result = str;
try {
result = URLEncoder.encode(str, DEFAULT_CHARSET);
}
catch (Exception e) {
log.error(e);
}
return result;
}
}
class JEEX509TrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
class TrustAnyHostnameVerifier implements HostnameVerifier {
@Override
public boolean verify(String hostname, SSLSession session) {
// 直接返回true
return true;
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sinobase.project.system.relation.mapper.DeptAndUserRelationMapper">
<!--批量插入-->
<insert id="insertRelation" parameterType="java.util.List">
insert IGNORE into sys_user_dprb(
id,
user_id,
dept_id,
status,
order_no
)
values
<foreach collection="list" item="item" index="index" separator=",">
(
#{item.id},
#{item.userId},
#{item.deptId},
#{item.status},
#{item.orderNo}
)
</foreach>
</insert>
<!--获取本地库部门下的用户id-->
<select id="selectRelationUidByDeptId" parameterType="java.lang.String" resultType="java.lang.String">
select
user_id
from
sys_user_dprb
where
dept_id=#{deptId}
</select>
<!--获取本地库部门下排序最大值-->
<select id="selectRelationOrderByDeptId" parameterType="java.lang.String" resultType="java.lang.Integer">
select
count(order_no)
from
sys_user_dprb
where
dept_id=#{deptId}
</select>
<!--删除部门下多余的关联关系-->
<delete id="deleteDurById" parameterType="DeptAndUserRelation">
delete from
sys_user_dprb
where
dept_id = #{deptId}
and
user_id = #{userId}
</delete>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sinobase.project.system.dept.mapper.DeptMapper">
<resultMap type="Dept" id="DeptResult">
<id property="deptId" column="dept_id" />
<result property="parentId" column="parent_id" />
<result property="ancestors" column="ancestors" />
<result property="deptName" column="dept_name" />
<result property="orderNum" column="order_num" />
<result property="leader" column="leader" />
<result property="phone" column="phone" />
<result property="email" column="email" />
<result property="status" column="status" />
<result property="delFlag" column="del_flag" />
<result property="parentName" column="parent_name" />
<result property="createBy" column="create_by" />
<result property="createTime" column="create_time" />
<result property="updateBy" column="update_by" />
<result property="updateTime" column="update_time" />
<result property="deptNumber" column="dept_number" />
<result property="fromUnit" column="from_unit" />
<result property="note" column="note" />
<result property="historyId" column="history_id" />
<result property="historyCode" column="history_code" />
<result property="unitType" column="unit_type" />
<result property="isZhc" column="is_zhc" />
<result property="companyId" column="company_id" />
<result property="deptcode" column="deptcode" />
<result property="companycode" column="companycode" />
<result property="supercode" column="supercode" />
<result property="isShow" column="isShow" />
<result property="deptProperty" column="dept_property" />
<result property="deptShort" column="dept_short" />
<result property="deptLevel" column="deptLevel" />
<result property="hasChildren" column="hasChildren" />
</resultMap>
<!--数据列表分页-->
<sql id="selectDeptVo">
select d.dept_id, d.parent_id,d.ancestors,d.history_id,d.dept_name,d.dept_number,
d.order_num, d.leader, d.phone, d.email, d.status, d.del_flag,d.create_by,d.create_time,
d.update_by,d.update_time,d.from_unit,d.note,d.history_code,d.unit_type,d.is_zhc,d.company_id,d.deptcode,
d.companycode,d.supercode,d.isShow,d.dept_property,d.dept_short,d.deptLevel
from sys_dept d
</sql>
<!-- 部门管理列表数据查询 -->
<select id="listForManage" parameterType="Dept" resultMap="DeptResult">
<include refid="selectDeptVo"/>
<where>
d.dept_id != '18043' and status = '1'
<if test="parentId != null and parentId != ''">
and d.parent_id = #{parentId}
</if>
<if test="deptName != null and deptName != ''">
and d.dept_name like concat('%', #{deptName}, '%')
</if>
<if test="historyId != null and historyId != ''">
and d.history_id = #{historyId}
</if>
</where>
order by d.order_num
</select>
<select id="selectRoleDeptTree" parameterType="String" resultType="String">
select concat(d.dept_id, d.dept_name) as dept_name
from sys_dept d
left join sys_role_dept rd on d.dept_id = rd.dept_id
where d.del_flag = '0' and rd.role_id = #{roleId}
order by d.parent_id, d.order_num
</select>
<!-- 根据父级id获取下级的部门信息 -->
<select id="selectDeptListByPID" parameterType="String" resultMap="DeptResult">
select * from sys_dept where parent_id = #{parentId} and status = '1' order by order_num
</select>
<!-- 批量更新排序字段 -->
<update id="sortSave" parameterType="String">
<foreach collection="array" item="deptid" index="index" open="" close="" separator=";">
update sys_dept
<set>
order_num = #{index}
</set>
where dept_id = #{deptid}
</foreach>
</update>
<select id="selectDeptList" parameterType="Dept" resultMap="DeptResult">
<include refid="selectDeptVo"/>
where d.del_flag = '0'
<if test="parentId!=null">
and parent_id = #{parentId}
</if>
<if test="deptName != null and deptName != ''">
and dept_name like concat('%', #{deptName}, '%')
</if>
<if test="status != null and status != ''">
and status = #{status}
</if>
order by d.order_num
</select>
<select id="checkDeptExistUser" resultType="int">
select count(1) from sys_user where dept_id = #{deptId} and del_flag = '0'
</select>
<select id="selectDeptCount" parameterType="Dept" resultType="int">
select count(1) from sys_dept
where del_flag = '0'
<if test="deptId != null and deptId != '0'.toString()"> and dept_id = #{deptId} </if>
<if test="parentId != null and parentId != '0'.toString()"> and parent_id = #{parentId} </if>
</select>
<select id="checkDeptNameUnique" resultMap="DeptResult">
<include refid="selectDeptVo"/>
where dept_name=#{deptName} and parent_id = #{parentId}
</select>
<select id="selectDeptById" resultMap="DeptResult">
select dept_id, parent_id,dept_number, ancestors,history_id,history_code,unit_type,is_zhc,
dept_name, order_num, leader, phone, email, status, del_flag, from_unit,note,create_by, create_time,update_by,update_time,company_id,deptcode,
companycode,supercode,isShow,dept_property,dept_short,deptLevel,
(select dept_name from sys_dept where dept_id = (select d.parent_id from sys_dept d where d.dept_id=#{deptId})) as parent_name
from sys_dept
where dept_id = #{deptId}
</select>
<insert id="insertDept" parameterType="Dept">
insert into sys_dept(
<if test="deptId != null and deptId != '0'.toString()">dept_id,</if>
<if test="parentId != null and parentId != '0'.toString()">parent_id,</if>
<if test="deptName != null and deptName != ''">dept_name,</if>
<if test="ancestors != null and ancestors != ''">ancestors,</if>
<if test="orderNum != null and orderNum != ''">order_num,</if>
<if test="leader != null and leader != ''">leader,</if>
<if test="phone != null and phone != ''">phone,</if>
<if test="email != null and email != ''">email,</if>
<if test="status != null">status,</if>
<if test="createBy != null and createBy != ''">create_by,</if>
<if test="companyId != null and companyId != ''">company_id,</if>
<if test="deptcode != null and deptcode != ''">deptcode,</if>
<if test="companycode != null and companycode != ''">companycode,</if>
<if test="supercode != null and supercode != ''">supercode,</if>
<if test="isShow != null and isShow != ''">isShow,</if>
<if test="deptProperty != null and deptProperty != ''">dept_property,</if>
<if test="deptShort != null and deptShort != ''">dept_short,</if>
<if test="deptLevel != null and deptLevel != ''">deptLevel,</if>
create_time
)values(
<if test="deptId != null and deptId != '0'.toString()">#{deptId},</if>
<if test="parentId != null and parentId != '0'.toString()">#{parentId},</if>
<if test="deptName != null and deptName != ''">#{deptName},</if>
<if test="ancestors != null and ancestors != ''">#{ancestors},</if>
<if test="orderNum != null and orderNum != ''">#{orderNum},</if>
<if test="leader != null and leader != ''">#{leader},</if>
<if test="phone != null and phone != ''">#{phone},</if>
<if test="email != null and email != ''">#{email},</if>
<if test="status != null">#{status},</if>
<if test="createBy != null and createBy != ''">#{createBy},</if>
<if test="companyId != null and companyId != ''">#{companyId},</if>
<if test="deptcode != null and deptcode != ''">#{deptcode},</if>
<if test="companycode != null and companycode != ''">#{companycode},</if>
<if test="supercode != null and supercode != ''">#{supercode},</if>
<if test="isShow != null and isShow != ''">#{isShow},</if>
<if test="deptProperty != null and deptProperty != ''">#{deptProperty},</if>
<if test="deptShort != null and deptShort != ''">#{deptShort},</if>
<if test="deptLevel != null and deptLevel != ''">#{deptLevel},</if>
sysdate()
)
</insert>
<update id="updateDept" parameterType="Dept">
update sys_dept
<set>
<if test="parentId != null and parentId != '0'.toString()">parent_id = #{parentId},</if>
<if test="deptName != null and deptName != ''">dept_name = #{deptName},</if>
<if test="ancestors != null and ancestors != ''">ancestors = #{ancestors},</if>
<if test="orderNum != null and orderNum != ''">order_num = #{orderNum},</if>
<if test="leader != null and leader != ''">leader = #{leader},</if>
<if test="phone != null and phone != ''">phone = #{phone},</if>
<if test="email != null and email != ''">email = #{email},</if>
<if test="status != null and status != ''">status = #{status},</if>
<if test="companyId != null and companyId != ''">company_id = #{companyId},</if>
<if test="updateBy != null and updateBy != ''">update_by = #{updateBy},</if>
<if test="deptcode != null and deptcode != ''">deptcode=#{deptcode},</if>
<if test="companycode != null and companycode != ''">companycode=#{companycode},</if>
<if test="supercode != null and supercode != ''">supercode=#{supercode},</if>
<if test="isShow != null and isShow != ''">isShow=#{isShow},</if>
<if test="deptProperty != null and deptProperty != ''">deptProperty=#{deptProperty},</if>
<if test="deptShort != null and deptShort != ''">dept_short=#{deptShort},</if>
<if test="deptLevel != null and deptLevel != ''">deptLevel = #{deptLevel},</if>
update_time = sysdate()
</set>
where dept_id = #{deptId}
</update>
<update id="updateDeptChildren" parameterType="java.util.List">
update sys_dept set ancestors =
<foreach collection="depts" item="item" index="index"
separator=" " open="case dept_id" close="end">
when #{item.deptId} then #{item.ancestors}
</foreach>
where dept_id in
<foreach collection="depts" item="item" index="index"
separator="," open="(" close=")">
#{item.deptId}
</foreach>
</update>
<delete id="deleteDeptById">
update sys_dept set del_flag = '2' where dept_id = #{deptId}
</delete>
<update id="updateDeptStatus" parameterType="Dept">
update sys_dept
<set>
<if test="status != null and status != ''">status = #{status},</if>
<if test="updateBy != null and updateBy != ''">update_by = #{updateBy},</if>
update_time = sysdate()
</set>
where dept_id in (${ancestors})
</update>
<select id="listDeptByDeptId" parameterType="java.lang.String" resultMap="DeptResult">
select * from sys_dept
<where>
dept_id in
<foreach collection="array" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</where>
</select>
<!--根据部门对象集合添加部门-->
<insert id="insertDeptList" parameterType="Dept">
insert IGNORE into sys_dept(
dept_id,
parent_id,
dept_name,
ancestors,
order_num,
phone,
status,
from_unit,
note,
dept_number,
history_id,
history_code,
unit_type,
is_zhc,
create_by,
company_id,
deptcode,
companycode,
supercode,
isShow,
dept_property,
dept_short,
deptLevel,
create_time
)
values
<foreach collection="list" item="dept" index="index" separator=",">
(
#{dept.deptId},
#{dept.parentId},
#{dept.deptName},
#{dept.ancestors},
#{dept.orderNum},
#{dept.phone},
#{dept.status},
#{dept.fromUnit},
#{dept.note},
#{dept.deptNumber},
#{dept.historyId},
#{dept.historyCode},
#{dept.unitType},
#{dept.isZhc},
#{dept.createBy},
#{dept.companyId},
#{dept.deptcode},
#{dept.companycode},
#{dept.supercode},
#{dept.isShow},
#{dept.deptProperty},
#{dept.deptShort},
#{dept.deptLevel},
sysdate()
)
</foreach>
</insert>
<!--获取本地数据库所有部门的id-->
<select id="selectAllDeptId" resultType="java.lang.String">
select
dept_id
from
sys_dept
</select>
<select id="getDeptsByUserId" resultMap="DeptResult" parameterType="java.lang.String">
select d.dept_id,d.dept_name,d.parent_id,d.unit_type from sys_dept d,sys_user_dprb r
where d.dept_id = r.dept_id and r.user_id=#{userId}
</select>
<!--获取所有部门信息-->
<select id="selectAllDept" parameterType="Dept" resultMap="DeptResult">
select
d.dept_id, d.parent_id,dept_number, d.ancestors,d.from_unit,d.note, d.history_id,d.history_code,d.unit_type,d.is_zhc,
d.dept_name, d.order_num, d.leader, d.phone, d.email, d.status, d.del_flag,d.update_by,d.update_time, d.create_by, d.create_time,d.company_id,d.deptcode,
d.companycode,d.supercode,d.isShow,d.dept_property,d.dept_short,d.deptLevel
from
sys_dept d
where
d.history_id like '001' '%' and d.status = '1'
order by d.parent_id ,d.order_num is null ,d.order_num
</select>
<!--根据部门id查询所有子部门信息 -->
<select id="selectDeptListByDeptId" parameterType="java.lang.String" resultMap="DeptResult">
select
d.dept_id, d.parent_id,dept_number, d.ancestors,d.from_unit,d.note, d.history_id,d.history_code,d.unit_type,d.is_zhc,
d.dept_name, d.order_num, d.leader, d.phone, d.email, d.status, d.del_flag,d.update_by,d.update_time,
d.create_by, d.create_time,d.company_id,d.deptcode,d.companycode,d.supercode,d.isShow,d.dept_property,d.dept_short,d.deptLevel
from
sys_dept d
where
d.parent_id = #{deptId} and d.status = '1'
order by d.order_num is null ,d.order_num asc
</select>
<select id="selectMaxId" resultType="Integer">
select max(CAST(dept_id AS SIGNED)) from sys_dept
</select>
<!--根据部门id获取所有子孙部门-->
<select id="selectDeptListsByDeptId" parameterType="java.lang.String" resultMap="DeptResult">
select d.dept_id, d.parent_id,dept_number, d.ancestors,d.from_unit,d.note, d.history_id,d.history_code,d.unit_type,d.is_zhc,
d.dept_name, d.order_num, d.leader, d.phone, d.email, d.status, d.del_flag,d.update_by,d.update_time,
d.create_by, d.create_time,d.company_id,d.deptcode,d.companycode,d.supercode,d.isShow,d.dept_property,d.dept_short,d.deptLevel,
if((select count(1) from sys_user u left join sys_user_dprb b on u.user_id = b.user_id where b.dept_id=d.dept_id and d.status=1 and u.status=1)=0 and (select count(1) from sys_dept s where s.parent_id=d.dept_id and s.status=1)=0,'false','true') hasChildren
from sys_dept d
<where>
d.status = '1' and d.history_id like '001' '%'
<if test="deptId != null and deptId != '' and deptId != '0'.toString()">
<!--and d.ancestors LIKE CONCAT((SELECT t.ancestors FROM sys_dept t where t.dept_id = #{deptId}),'%') -->
and d.parent_id = #{deptId}
</if>
</where>
order by parent_id,order_num asc
</select>
<!--根据部门id,以及相关权限获取下一级部门-->
<select id="selectDeptListByDeptIdAndAuthority" parameterType="Map" resultMap="DeptResult">
select d.dept_id, d.parent_id,dept_number, d.ancestors,d.from_unit,d.note, d.history_id,d.history_code,d.unit_type,d.is_zhc,
d.dept_name, d.order_num, d.leader, d.phone, d.email, d.status, d.del_flag,d.update_by,d.update_time,
d.create_by, d.create_time,d.company_id,d.deptcode,d.companycode,d.supercode,d.isShow,d.dept_property,d.dept_short,d.deptLevel,
if((select count(1) from sys_dept s where s.parent_id=d.dept_id and s.status=1)=0,'false','true') hasChildren
from sys_dept d
<where>
d.status = '1' and d.history_id like '001' '%'
<if test="auth.deptId != null and auth.deptId != '' and auth.deptId != '0'.toString()">
and d.parent_id = #{auth.deptId}
</if>
<if test="auth.isshow=='yes'">
and d.dept_id in (SELECT dept_permission from sys_dept_permission where property = #{auth.deptId} and isshow=#{auth.isshow})
</if>
<if test="auth.isshow=='no'">
and d.dept_id not in (SELECT dept_permission from sys_dept_permission where property = #{auth.deptId} and isshow=#{auth.isshow})
</if>
</where>
order by parent_id,order_num asc
</select>
<!-- 通过sql插入部门信息-->
<insert id="insertDeptBySql" parameterType="java.lang.String" >
${sql}
</insert>
<select id="selectBySql" parameterType="java.lang.String" resultType="java.util.Map">
${sql}
</select>
<select id="selectAllBySql" parameterType="java.lang.String" resultType="java.util.Map">
${sql}
</select>
<!--根据部门id获取顶级部门信息-->
<select id="getCompanyId" parameterType="java.lang.String" resultMap="DeptResult">
select t.* from (
select @dept_id idlist,
(select @dept_id:=group_concat(parent_id separator ',') from sys_dept where find_in_set(dept_id,@dept_id)) sub
from sys_dept,(select @dept_id:=#{deptId}) vars
where @dept_id is not null) tl,sys_dept t
where find_in_set(t.dept_id,tl.idlist) ORDER BY t.parent_id asc LIMIT 0,1
</select>
<!--根据部门id,以及相关权限获取所有子孙部门-->
<select id="getAllChildrenDept" parameterType="Map" resultType="java.util.HashMap">
select dept_id, (select dept_short from sys_dept where dept_id=d.parent_id) as company_name, d.dept_short, d.dept_name, parent_id, d.history_id from sys_dept d
<where>
d.status = '1' and d.history_id like '001' '%'
<!--<if test="auth.deptId != null and auth.deptId != '' and auth.deptId != '0'.toString()">-->
<!--and d.parent_id = #{auth.deptId}-->
<!--</if>-->
<if test="auth.ancestors != null">
and d.ancestors like CONCAT('%', CONCAT(#{auth.ancestors}), '%')
</if>
<if test="auth.deptname != null">
and d.dept_short like CONCAT('%', CONCAT(#{auth.deptname}), '%')
</if>
<if test="auth.isshow=='yes'">
and d.dept_id in (SELECT dept_permission from sys_dept_permission where property = #{auth.deptId} and isshow=#{auth.isshow})
</if>
<if test="auth.isshow=='no'">
and d.dept_id not in (SELECT dept_permission from sys_dept_permission where property = #{auth.deptId} and isshow=#{auth.isshow})
</if>
</where>
order by parent_id,order_num asc
</select>
<select id="getDeptLikeAncestors" parameterType="java.lang.String" resultMap="DeptResult">
select dept_name from sys_dept where ancestors like CONCAT(CONCAT(#{ancestors}), '%')
</select>
<select id="listDeptForDeptName" parameterType="java.lang.String" resultMap="DeptResult">
select * from sys_dept where dept_name = #{deptName} and del_flag = '0' and status = '1'
</select>
<select id="getDeptByAncestors" parameterType="java.lang.String" resultMap="DeptResult">
select * from sys_dept where ancestors = #{ancestors} and from_unit= '0'
</select>
<select id="getDeptByFromUnit" parameterType="java.lang.String" resultMap="DeptResult">
select * from sys_dept where from_unit=#{fromUnit} and parent_id = (select dept_id from sys_dept where parent_id='0' and from_unit='0' and del_flag='0') and del_flag='0' and used_for_statistics='1' order by order_num asc
</select>
<select id="getOldDeptInfo" resultType="java.util.HashMap" parameterType="String">
select * from flow_dept where deptid=#{historyId}
</select>
<select id="getDeptNamesByDeptIds" parameterType="java.lang.String" resultType="java.lang.String">
<foreach collection="array" item="deptid" index="index" open="" close="" separator=" union all ">
select (case when count(dept_id)>0 then dept_name else '' end) dept_name from sys_dept where dept_id=#{deptid, jdbcType=VARCHAR}
</foreach>
</select>
<resultMap type="Dept" id="DeptResult_childs">
<id property="deptId" column="dept_id" />
<result property="parentId" column="parent_id" />
<result property="ancestors" column="ancestors" />
<result property="deptName" column="dept_name" />
<result property="orderNum" column="order_num" />
<result property="leader" column="leader" />
<result property="phone" column="phone" />
<result property="email" column="email" />
<result property="status" column="status" />
<result property="delFlag" column="del_flag" />
<result property="parentName" column="parent_name" />
<result property="createBy" column="create_by" />
<result property="createTime" column="create_time" />
<result property="updateBy" column="update_by" />
<result property="updateTime" column="update_time" />
<result property="deptNumber" column="dept_number" />
<result property="fromUnit" column="from_unit" />
<result property="note" column="note" />
<result property="historyId" column="history_id" />
<result property="historyCode" column="history_code" />
<result property="unitType" column="unit_type" />
<result property="isZhc" column="is_zhc" />
<result property="companyId" column="company_id" />
<result property="deptcode" column="deptcode" />
<result property="companycode" column="companycode" />
<result property="supercode" column="supercode" />
<result property="isShow" column="isShow" />
<result property="deptProperty" column="dept_property" />
<result property="deptShort" column="dept_short" />
<result property="deptLevel" column="deptLevel" />
<result property="hasChildren" column="hasChildren" />
<result property="childDeptIds" column="child_dept_ids" /><!-- -->
</resultMap>
<select id="getDeptByFromUnit_childDpetIds" parameterType="java.lang.String" resultMap="DeptResult_childs">
select d.*,(select GROUP_CONCAT(distinct dept_id) from sys_dept where parent_id=d.dept_id) as child_dept_ids
from sys_dept d where d.from_unit=#{fromUnit} and d.parent_id = (select dept_id from sys_dept where parent_id='0' and from_unit='0' and del_flag='0') and d.del_flag='0' and d.used_for_statistics='1' order by d.order_num asc
</select>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sinobase.project.system.portal.mapper.DocSendMapper">
<sql id="selectDocSendVO">
select * from doc_send
</sql>
<select id="listDocSend"
parameterType="com.sinobase.project.system.portal.domain.DocSend"
resultType="com.sinobase.project.system.portal.domain.DocSend">
<include refid="selectDocSendVO"/>
<where>
<if test="relationId != null and relationId != ''">AND relation_id = #{relationId}</if>
<if test="relationTable != null and relationTable != ''">AND relation_table = #{relationTable}</if>
<if test="relationKey != null and relationKey != ''">AND relation_key = #{relationKey}</if>
<if test="viewUrl != null and viewUrl != ''">AND view_url = #{viewUrl}</if>
<if test="keyWord != null and keyWord != ''">AND keyword = #{keyWord}</if>
<if test="inUserId != null and inUserId != ''">AND in_user_id in (#{inUserId})</if>
<if test="creUserId != null and creUserId != ''">AND cre_user_id = #{creUserId}</if>
<if test="typeId != null and typeId != ''">AND type_id = #{typeId}</if>
<if test="seeFlag != null and seeFlag != ''">AND see_flag = #{seeFlag}</if>
<if test="sendTitle != null and sendTitle != ''">AND send_title = #{sendTitle}</if>
<if test="flag != null and flag != ''">AND flag = #{flag}</if>
<if test="userNotion != null and userNotion != ''">AND user_notion = #{userNotion}</if>
<if test="notionDate != null and notionDate != ''">AND notion_date = #{notionDate}</if>
<if test="filingCabinetId != null and filingCabinetId != ''">AND filing_cabinet_id = #{filingCabinetId}</if>
<if test="filingCabinetName != null and filingCabinetName != ''">AND filing_cabinet_name = #{filingCabinetName}</if>
<if test="inDeptId != null and inDeptId != ''">AND in_dept_id in (#{inDeptId})</if>
<if test="inDeptName != null and inDeptName != ''">AND in_dept_name in (#{inDeptName})</if>
<if test="delFlag != null and delFlag != ''">AND del_flag = #{delFlag}</if>
<if test="isGongGao != null and isGongGao != ''">AND is_gonggao = #{isGongGao}</if>
</where>
</select>
<delete id="deleteMessageByOldOASendMessage">
delete from sys_message where grant_user_id ='#{grantUserId}'
and data_source= '旧OA'
and is_old_oa_data ='yes'
and message_type='docSendWait'
</delete>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sinobase.project.system.menu.mapper.MenuMapper">
<resultMap type="Menu" id="MenuResult">
<id property="menuId" column="menu_id" />
<result property="menuName" column="menu_name" />
<result property="parentName" column="parent_name" />
<result property="parentId" column="parent_id" />
<result property="orderNum" column="order_num" />
<result property="url" column="url" />
<result property="menuType" column="menu_type" />
<result property="visible" column="visible" />
<result property="perms" column="perms" />
<result property="icon" column="icon" />
<result property="createBy" column="create_by" />
<result property="createTime" column="create_time" />
<result property="updateTime" column="update_time" />
<result property="updateBy" column="update_by" />
<result property="remark" column="remark" />
</resultMap>
<sql id="selectMenuVo">
select menu_id, menu_name, parent_id, order_num, url, menu_type, visible, perms, icon, create_by, create_time
from sys_menu
</sql>
<select id="selectMenusByUserId" resultMap="MenuResult">
select distinct m.menu_id, m.parent_id, m.menu_name, m.url, m.perms ,CONCAT('parse_',m.menu_type) as menu_type, m.order_num, m.create_time
from sys_menu m
left join sys_role_menu rm on m.menu_id = rm.menu_id
left join sys_user_role ur on rm.role_id = ur.role_id
LEFT JOIN sys_role ro on ur.role_id = ro.role_id
where ur.user_id = #{userId} and m.visible = '1' AND ro.status = 1 and m.menu_type = #{menuType}
<!--and m.menu_type in ('M', 'C')-->
<if test="parentId != null and parentId != '0'.toString()">
and m.parent_id = #{parentId}
</if>
order by m.order_num
</select>
<select id="selectMenuNormalAll" parameterType="Map" resultMap="MenuResult">
select distinct m.menu_id, m.parent_id, m.menu_name, m.url, m.perms ,CONCAT('parse_',m.menu_type) as menu_type, m.icon, m.order_num, m.create_time
from sys_menu m
where m.menu_type = #{menuType} and m.visible = '1'
<if test="parentId != null and parentId != '0'.toString()">
and m.parent_id = #{parentId}
</if>
order by m.order_num
</select>
<select id="selectMenuAll" resultMap="MenuResult">
<include refid="selectMenuVo"/>
order by order_num
</select>
<select id="selectPermsByUserId" resultType="String">
select distinct m.perms
from sys_menu m
left join sys_role_menu rm on m.menu_id = rm.menu_id
left join sys_user_role ur on rm.role_id = ur.role_id
where ur.user_id = #{userId}
</select>
<select id="selectMenuTree" parameterType="String" resultType="String">
select concat(m.menu_id, m.perms) as perms
from sys_menu m
left join sys_role_menu rm on m.menu_id = rm.menu_id
where rm.role_id = #{roleId}
order by m.parent_id, m.order_num
</select>
<select id="selectMenuList" parameterType="Menu" resultMap="MenuResult">
<include refid="selectMenuVo"/>
<where>
<if test="menuName != null and menuName != ''">
AND menu_name like concat('%', #{menuName}, '%')
</if>
<if test="visible != null and visible != ''">
AND visible = #{visible}
</if>
</where>
order by order_num
</select>
<delete id="deleteMenuById" parameterType="String">
delete from sys_menu where menu_id = #{menuId} or parent_id = #{menuId}
</delete>
<select id="selectMenuById" resultMap="MenuResult">
SELECT t.menu_id, t.parent_id, t.menu_name, t.order_num, t.url, t.menu_type, t.visible, t.perms, t.icon, t.remark,
(SELECT menu_name FROM sys_menu WHERE menu_id = t.parent_id) parent_name
FROM sys_menu t
where t.menu_id = #{menuId}
</select>
<select id="selectCountMenuByParentId" resultType="Integer">
select count(1) from sys_menu where parent_id=#{menuId}
</select>
<select id="checkMenuNameUnique" parameterType="Menu" resultMap="MenuResult">
<include refid="selectMenuVo"/>
where menu_name=#{menuName} and parent_id = #{parentId}
</select>
<update id="updateMenu" parameterType="Menu">
update sys_menu
<set>
<if test="menuName != null and menuName != ''">menu_name = #{menuName},</if>
<if test="parentId != null and parentId != '0'.toString()">parent_id = #{parentId},</if>
<if test="orderNum != null and orderNum != ''">order_num = #{orderNum},</if>
<if test="url != null and url != ''">url = #{url},</if>
<if test="menuType != null and menuType != ''">menu_type = #{menuType},</if>
<if test="visible != null">visible = #{visible},</if>
<if test="perms !=null and perms != ''">perms = #{perms},</if>
<if test="icon !=null and icon != ''">icon = #{icon},</if>
<if test="remark != null and remark != ''">remark = #{remark},</if>
<if test="updateBy != null and updateBy != ''">update_by = #{updateBy},</if>
update_time = sysdate()
</set>
where menu_id = #{menuId}
</update>
<insert id="insertMenu" parameterType="Menu">
insert into sys_menu(
<if test="menuId != null and menuId != '0'.toString()">menu_id,</if>
<if test="parentId != null and parentId != '0'.toString()">parent_id,</if>
<if test="menuName != null and menuName != ''">menu_name,</if>
<if test="orderNum != null and orderNum != ''">order_num,</if>
<if test="url != null and url != ''">url,</if>
<if test="menuType != null and menuType != ''">menu_type,</if>
<if test="visible != null">visible,</if>
<if test="perms !=null and perms != ''">perms,</if>
<if test="icon != null and icon != ''">icon,</if>
<if test="remark != null and remark != ''">remark,</if>
<if test="createBy != null and createBy != ''">create_by,</if>
create_time
)values(
<if test="menuId != null and menuId != '0'.toString()">#{menuId},</if>
<if test="parentId != null and parentId != '0'.toString()">#{parentId},</if>
<if test="menuName != null and menuName != ''">#{menuName},</if>
<if test="orderNum != null and orderNum != ''">#{orderNum},</if>
<if test="url != null and url != ''">#{url},</if>
<if test="menuType != null and menuType != ''">#{menuType},</if>
<if test="visible != null">#{visible},</if>
<if test="perms !=null and perms != ''">#{perms},</if>
<if test="icon != null and icon != ''">#{icon},</if>
<if test="remark != null and remark != ''">#{remark},</if>
<if test="createBy != null and createBy != ''">#{createBy},</if>
sysdate()
)
</insert>
<select id="selectMaxId" resultType="Integer">
select max(CAST(menu_id AS SIGNED)) from sys_menu
</select>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sinobase.project.system.portal.mapper.MessageMapper">
<sql id="selectMessageVO">
select * from sys_message
</sql>
<insert id="saveMessages" parameterType="java.util.List">
insert into sys_message
(
message_type,
id,
title,
content,
url,
receive_time,
expiration_time,
level,
data_source,
from_user_id,
from_user_name,
grant_user_id,
grant_dept_id,
read_user_id,
status,
grant_user_name,
grant_dept_name,
from_dept_id,
from_dept_name,
is_old_oa_data,
wait_handle_table_name,
wait_handle_primary_key_name,
wait_handle_primary_key_value,
subordinate_id,
category_types,
workflow_info_id
)
values
<foreach collection="list" item="item" index="index" separator=",">
(
#{item.messageType},
#{item.id},
#{item.title},
#{item.content},
#{item.url},
#{item.receiveTime},
#{item.expirationTime},
#{item.level},
#{item.dataSource},
#{item.fromUserId},
#{item.fromUserName},
#{item.grantUserId},
#{item.grantDeptId},
#{item.readUserId},
#{item.status},
#{item.grantUserName},
#{item.grantDeptName},
#{item.fromDeptId},
#{item.fromDeptName},
#{item.isOldOAData},
#{item.waitHandleTableName},
#{item.waitHandlePrimaryKeyName},
#{item.waitHandlePrimaryKeyValue},
#{item.subordinateId},
#{item.categoryTypes},
#{item.workflowInfoId}
)
</foreach>
</insert>
<select id="listMessage" parameterType="com.sinobase.project.system.portal.domain.Message"
resultType="com.sinobase.project.system.portal.domain.Message">
<include refid="selectMessageVO"/>
<where>
<if test="id != null and id != ''">AND id = #{id}</if>
<if test="messageType != null and messageType != ''">AND message_type = #{messageType}</if>
<if test="title != null and title != ''">AND title like concat('%', #{title}, '%')</if>
<if test="content != null and content != ''">AND content like concat('%', #{content}, '%')</if>
<if test="url != null and url != ''">AND url like concat('%', #{url}, '%')</if>
<if test="level != null and level != ''">AND level = #{level}</if>
<if test="dataSource != null and dataSource != ''">AND data_source = #{dataSource}</if>
<if test="expirationTime != null"> AND expiration_time = #{expirationTime}</if>
<if test="(grantUserId != null and grantUserId != '') and (fromUserId != null and fromUserId != '')">
AND (from_user_id = #{fromUserId} OR grant_user_id in ( #{grantUserId}) )
</if>
<if test="(fromUserId != null and fromUserId != '') and (grantUserId == null or grantUserId == '')">
AND from_user_id = #{fromUserId}
</if>
<if test="(grantUserId != null and grantUserId != '') and (fromUserId == null or fromUserId == '')">
AND grant_user_id in ( #{grantUserId})
</if>
<if test="fromUserName != null and fromUserName != ''">AND from_user_name like concat('%',
#{fromUserName},'%')
</if>
<if test="grantUserName != null and grantUserName != ''">AND grant_user_name like
concat('%',#{grantUserName}, '%')
</if>
<if test="grantDeptId != null and grantDeptId != ''">AND grant_dept_id = #{grantDeptId}</if>
<if test="grantDeptName != null and grantDeptName != ''">AND grant_dept_name like concat('%',
#{grantDeptName}, '%')
</if>
<if test="readUserId != null and readUserId != ''">AND read_user_id like concat('%', #{readUserId}, '%')
</if>
<if test="status != null and status != ''">AND status = #{status}</if>
<if test="isOldOAData != null and isOldOAData != ''">AND is_old_oa_data = #{isOldOAData}</if>
<if test="waitHandleTableName != null and waitHandleTableName != ''">AND wait_handle_table_name =
#{waitHandleTableName}
</if>
<if test="waitHandlePrimaryKeyName != null and waitHandlePrimaryKeyName != ''">AND
wait_handle_primary_key_name = #{waitHandlePrimaryKeyName}
</if>
<if test="waitHandlePrimaryKeyValue != null and waitHandlePrimaryKeyValue != ''">AND
wait_handle_primary_key_value = #{waitHandlePrimaryKeyValue}
</if>
<if test="categoryTypes != null and categoryTypes != ''">AND category_types = #{categoryTypes}</if>
<if test="subordinateId != null and subordinateId != ''">AND subordinate_id = #{subordinateId}</if>
<if test="receiveTime != null ">AND receive_time > #{receiveTime}</if>
</where>
ORDER BY receive_time desc
</select>
<insert id="saveMessage" parameterType="com.sinobase.project.system.portal.domain.Message">
insert into sys_message (id,title,level,data_source,from_user_id,
<if test="messageType != null and messageType != ''">message_type,</if>
<if test="content != null and content != ''">content,</if>
<if test="url != null and url != ''">url,</if>
<if test="expirationTime != null">expiration_time,</if>
<if test="fromUserName != null and fromUserName != ''">from_user_name,</if>
<if test="grantUserId !=null and grantUserId != ''">grant_user_id,</if>
<if test="grantUserName !=null and grantUserName != ''">grant_user_name,</if>
<if test="grantDeptId != null and grantDeptId != ''">grant_dept_id,</if>
<if test="grantDeptName != null and grantDeptName != ''">grant_dept_name,</if>
<if test="status != null and status != ''">status,</if>
<if test="workflowInfoId != null and workflowInfoId != ''">workflowInfoId,</if>
receive_time
)VALUES(
#{id},#{title},#{level},#{dataSource},#{fromUserId},
<if test="messageType != null and messageType != ''">#{messageType},</if>
<if test="content != null and content != ''">#{content},</if>
<if test="url != null and url != ''">#{url},</if>
<if test="expirationTime != null">#{expirationTime},</if>
<if test="fromUserName != null and fromUserName != ''">#{fromUserName},</if>
<if test="grantUserId !=null and grantUserId != ''">#{grantUserId},</if>
<if test="grantUserName !=null and grantUserName != ''">#{grantUserName},</if>
<if test="grantDeptId != null and grantDeptId != ''">#{grantDeptId},</if>
<if test="grantDeptName != null and grantDeptName != ''">#{grantDeptName},</if>
<if test="status != null and status != ''">#{status},</if>
<if test="workflowInfoId != null and workflowInfoId != ''">#{workflowInfoId},</if>
#{receiveTime}
)
</insert>
<update id="updateMessage">
update sys_message
<set>
<if test="title != null and title != ''">title = #{title},</if>
<if test="messageType != null and messageType != ''">message_type = #{messageType},</if>
<if test="level != null and level != ''">level = #{level},</if>
<if test="receiveTime != null">receive_time = #{receiveTime},</if>
<if test="expirationTime != null">expiration_time = #{expirationTime},</if>
<if test="grantUserId !=null and grantUserId != ''">grant_user_id =#{grantUserId},</if>
<if test="grantUserName !=null and grantUserName != ''">grant_user_name = #{grantUserName},</if>
<if test="grantDeptId != null and grantDeptId != ''">grant_dept_id =#{grantDeptId},</if>
<if test="grantDeptName != null and grantDeptName != ''">grant_dept_name = #{grantDeptName},</if>
<if test="url != null and url != ''">url = #{url},</if>
<if test="content != null and content != ''">content = #{content},</if>
<if test="status != null and status != ''">status = #{status}</if>
</set>
<where>
id = #{id}
</where>
</update>
<delete id="delMessage" parameterType="java.lang.String">
delete from sys_message where id in
<foreach collection="array" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</delete>
<update id="updateMessageByWorkflowInfoId">
update sys_message
set message_type = 'workFlowRead'
where workflow_info_id = #{workflowInfoId}
</update>
<update id="deleteMessageByWorkflowInfoId">
delete from sys_message
where workflow_info_id = #{workflowInfoId}
</update>
<delete id="deleteMessageByOldOAWriteMessage">
delete from sys_message where grant_user_id ='#{grantUserId}'
and data_source= '旧OA'
and is_old_oa_data ='yes'
and message_type='workFlowWrite'
</delete>
<update id="updateMessageByWorkitemId">
update sys_message
set message_type = 'workFlowRead'
where wait_handle_primary_key_value = #{workitemId}
</update>
<delete id="delMessageForSubordinateIds" parameterType="java.lang.String">
delete from sys_message where subordinate_id in
<foreach collection="array" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</delete>
<delete id="deleteNotWorkFlowMessage" parameterType="java.lang.String">
delete from sys_message where subordinate_id = #{subordinateId} and status = 'normal' and workflow_info_id = 'no-work-info-id';
</delete>
<delete id="deleteNotWorkFlowMessageByMany">
delete from sys_message
where subordinate_id = #{id}
and workflow_info_id = 'no-work-info-id'
and grant_user_id = #{userId}
and url like concat('%',#{url}, '%');
</delete>
<select id="listSuperviseBacklog" resultType="com.sinobase.project.system.portal.domain.Message">
select * from sys_message
<where>
<if test="superviseFiletypeIds != null">
<foreach index="index" collection="superviseFiletypeIds" item="superviseFiletypeId" open="(" close=")">
url LIKE CONCAT('%',#{superviseFiletypeId},'%')
<if test="superviseFiletypeIds.size()-1 != index">
or
</if>
</foreach>
</if>
<if test="message.title !='' and message.title!=null">
AND title LIKE CONCAT('%',#{message.title},'%')
</if>
<if test="sysUserId != null and sysUserId != ''">
AND grant_user_id = #{sysUserId}
</if>
order by receive_time desc
</where>
</select>
<delete id="deleteSysMessageByRecordId">
delete from sys_message where subordinate_id = #{recordid}
</delete>
<delete id="deleteFlowReadNewByRecordId">
delete from flow_read_new where recordid = #{recordid}
</delete>
<delete id="deleteNewFlowWriteByRecordId">
delete from epcloud.flow_write where recordid = #{recordid}
</delete>
<delete id="deleteFlowWriteByRecordId">
delete from flow_write where recordid = #{recordid}
</delete>
<delete id="deleteFlowWflogByRecordId">
delete from flow_wflog where recordid = #{recordid}
</delete>
<delete id="deleteFlowReadByRecordId">
delete from flow_read where recordid = #{recordid}
</delete>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sinobase.project.system.post.mapper.PostMapper">
<resultMap type="Post" id="PostResult">
<id property="postId" column="post_id" />
<result property="postCode" column="post_code" />
<result property="postName" column="post_name" />
<result property="postSort" column="post_sort" />
<result property="status" column="status" />
<result property="createBy" column="create_by" />
<result property="createTime" column="create_time" />
<result property="updateBy" column="update_by" />
<result property="updateTime" column="update_time" />
<result property="remark" column="remark" />
</resultMap>
<sql id="selectPostVo">
select post_id, post_code, post_name, post_sort, status, create_by, create_time, remark
from sys_post
</sql>
<select id="selectPostList" parameterType="Post" resultMap="PostResult">
<include refid="selectPostVo"/>
<where>
<if test="postCode != null and postCode != ''">
AND post_code like concat('%', #{postCode}, '%')
</if>
<if test="status != null and status != ''">
AND status = #{status}
</if>
<if test="postName != null and postName != ''">
AND post_name like concat('%', #{postName}, '%')
</if>
</where>
</select>
<select id="selectPostAll" resultMap="PostResult">
<include refid="selectPostVo"/>
</select>
<select id="selectPostsByUserId" resultMap="PostResult">
SELECT p.post_id, p.post_name, p.post_code
FROM sys_user u
LEFT JOIN sys_user_post up ON u.user_id = up.user_id
LEFT JOIN sys_post p ON up.post_id = p.post_id
WHERE up.user_id = #{userId}
</select>
<select id="selectPostById" parameterType="Long" resultMap="PostResult">
<include refid="selectPostVo"/>
where post_id = #{postId}
</select>
<select id="checkPostNameUnique" parameterType="String" resultMap="PostResult">
<include refid="selectPostVo"/>
where post_name=#{postName}
</select>
<select id="checkPostCodeUnique" parameterType="String" resultMap="PostResult">
<include refid="selectPostVo"/>
where post_code=#{postCode}
</select>
<delete id="deletePostByIds" parameterType="Long">
delete from sys_post where post_id in
<foreach collection="array" item="postId" open="(" separator="," close=")">
#{postId}
</foreach>
</delete>
<update id="updatePost" parameterType="Post">
update sys_post
<set>
<if test="postCode != null and postCode != ''">post_code = #{postCode},</if>
<if test="postName != null and postName != ''">post_name = #{postName},</if>
<if test="postSort != null and postSort != ''">post_sort = #{postSort},</if>
<if test="status != null and status != ''">status = #{status},</if>
<if test="remark != null and remark != ''">remark = #{remark},</if>
<if test="updateBy != null and updateBy != ''">update_by = #{updateBy},</if>
update_time = sysdate()
</set>
where post_id = #{postId}
</update>
<insert id="insertPost" parameterType="Post" useGeneratedKeys="true" keyProperty="postId">
insert into sys_post(
<if test="postId != null and postId != 0">post_id,</if>
<if test="postCode != null and postCode != ''">post_code,</if>
<if test="postName != null and postName != ''">post_name,</if>
<if test="postSort != null and postSort != ''">post_sort,</if>
<if test="status != null and status != ''">status,</if>
<if test="remark != null and remark != ''">remark,</if>
<if test="createBy != null and createBy != ''">create_by,</if>
create_time
)values(
<if test="postId != null and postId != 0">#{postId},</if>
<if test="postCode != null and postCode != ''">#{postCode},</if>
<if test="postName != null and postName != ''">#{postName},</if>
<if test="postSort != null and postSort != ''">#{postSort},</if>
<if test="status != null and status != ''">#{status},</if>
<if test="remark != null and remark != ''">#{remark},</if>
<if test="createBy != null and createBy != ''">#{createBy},</if>
sysdate()
)
</insert>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sinobase.project.system.role.mapper.RoleDeptMapper">
<resultMap type="RoleDept" id="RoleDeptResult">
<result property="roleId" column="role_id" />
<result property="detpId" column="dept_id" />
</resultMap>
<delete id="deleteRoleDeptByRoleId" parameterType="String">
delete from sys_role_dept where role_id=#{roleId}
</delete>
<select id="selectCountRoleDeptByDeptId" resultType="Integer">
select count(1) from sys_role_dept where dept_id=#{detpId}
</select>
<delete id="deleteRoleDept" parameterType="String">
delete from sys_role_dept where role_id in
<foreach collection="array" item="roleId" open="(" separator="," close=")">
#{roleId}
</foreach>
</delete>
<insert id="batchRoleDept">
insert into sys_role_dept(role_id, dept_id) values
<foreach item="item" index="index" collection="list" separator=",">
(#{item.roleId},#{item.deptId})
</foreach>
</insert>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sinobase.project.system.role.mapper.RoleMapper">
<resultMap type="Role" id="RoleResult">
<id property="roleId" column="role_id" />
<result property="roleName" column="role_name" />
<result property="roleKey" column="role_key" />
<result property="roleSort" column="role_sort" />
<result property="dataScope" column="data_scope" />
<result property="status" column="status" />
<result property="delFlag" column="del_flag" />
<result property="createBy" column="create_by" />
<result property="createTime" column="create_time" />
<result property="updateBy" column="update_by" />
<result property="updateTime" column="update_time" />
<result property="remark" column="remark" />
</resultMap>
<sql id="selectRoleContactVo">
select distinct r.role_id, r.role_name, r.role_key, r.role_sort, r.data_scope,
r.status, r.del_flag, r.create_time, r.remark
from sys_role r
left join sys_user_role ur on ur.role_id = r.role_id
left join sys_user u on u.user_id = ur.user_id
left join sys_dept d on u.dept_id = d.dept_id
</sql>
<sql id="selectRoleVo">
select r.role_id, r.role_name, r.role_key, r.role_sort, r.data_scope, r.status, r.del_flag, r.create_time, r.remark
from sys_role r
</sql>
<select id="getID" resultType="String">
select max(CAST(role_id as SIGNED)+1) as maxid from sys_role
</select>
<select id="selectRoleList" parameterType="Role" resultMap="RoleResult">
<include refid="selectRoleContactVo"/>
where r.del_flag = '0'
<if test="roleName != null and roleName != ''">
AND r.role_name like concat('%', #{roleName}, '%')
</if>
<if test="status != null and status != ''">
AND r.status = #{status}
</if>
<if test="roleKey != null and roleKey != ''">
AND r.role_key like concat('%', #{roleKey}, '%')
</if>
<if test="dataScope != null and dataScope != ''">
AND r.data_scope = #{dataScope}
</if>
<if test="params.beginTime != null and params.beginTime != ''"><!-- 开始时间检索 -->
and date_format(r.create_time,'%y%m%d') &gt;= date_format(#{params.beginTime},'%y%m%d')
</if>
<if test="params.endTime != null and params.endTime != ''"><!-- 结束时间检索 -->
and date_format(r.create_time,'%y%m%d') &lt;= date_format(#{params.endTime},'%y%m%d')
</if>
<!-- 数据范围过滤 -->
${params.dataScope}
</select>
<select id="selectRolesByUserId" resultMap="RoleResult">
<include refid="selectRoleContactVo"/>
WHERE r.del_flag = '0' and ur.user_id = #{userId}
</select>
<select id="selectRoleById" parameterType="String" resultMap="RoleResult">
<include refid="selectRoleVo"/>
where r.del_flag = '0' and r.role_id = #{roleId}
</select>
<select id="checkRoleNameUnique" parameterType="String" resultMap="RoleResult">
<include refid="selectRoleVo"/>
where r.role_name=#{roleName}
</select>
<select id="checkRoleKeyUnique" parameterType="String" resultMap="RoleResult">
<include refid="selectRoleVo"/>
where r.role_key=#{roleKey}
</select>
<delete id="deleteRoleById" parameterType="String">
delete from sys_role where role_id = #{roleId}
</delete>
<delete id="deleteRoleByIds" parameterType="String">
update sys_role set del_flag = '2' where role_id in
<foreach collection="array" item="roleId" open="(" separator="," close=")">
#{roleId}
</foreach>
</delete>
<update id="updateRole" parameterType="Role">
update sys_role
<set>
<if test="roleName != null and roleName != ''">role_name = #{roleName},</if>
<if test="roleKey != null and roleKey != ''">role_key = #{roleKey},</if>
<if test="roleSort != null and roleSort != ''">role_sort = #{roleSort},</if>
<if test="dataScope != null and dataScope != ''">data_scope = #{dataScope},</if>
<if test="status != null and status != ''">status = #{status},</if>
<if test="remark != null and remark != ''">remark = #{remark},</if>
<if test="updateBy != null and updateBy != ''">update_by = #{updateBy},</if>
update_time = sysdate()
</set>
where role_id = #{roleId}
</update>
<insert id="insertRole" parameterType="Role" useGeneratedKeys="true" keyProperty="roleId">
insert into sys_role(
<if test="roleId != null and roleId != ''">role_id,</if>
<if test="roleName != null and roleName != ''">role_name,</if>
<if test="roleKey != null and roleKey != ''">role_key,</if>
<if test="roleSort != null and roleSort != ''">role_sort,</if>
<if test="dataScope != null and dataScope != ''">data_scope,</if>
<if test="status != null and status != ''">status,</if>
<if test="remark != null and remark != ''">remark,</if>
<if test="createBy != null and createBy != ''">create_by,</if>
create_time
)values(
<if test="roleId != null and roleId != ''">#{roleId},</if>
<if test="roleName != null and roleName != ''">#{roleName},</if>
<if test="roleKey != null and roleKey != ''">#{roleKey},</if>
<if test="roleSort != null and roleSort != ''">#{roleSort},</if>
<if test="dataScope != null and dataScope != ''">#{dataScope},</if>
<if test="status != null and status != ''">#{status},</if>
<if test="remark != null and remark != ''">#{remark},</if>
<if test="createBy != null and createBy != ''">#{createBy},</if>
sysdate()
)
</insert>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sinobase.project.system.role.mapper.RoleMenuMapper">
<resultMap type="RoleMenu" id="RoleMenuResult">
<result property="roleId" column="role_id" />
<result property="menuId" column="menu_id" />
</resultMap>
<delete id="deleteRoleMenuByRoleId" parameterType="String">
delete from sys_role_menu where role_id=#{roleId}
</delete>
<select id="selectCountRoleMenuByMenuId" resultType="Integer">
select count(1) from sys_role_menu where menu_id=#{menuId}
</select>
<delete id="deleteRoleMenu" parameterType="String">
delete from sys_role_menu where role_id in
<foreach collection="array" item="roleId" open="(" separator="," close=")">
#{roleId}
</foreach>
</delete>
<insert id="batchRoleMenu">
insert into sys_role_menu(role_id, menu_id) values
<foreach item="item" index="index" collection="list" separator=",">
(#{item.roleId},#{item.menuId})
</foreach>
</insert>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sinobase.project.system.user.mapper.UserDprbMapper">
<select id="getOrderNum" resultType="Integer">
select count(id) from sys_user_dprb where dept_id = #{deptId}
</select>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sinobase.project.system.group.mapper.UserGroupMapper">
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sinobase.project.system.user.mapper.UserMapper">
<resultMap type="User" id="UserResultDeptsRoles">
<id property="userId" column="user_id" />
<result property="userName" column="user_name" />
<result property="email" column="email" />
<result property="phonenumber" column="phonenumber" />
<result property="tel" column="tel" />
<result property="sex" column="sex" />
<result property="avatar" column="avatar" />
<result property="status" column="status" />
<result property="delFlag" column="del_flag" />
<result property="remark" column="remark" />
<result property="historyId" column="history_id" />
<result property="userStatus" column="user_status" />
<result property="masterCode" column="master_code" />
<result property="userCode" column="user_code" />
<result property="idcNumber" column="idc_Number" />
<collection property="depts" javaType="java.util.List" resultMap="deptResult" />
<collection property="roles" javaType="java.util.List" resultMap="RoleResult" />
</resultMap>
<resultMap type="User" id="UserResult">
<id property="userId" column="user_id" />
<result property="deptId" column="dept_id" />
<result property="deptName" column="dept_name" />
<result property="loginName" column="login_name" />
<result property="userName" column="user_name" />
<result property="email" column="email" />
<result property="phonenumber" column="phonenumber" />
<result property="tel" column="tel" />
<result property="sex" column="sex" />
<result property="avatar" column="avatar" />
<result property="password" column="password" />
<result property="salt" column="salt" />
<result property="status" column="status" />
<result property="delFlag" column="del_flag" />
<result property="loginIp" column="login_ip" />
<result property="loginDate" column="login_date" />
<result property="createBy" column="create_by" />
<result property="createTime" column="create_time" />
<result property="updateBy" column="update_by" />
<result property="updateTime" column="update_time" />
<result property="remark" column="remark" />
<result property="historyId" column="history_id" />
<result property="userStatus" column="user_status" />
<result property="masterCode" column="master_code" />
<result property="userCode" column="user_code" />
<result property="idcNumber" column="idc_Number" />
<result property="shortcut" column="shortcut" />
<association property="dept" column="dept_id" javaType="Dept" resultMap="deptResult" />
<collection property="roles" javaType="java.util.List" resultMap="RoleResult" />
</resultMap>
<resultMap id="deptResult" type="Dept">
<id property="deptId" column="dept_id" />
<result property="parentId" column="parent_id" />
<result property="deptName" column="dept_name" />
<result property="orderNum" column="order_num" />
<result property="status" column="dept_status" />
</resultMap>
<resultMap id="RoleResult" type="Role">
<id property="roleId" column="role_id" />
<result property="roleName" column="role_name" />
<result property="roleKey" column="role_key" />
<result property="roleSort" column="role_sort" />
<result property="dataScope" column="data_scope" />
<result property="status" column="role_status" />
</resultMap>
<sql id="selectUserVo">
select u.user_id, u.history_id, u.shortcut,(SELECT d.dept_name from sys_dept d JOIN sys_user_dprb sud on d.dept_id = sud.dept_id JOIN sys_user su on sud.user_id = su.user_id where su.user_id = #{userId} ORDER BY d.parent_id asc LIMIT 0,1) as dept_name,
u.login_name, u.user_name, u.email, u.phonenumber,u.tel, u.sex, u.avatar, u.password, u.salt, u.status, u.del_flag, u.login_ip, u.login_date, u.create_time, u.remark,u.user_code,u.idc_Number,
d.dept_id, d.parent_id, d.order_num, d.status as dept_status,
r.role_id, r.role_name, r.role_key, r.role_sort, r.data_scope, r.status as role_status
from sys_user u
LEFT JOIN sys_user_dprb ud ON u.user_id = ud.user_id
LEFT JOIN sys_dept d ON ud.dept_id = d.dept_id
LEFT JOIN sys_user_role ur ON u.user_id = ur.user_id
LEFT JOIN sys_role r ON r.role_id = ur.role_id
</sql>
<sql id="selectUserInfoDeptsRolesVo">
select
u.user_id,
u.login_name, u.user_name, u.email, u.phonenumber,u.tel, u.sex, u.avatar, u.password, u.salt, u.status, u.del_flag, u.login_ip, u.login_date, u.create_time, u.remark,u.user_code,u.idc_Number,
d.dept_id, d.parent_id, d.dept_name, d.order_num, d.status as dept_status,
r.role_id, r.role_name, r.role_key, r.role_sort, r.data_scope, r.status as role_status
from sys_user u
LEFT JOIN sys_user_dprb sud on u.user_id = sud.user_id
LEFT JOIN sys_dept d on sud.dept_id = d.dept_id
left join sys_user_role ur on u.user_id = ur.user_id
left join sys_role r on r.role_id = ur.role_id
</sql>
<select id="selectUserList" parameterType="User" resultMap="UserResult">
select u.user_id, u.dept_id, u.login_name, u.user_name, u.email, u.phonenumber,u.tel, u.password, u.sex, u.avatar, u.salt, u.status, u.del_flag, u.login_ip, u.login_date, u.create_by, u.create_time, u.remark,u.user_code,u.idc_Number,d.dept_name from sys_user u
left join sys_dept d on u.dept_id = d.dept_id
where u.del_flag = '0'
<if test="loginName != null and loginName != ''">
AND u.login_name like concat('%', #{loginName}, '%')
</if>
<if test="status != null and status != ''">
AND u.status = #{status}
</if>
<if test="phonenumber != null and phonenumber != ''">
AND u.phonenumber like concat('%', #{phonenumber}, '%')
</if>
<if test="params.beginTime != null and params.beginTime != ''"><!-- 开始时间检索 -->
AND date_format(u.create_time,'%y%m%d') &gt;= date_format(#{params.beginTime},'%y%m%d')
</if>
<if test="params.endTime != null and params.endTime != ''"><!-- 结束时间检索 -->
AND date_format(u.create_time,'%y%m%d') &lt;= date_format(#{params.endTime},'%y%m%d')
</if>
<if test="deptId != null and deptId != '0'.toString">
AND (u.dept_id = #{deptId} OR u.dept_id IN ( SELECT t.dept_id FROM sys_dept t WHERE FIND_IN_SET (#{deptId},ancestors) ))
</if>
<!-- 数据范围过滤 -->
${params.dataScope}
</select>
<select id="selectUserInfoDeptsRolesByUserId" parameterType="String" resultMap="UserResultDeptsRoles">
<include refid="selectUserInfoDeptsRolesVo"/>
where u.user_id = #{userId}
</select>
<select id="selectUserByLoginName" parameterType="String" resultMap="UserResult">
select * from sys_user where login_name = #{userName}
</select>
<select id="selectUserByLoginNameAndStatus" parameterType="String" resultMap="UserResult">
select * from sys_user where login_name = #{userName} and status = 1
</select>
<select id="selectUserByPhoneNumber" parameterType="String" resultMap="UserResult">
<include refid="selectUserVo"/>
where u.phonenumber = #{phonenumber}
</select>
<select id="selectUserByEmail" parameterType="String" resultMap="UserResult">
<include refid="selectUserVo"/>
where u.email = #{email}
</select>
<select id="checkLoginNameUnique" parameterType="String" resultType="int">
select count(1) from sys_user where login_name=#{loginName}
</select>
<select id="checkPhoneUnique" parameterType="String" resultMap="UserResult">
select user_id, phonenumber from sys_user where phonenumber=#{phonenumber}
</select>
<select id="checkEmailUnique" parameterType="String" resultMap="UserResult">
select user_id, email from sys_user where email=#{email}
</select>
<select id="selectUserById" resultMap="UserResult">
<include refid="selectUserVo"/>
where u.user_id = #{userId}
</select>
<delete id="deleteUserById" >
delete from sys_user where user_id = #{userId};
delete from sys_user_dprb where user_id = #{userId};
delete from sys_user_post where user_id = #{userId};
delete from sys_user_role where user_id = #{userId}
</delete>
<delete id="deleteUserByIds">
update sys_user set del_flag = '2' where user_id in
<foreach collection="array" item="userId" open="(" separator="," close=")">
#{userId}
</foreach>
</delete>
<update id="updateUser" parameterType="User">
update sys_user
<set>
<if test="deptId != null and deptId != '0'.toString">dept_id = #{deptId},</if>
<if test="loginName != null and loginName != ''">login_name = #{loginName},</if>
<if test="userName != null and userName != ''">user_name = #{userName},</if>
<if test="email != null and email != ''">email = #{email},</if>
<if test="phonenumber != null and phonenumber != ''">phonenumber = #{phonenumber},</if>
<if test="sex != null and sex != ''">sex = #{sex},</if>
<if test="avatar != null and avatar != ''">avatar = #{avatar},</if>
<if test="password != null and password != ''">password = #{password},</if>
<if test="salt != null and salt != ''">salt = #{salt},</if>
<if test="status != null and status != ''">status = #{status},</if>
<if test="loginIp != null and loginIp != ''">login_ip = #{loginIp},</if>
<if test="loginDate != null">login_date = #{loginDate},</if>
<if test="updateBy != null and updateBy != ''">update_by = #{updateBy},</if>
<if test="remark != null and remark != ''">remark = #{remark},</if>
<if test="shortcut != null and shortcut != ''">shortcut = #{shortcut},</if>
<if test="userCode != null and userCode != ''">user_code = #{userCode},</if>
<if test="idcNumber != null and idcNumber != ''">idc_Number = #{idcNumber},</if>
update_time = sysdate()
</set>
where user_id = #{userId}
</update>
<insert id="insertUser" parameterType="User" useGeneratedKeys="true" keyProperty="userId">
insert into sys_user(
<if test="userId != null and userId != '0'.toString">user_id,</if>
<if test="deptId != null and deptId != '0'.toString">dept_id,</if>
<if test="loginName != null and loginName != ''">login_name,</if>
<if test="userName != null and userName != ''">user_name,</if>
<if test="email != null and email != ''">email,</if>
<if test="phonenumber != null and phonenumber != ''">phonenumber,</if>
<if test="sex != null and sex != ''">sex,</if>
<if test="password != null and password != ''">password,</if>
<if test="salt != null and salt != ''">salt,</if>
<if test="status != null and status != ''">status,</if>
<if test="createBy != null and createBy != ''">create_by,</if>
<if test="remark != null and remark != ''">remark,</if>
<if test="userCode != null and userCode != ''">user_code,</if>
<if test="idcNumber != null and idcNumber != ''">idc_Number,</if>
create_time
)values(
<if test="userId != null and userId != ''">#{userId},</if>
<if test="deptId != null and deptId != ''">#{deptId},</if>
<if test="loginName != null and loginName != ''">#{loginName},</if>
<if test="userName != null and userName != ''">#{userName},</if>
<if test="email != null and email != ''">#{email},</if>
<if test="phonenumber != null and phonenumber != ''">#{phonenumber},</if>
<if test="sex != null and sex != ''">#{sex},</if>
<if test="password != null and password != ''">#{password},</if>
<if test="salt != null and salt != ''">#{salt},</if>
<if test="status != null and status != ''">#{status},</if>
<if test="createBy != null and createBy != ''">#{createBy},</if>
<if test="remark != null and remark != ''">#{remark},</if>
<if test="userCode != null and userCode != ''">#{userCode},</if>
<if test="idcNumber != null and idcNumber != ''">#{idcNumber},</if>
sysdate()
)
</insert>
<select id="selectMaxId" resultType="Integer">
select max(CAST(user_id AS SIGNED)) from sys_user
</select>
<select id="listUserDetIds" parameterType="java.lang.String" resultMap="UserResult">
<include refid="selectUserVo"/>
<where>
d.dept_id in
<foreach collection="array" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</where>
</select>
<select id="listUserByUserId" parameterType="java.lang.String" resultMap="UserResult">
select * from sys_user
<where>
user_id in
<foreach collection="array" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</where>
</select>
<!-- 集成公司平台代码 开始 -->
<!-- 集成公司平台专用:根据条件分页查询用户对象 -->
<select id="selectUserListForPlatform" parameterType="User" resultMap="UserResult">
select u.user_id,u.login_name,u.user_name,u.user_type,u.history_id,u.user_status,u.master_code,u.email,
u.phonenumber,u.tel, u.password, u.sex, u.avatar, u.status,u.del_flag,u.remark,u.user_code,u.idc_Number,r.dept_id
from sys_user u,sys_user_dprb r
where r.user_id = u.user_id and r.status='1'
<choose>
<when test="historyId != null and historyId != ''">
and u.history_id = #{historyId}
</when>
<otherwise>
<choose>
<when test="deptId != null and deptId != ''">
and r.dept_id = #{deptId}
</when>
<otherwise>
and r.dept_id = '0'
</otherwise>
</choose>
</otherwise>
</choose>
<if test="loginName != null and loginName != ''">
and u.login_name like concat('%', #{loginName}, '%')
</if>
<if test="status != null and status != ''">
and u.status = #{status}
</if>
order by r.order_no
<!-- 数据范围过滤 -->
${params.dataScope}
</select>
<!--添加用户信息-->
<insert id="insertUserByList" parameterType="java.lang.Object">
insert IGNORE into sys_user
(
user_id,
history_id,
login_name,
user_name,
status,
user_status,
sex,
phonenumber,
phone_imei,
master_code,
email,
del_flag,
user_code,
idc_Number,
create_time
)
values
<foreach collection="list" item="user" index="index" separator=",">
(
#{user.userId},
#{user.historyId},
#{user.loginName},
#{user.userName},
#{user.status},
#{user.userStatus},
#{user.sex},
#{user.phonenumber},
#{user.phoneImei},
#{user.masterCode},
#{user.email},
#{user.delFlag},
#{user.userCode},
#{user.idcNumber},
sysdate()
)
</foreach>
</insert>
<!--获取所有用户信息-->
<select id="selectAllUserList" resultMap="UserResult">
select
su.user_id,su.dept_id, su.login_name,su.user_name,su.user_status,su.phone_imei,su.master_code,su.history_id,su.email,su.phonenumber,su.tel,su.sex,su.password,su.status,su.del_flag,su.create_by
from
sys_user su
</select>
<!-- 更新排序 -->
<select id="selectUserForSort" parameterType="java.lang.String" resultMap="UserResult">
select r.id as user_id,u.user_name,u.status
from sys_user u,sys_user_dprb r
where u.user_id=r.user_id and r.dept_id=#{deptId} and r.status='1'
order by r.order_no
</select>
<!-- 批量更新排序字段 -->
<update id="sortSave" parameterType="String">
<foreach collection="array" item="rid" index="index" open="" close="" separator=";">
update sys_user_dprb
<set>
order_no = #{index}
</set>
where id = #{rid}
</foreach>
</update>
<!--根据部门id获取当前部门下的用户信息-->
<select id="selectUserListByDeptId" parameterType="java.lang.String" resultMap="UserResult">
select su.user_id,su.dept_id, su.login_name,su.user_name,su.user_status,su.phone_imei,su.master_code,su.history_id,su.email,su.phonenumber,su.tel,su.sex,su.password,su.status,su.del_flag,su.create_by,su.user_code,su.idc_Number
from
sys_user_dprb sud
join
sys_user su
on
sud.user_id = su.user_id
where
sud.dept_id = #{deptId} and sud.dept_id is not null and sud.status='1' and su.status='1'
order by cast(sud.order_no as SIGNED INTEGER) asc
</select>
<!--页面显示用户数据 根据部门id获取部门下所有用户-->
<select id="selectUserListByHtml" parameterType="User" resultMap="UserResult">
select
u.user_id, d.dept_id,u.login_name,u.user_status,u.phone_imei,u.master_code,u.history_id, u.user_name, u.email,
u.phonenumber,u.tel, d.dept_name,u.password, u.sex, u.avatar, u.salt, u.status, u.del_flag, u.login_ip,
u.login_date, u.create_by, u.create_time, u.remark,u.user_code,u.idc_Number
from
sys_user_dprb sud
join
sys_user u
on
sud.user_id = u.user_id
join
sys_dept d
on
d.dept_id = sud.dept_id
<where>
<if test="loginName != null and loginName != ''">
AND u.login_name like concat('%', #{loginName}, '%')
</if>
<if test="status != null and status != ''">
AND u.status = #{status}
</if>
<if test="phonenumber != null and phonenumber != ''">
AND u.phonenumber like concat('%', #{phonenumber}, '%')
</if>
<if test="params.beginTime != null and params.beginTime != ''"><!-- 开始时间检索 -->
AND date_format(u.create_time,'%y%m%d') &gt;= date_format(#{params.beginTime},'%y%m%d')
</if>
<if test="params.endTime != null and params.endTime != ''"><!-- 结束时间检索 -->
AND date_format(u.create_time,'%y%m%d') &lt;= date_format(#{params.endTime},'%y%m%d')
</if>
<if test="deptId != null and deptId != 0">
AND (d.dept_id = #{deptId} OR d.dept_id IN ( select sd.dept_id
from sys_dept sd
WHERE sd.status = '1' and sd.ancestors LIKE CONCAT((SELECT t.ancestors FROM sys_dept t where t.dept_id = #{deptId}),'%') ))
</if>
<!-- 数据范围过滤 -->
${params.dataScope}
</where>
ORDER BY d.parent_id,d.order_num is null ,d.order_num, order_no = 'null',sud.order_no+0 asc
</select>
<!--获取部门下的用户信息为用户树提供相应数据-->
<select id="getAllUser" resultType="java.util.Map">
SELECT su.user_id as id,su.user_name as name,sud.dept_id as parentId
from
sys_user_dprb sud
JOIN sys_user su
on sud.user_id=su.user_id and su.status='1' and sud.status='1'
order by sud.order_no asc
</select>
<!--根据sql添加用户信息-->
<insert id="insertUserBySql" parameterType="java.lang.String">
${sql}
</insert>
<!--根据部门id,以及相关权限获取所有子孙部门-->
<select id="getAllChildren" parameterType="java.lang.String" resultType="java.util.HashMap">
select d.dept_id, (select dept_short from sys_dept where dept_id=d.parent_id) as company_name, d.dept_short, d.dept_name, u.user_name ,u.user_id, u.history_id from sys_dept d,sys_user u,sys_user_dprb s
<where>
d.dept_id=s.dept_id and u.user_id=s.user_id and d.status = '1' and d.history_id like '001' '%' and s.status='1' and u.status='1'
and d.ancestors like CONCAT('%', CONCAT(#{ancestors}), '%')
and u.user_name like CONCAT('%', CONCAT(#{username}), '%')
</where>
order by d.parent_id,d.order_num,s.order_no asc
</select>
<select id="selectAllocatedList" parameterType="User" resultMap="UserResult">
select distinct u.user_id, u.dept_id, u.login_name, u.user_name, u.email, u.avatar, u.phonenumber,u.tel, u.status, u.create_time
from sys_user u
left join sys_dept d on u.dept_id = d.dept_id
left join sys_user_role ur on u.user_id = ur.user_id
left join sys_role r on r.role_id = ur.role_id
where
<!--u.del_flag = '0' and -->
r.role_id = #{roleId}
<if test="loginName != null and loginName != ''">
AND u.login_name like concat('%', #{loginName}, '%')
</if>
<if test="phonenumber != null and phonenumber != ''">
AND u.phonenumber like concat('%', #{phonenumber}, '%')
</if>
</select>
<select id="selectUnallocatedList" parameterType="User" resultMap="UserResult">
select distinct u.user_id, u.dept_id, u.login_name, u.user_name, u.email, u.avatar, u.phonenumber,u.tel, u.status, u.create_time
from sys_user u
left join sys_dept d on u.dept_id = d.dept_id
left join sys_user_role ur on u.user_id = ur.user_id
left join sys_role r on r.role_id = ur.role_id
where
<!--u.del_flag = '0' and-->
(r.role_id != #{roleId} or r.role_id IS NULL)
and u.user_id not in (select u.user_id from sys_user u inner join sys_user_role ur on u.user_id = ur.user_id and ur.role_id = #{roleId})
<if test="loginName != null and loginName != ''">
AND u.login_name like concat('%', #{loginName}, '%')
</if>
<if test="phonenumber != null and phonenumber != ''">
AND u.phonenumber like concat('%', #{phonenumber}, '%')
</if>
</select>
<select id="selectUserByMasterCode" parameterType="String" resultMap="UserResult">
select * from sys_user where master_code = #{masterCode}
</select>
<select id="getUserZHByDeptShort" resultType="java.util.HashMap">
select u.user_id,u.dept_id,u.login_name,u.user_name,d.parent_id,d.dept_short,d.dept_name,d.note,de.dept_short as parent_short from sys_user u
left join sys_dept d on (d.dept_id=u.dept_id)
left join sys_dept de on (de.dept_id=d.parent_id)
where u.user_name like '%综合%'
and (d.dept_short=#{deptShort } or de.dept_short=#{deptShort })
</select>
<select id="getUserZHByDeptShorts" resultType="java.util.HashMap">
select u.user_id,u.dept_id,u.login_name,u.user_name,d.parent_id,d.dept_short,d.dept_name,d.note,de.dept_short as parent_short from sys_user u
left join sys_dept d on (d.dept_id=u.dept_id)
left join sys_dept de on (de.dept_id=d.parent_id)
where u.user_name like '%综合%'
and (d.dept_short in
<foreach item="deptShort" collection="deptShorts" separator="," open="(" close=")">
#{deptShort }
</foreach>
or de.dept_short in
<foreach item="deptShort" collection="deptShorts" separator="," open="(" close=")">
#{deptShort }
</foreach>
)
</select>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sinobase.project.system.user.mapper.UserPostMapper">
<resultMap type="UserPost" id="UserPostResult">
<result property="userId" column="user_id" />
<result property="postId" column="post_id" />
</resultMap>
<delete id="deleteUserPostByUserId">
delete from sys_user_post where user_id=#{userId}
</delete>
<select id="countUserPostById" resultType="Integer">
select count(1) from sys_user_post where post_id=#{postId}
</select>
<delete id="deleteUserPost" parameterType="String">
delete from sys_user_post where user_id in
<foreach collection="array" item="userId" open="(" separator="," close=")">
#{userId}
</foreach>
</delete>
<insert id="batchUserPost">
insert into sys_user_post(user_id, post_id) values
<foreach item="item" index="index" collection="list" separator=",">
(#{item.userId},#{item.postId})
</foreach>
</insert>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sinobase.project.system.user.mapper.UserRoleMapper">
<resultMap type="UserRole" id="UserRoleResult">
<result property="userId" column="user_id" />
<result property="roleId" column="role_id" />
</resultMap>
<delete id="deleteUserRoleByUserId">
delete from sys_user_role where user_id=#{userId}
</delete>
<select id="countUserRoleByRoleId" resultType="Integer">
select count(1) from sys_user_role where role_id=#{roleId}
</select>
<delete id="deleteUserRole" parameterType="Long">
delete from sys_user_role where user_id in
<foreach collection="array" item="userId" open="(" separator="," close=")">
#{userId}
</foreach>
</delete>
<insert id="batchUserRole">
insert into sys_user_role(user_id, role_id) values
<foreach item="item" index="index" collection="list" separator=",">
(#{item.userId},#{item.roleId})
</foreach>
</insert>
<delete id="deleteUserRoleInfo" parameterType="UserRole">
delete from sys_user_role where user_id=#{userId} and role_id=#{roleId}
</delete>
<delete id="deleteUserRoleInfos">
delete from sys_user_role where role_id=#{roleId} and user_id in
<foreach collection="userIds" item="userId" open="(" separator="," close=")">
#{userId}
</foreach>
</delete>
</mapper>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment