Commit 8b643e22 authored by HuangBingGui's avatar HuangBingGui
Browse files

no commit message

parent 563ff060
/**
* Copyright (c) 2005-2012 springside.org.cn
*/
package com.jeespring.common.security;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import org.apache.commons.lang3.Validate;
import com.jeespring.common.utils.Exceptions;
/**
* 支持SHA-1/MD5消息摘要的工具类.
*
* 返回ByteSource,可进一步被编码为Hex, Base64或UrlSafeBase64
*
* @author JeeSpring
*/
public class Digests {
private static final String SHA1 = "SHA-1";
private static final String MD5 = "MD5";
private static SecureRandom random = new SecureRandom();
/**
* 对输入字符串进行md5散列.
*/
public static byte[] md5(byte[] input) {
return digest(input, MD5, null, 1);
}
public static byte[] md5(byte[] input, int iterations) {
return digest(input, MD5, null, iterations);
}
/**
* 对输入字符串进行sha1散列.
*/
public static byte[] sha1(byte[] input) {
return digest(input, SHA1, null, 1);
}
public static byte[] sha1(byte[] input, byte[] salt) {
return digest(input, SHA1, salt, 1);
}
public static byte[] sha1(byte[] input, byte[] salt, int iterations) {
return digest(input, SHA1, salt, iterations);
}
/**
* 对字符串进行散列, 支持md5与sha1算法.
*/
private static byte[] digest(byte[] input, String algorithm, byte[] salt, int iterations) {
try {
MessageDigest digest = MessageDigest.getInstance(algorithm);
if (salt != null) {
digest.update(salt);
}
byte[] result = digest.digest(input);
for (int i = 1; i < iterations; i++) {
digest.reset();
result = digest.digest(result);
}
return result;
} catch (GeneralSecurityException e) {
throw Exceptions.unchecked(e);
}
}
/**
* 生成随机的Byte[]作为salt.
*
* @param numBytes byte数组的大小
*/
public static byte[] generateSalt(int numBytes) {
Validate.isTrue(numBytes > 0, "numBytes argument must be a positive integer (1 or larger)", numBytes);
byte[] bytes = new byte[numBytes];
random.nextBytes(bytes);
return bytes;
}
/**
* 对文件进行md5散列.
*/
public static byte[] md5(InputStream input) throws IOException {
return digest(input, MD5);
}
/**
* 对文件进行sha1散列.
*/
public static byte[] sha1(InputStream input) throws IOException {
return digest(input, SHA1);
}
private static byte[] digest(InputStream input, String algorithm) throws IOException {
try {
MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
int bufferLength = 8 * 1024;
byte[] buffer = new byte[bufferLength];
int read = input.read(buffer, 0, bufferLength);
while (read > -1) {
messageDigest.update(buffer, 0, read);
read = input.read(buffer, 0, bufferLength);
}
return messageDigest.digest();
} catch (GeneralSecurityException e) {
throw Exceptions.unchecked(e);
}
}
public static String string2MD5(String inStr){
MessageDigest md5 = null;
try{
md5 = MessageDigest.getInstance("MD5");
}catch (Exception e){
System.out.println(e.toString());
e.printStackTrace();
return "";
}
char[] charArray = inStr.toCharArray();
byte[] byteArray = new byte[charArray.length];
for (int i = 0; i < charArray.length; i++)
byteArray[i] = (byte) charArray[i];
byte[] md5Bytes = md5.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++){
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16)
hexValue.append("0");
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
}
package com.jeespring.common.security;
import java.security.MessageDigest;
/**
* MD5加密工具类
* <功能详细描述>
*
* @author chenlujun
* @version [版本号, 2014年10月1日]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class MD5Tools
{
public final static String MD5(String pwd) {
//用于加密的字符
char md5String[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F' };
try {
//使用平台的默认字符集将此 String 编码为 byte序列,并将结果存储到一个新的 byte数组中
byte[] btInput = pwd.getBytes();
//信息摘要是安全的单向哈希函数,它接收任意大小的数据,并输出固定长度的哈希值。
MessageDigest mdInst = MessageDigest.getInstance("MD5");
//MessageDigest对象通过使用 update方法处理数据, 使用指定的byte数组更新摘要
mdInst.update(btInput);
// 摘要更新之后,通过调用digest()执行哈希计算,获得密文
byte[] md = mdInst.digest();
// 把密文转换成十六进制的字符串形式
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) { // i = 0
byte byte0 = md[i]; //95
str[k++] = md5String[byte0 >>> 4 & 0xf]; // 5
str[k++] = md5String[byte0 & 0xf]; // F
}
//返回经过加密后的字符串
return new String(str);
} catch (Exception e) {
return null;
}
}
}
\ No newline at end of file
package com.jeespring.common.security;
import com.jeespring.modules.sys.entity.User;
import com.jeespring.modules.sys.entity.UserRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import com.jeespring.common.utils.StringUtils;
import com.jeespring.common.utils.bean.BeanUtils;
/**
* shiro 工具类
*
* @author JeeSpring
*/
public class ShiroUtils
{
public static Subject getSubjct()
{
return SecurityUtils.getSubject();
}
public static Session getSession()
{
return SecurityUtils.getSubject().getSession();
}
public static void logout()
{
getSubjct().logout();
}
public static User getUser()
{
User user = null;
Object obj = getSubjct().getPrincipal();
if (StringUtils.isNotNull(obj))
{
user = new User();
BeanUtils.copyBeanProp(user, obj);
}
return user;
}
public static void setUser(User user)
{
Subject subject = getSubjct();
PrincipalCollection principalCollection = subject.getPrincipals();
String realmName = principalCollection.getRealmNames().iterator().next();
PrincipalCollection newPrincipalCollection = new SimplePrincipalCollection(user, realmName);
// 重新加载Principal
subject.runAs(newPrincipalCollection);
}
public static void clearCachedAuthorizationInfo()
{
RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
UserRealm realm = (UserRealm) rsm.getRealms().iterator().next();
realm.clearCachedAuthorizationInfo();
}
public static Long getUserId()
{
return Long.valueOf(getUser().getId());
}
public static String getLoginName()
{
return getUser().getLoginName();
}
public static String getIp()
{
return getSubjct().getSession().getHost();
}
public static String getSessionId()
{
return String.valueOf(getSubjct().getSession().getId());
}
}
/**
* Copyright &copy; 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package com.jeespring.common.security.shiro;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.tags.PermissionTag;
/**
* Shiro HasAnyPermissions Tag.
*
* @author calvin
*/
public class HasAnyPermissionsTag extends PermissionTag {
private static final long serialVersionUID = 1L;
private static final String PERMISSION_NAMES_DELIMETER = ",";
@Override
protected boolean showTagBody(String permissionNames) {
boolean hasAnyPermission = false;
Subject subject = getSubject();
if (subject != null) {
// Iterate through permissions and check to see if the user has one of the permissions
for (String permission : permissionNames.split(PERMISSION_NAMES_DELIMETER)) {
if (subject.isPermitted(permission.trim())) {
hasAnyPermission = true;
break;
}
}
}
return hasAnyPermission;
}
}
/**
* Copyright &copy; 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package com.jeespring.common.security.shiro.cache;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Sets;
import com.jeespring.common.web.Servlets;
/**
* 自定义授权缓存管理类
* @author 黄炳桂 516821420@qq.com
* @version 2014-7-21
*/
public class SessionCacheManager implements CacheManager {
@Override
public <K, V> Cache<K, V> getCache(String name) throws CacheException {
return new SessionCache<K, V>(name);
}
/**
* SESSION缓存管理类
*/
public class SessionCache<K, V> implements Cache<K, V> {
private Logger logger = LoggerFactory.getLogger(getClass());
private String cacheKeyName = null;
public SessionCache(String cacheKeyName) {
this.cacheKeyName = cacheKeyName;
}
public Session getSession(){
Session session = null;
try{
Subject subject = SecurityUtils.getSubject();
session = subject.getSession(false);
if (session == null){
session = subject.getSession();
}
}catch (InvalidSessionException e){
logger.error("Invalid session error", e);
}catch (UnavailableSecurityManagerException e2){
logger.error("Unavailable SecurityManager error", e2);
}
return session;
}
@SuppressWarnings("unchecked")
@Override
public V get(K key) throws CacheException {
if (key == null){
return null;
}
V v = null;
HttpServletRequest request = Servlets.getRequest();
if (request != null){
v = (V)request.getAttribute(cacheKeyName);
if (v != null){
return v;
}
}
V value = null;
value = (V)getSession().getAttribute(cacheKeyName);
logger.debug("get {} {} {}", cacheKeyName, key, request != null ? request.getRequestURI() : "");
if (request != null && value != null){
request.setAttribute(cacheKeyName, value);
}
return value;
}
@Override
public V put(K key, V value) throws CacheException {
if (key == null){
return null;
}
getSession().setAttribute(cacheKeyName, value);
if (logger.isDebugEnabled()){
HttpServletRequest request = Servlets.getRequest();
logger.debug("put {} {} {}", cacheKeyName, key, request != null ? request.getRequestURI() : "");
}
return value;
}
@SuppressWarnings("unchecked")
@Override
public V remove(K key) throws CacheException {
V value = null;
value = (V)getSession().removeAttribute(cacheKeyName);
logger.debug("remove {} {}", cacheKeyName, key);
return value;
}
@Override
public void clear() throws CacheException {
getSession().removeAttribute(cacheKeyName);
logger.debug("clear {}", cacheKeyName);
}
@Override
public int size() {
logger.debug("invoke session size abstract size method not supported.");
return 0;
}
@Override
public Set<K> keys() {
logger.debug("invoke session keys abstract size method not supported.");
return Sets.newHashSet();
}
@Override
public Collection<V> values() {
logger.debug("invoke session values abstract size method not supported.");
return Collections.emptyList();
}
}
}
/**
* Copyright &copy; 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package com.jeespring.common.security.shiro.session;
import java.io.Serializable;
import java.util.Collection;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.google.common.collect.Sets;
import com.jeespring.common.config.Global;
import com.jeespring.common.utils.DateUtils;
import com.jeespring.common.utils.IdGen;
import com.jeespring.common.utils.StringUtils;
import com.jeespring.common.web.Servlets;
/**
* 系统安全认证实现类
* @author 黄炳桂 516821420@qq.com
* @version 2014-7-24
*/
@Component("sessionDAO")
public class CacheSessionDAO extends EnterpriseCacheSessionDAO implements SessionDAO,InitializingBean{
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private IdGen idgen;
@Autowired
private CacheManager cacheManager;
@Override
public void afterPropertiesSet() throws Exception {
setSessionIdGenerator(idgen);
setActiveSessionsCacheName("activeSessionsCache");
setCacheManager(cacheManager);
}
public CacheSessionDAO() {
super();
}
@Override
protected void doUpdate(Session session) {
if (session == null || session.getId() == null) {
return;
}
HttpServletRequest request = Servlets.getRequest();
if (request != null){
String uri = request.getServletPath();
// 如果是静态文件,则不更新SESSION
if (Servlets.isStaticFile(uri)){
return;
}
// 如果是视图文件,则不更新SESSION
if (StringUtils.startsWith(uri, Global.getConfig("spring.mvc.view.prefix"))
&& StringUtils.endsWith(uri, Global.getConfig("spring.mvc.view.suffix"))){
return;
}
// 手动控制不更新SESSION
String updateSession = request.getParameter("updateSession");
if (Global.FALSE.equals(updateSession) || Global.NO.equals(updateSession)){
return;
}
}
super.doUpdate(session);
logger.debug("update {} {}", session.getId(), request != null ? request.getRequestURI() : "");
}
@Override
protected void doDelete(Session session) {
if (session == null || session.getId() == null) {
return;
}
super.doDelete(session);
logger.debug("delete {} ", session.getId());
}
@Override
protected Serializable doCreate(Session session) {
HttpServletRequest request = Servlets.getRequest();
if (request != null){
String uri = request.getServletPath();
// 如果是静态文件,则不创建SESSION
if (Servlets.isStaticFile(uri)){
return null;
}
}
super.doCreate(session);
logger.debug("doCreate {} {}", session, request != null ? request.getRequestURI() : "");
return session.getId();
}
@Override
protected Session doReadSession(Serializable sessionId) {
return super.doReadSession(sessionId);
}
@Override
public Session readSession(Serializable sessionId) throws UnknownSessionException {
try{
Session s = null;
HttpServletRequest request = Servlets.getRequest();
if (request != null){
String uri = request.getServletPath();
// 如果是静态文件,则不获取SESSION
if (Servlets.isStaticFile(uri)){
return null;
}
s = (Session)request.getAttribute("session_"+sessionId);
}
if (s != null){
return s;
}
Session session = super.readSession(sessionId);
logger.debug("readSession {} {}", sessionId, request != null ? request.getRequestURI() : "");
if (request != null && session != null){
request.setAttribute("session_"+sessionId, session);
}
return session;
}catch (UnknownSessionException e) {
return null;
}
}
/**
* 获取活动会话
* @param includeLeave 是否包括离线(最后访问时间大于3分钟为离线会话)
* @return
*/
@Override
public Collection<Session> getActiveSessions(boolean includeLeave) {
return getActiveSessions(includeLeave, null, null);
}
/**
* 获取活动会话
* @param includeLeave 是否包括离线(最后访问时间大于3分钟为离线会话)
* @param principal 根据登录者对象获取活动会话
* @param filterSession 不为空,则过滤掉(不包含)这个会话。
* @return
*/
@Override
public Collection<Session> getActiveSessions(boolean includeLeave, Object principal, Session filterSession) {
// 如果包括离线,并无登录者条件。
if (includeLeave && principal == null){
return getActiveSessions();
}
Set<Session> sessions = Sets.newHashSet();
for (Session session : getActiveSessions()){
boolean isActiveSession = false;
// 不包括离线并符合最后访问时间小于等于3分钟条件。
if (includeLeave || DateUtils.pastMinutes(session.getLastAccessTime()) <= 3){
isActiveSession = true;
}
// 符合登陆者条件。
if (principal != null){
PrincipalCollection pc = (PrincipalCollection)session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
if (principal.toString().equals(pc != null ? pc.getPrimaryPrincipal().toString() : StringUtils.EMPTY)){
isActiveSession = true;
}
}
// 过滤掉的SESSION
if (filterSession != null && filterSession.getId().equals(session.getId())){
isActiveSession = false;
}
if (isActiveSession){
sessions.add(session);
}
}
return sessions;
}
}
package com.jeespring.common.security.shiro.session;
import java.util.Collection;
import org.apache.shiro.session.Session;
public interface SessionDAO extends org.apache.shiro.session.mgt.eis.SessionDAO {
/**
* 获取活动会话
* @param includeLeave 是否包括离线(最后访问时间大于3分钟为离线会话)
* @return
*/
Collection<Session> getActiveSessions(boolean includeLeave);
/**
* 获取活动会话
* @param includeLeave 是否包括离线(最后访问时间大于3分钟为离线会话)
* @param principal 根据登录者对象获取活动会话
* @param filterSession 不为空,则过滤掉(不包含)这个会话。
* @return
*/
Collection<Session> getActiveSessions(boolean includeLeave, Object principal, Session filterSession);
}
/**
* Copyright &copy; 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package com.jeespring.common.security.shiro.session;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jeespring.common.utils.StringUtils;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SessionContext;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.session.mgt.SimpleSession;
import org.apache.shiro.web.servlet.Cookie;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Component;
/**
* 自定义WEB会话管理类
* @author 黄炳桂 516821420@qq.com
* @version 2014-7-20
*/
@Component
public class SessionManager extends DefaultWebSessionManager {
public SessionManager() {
super();
}
@Override
protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
// 如果参数中包含“__sid”参数,则使用此sid会话。 例如:http://localhost/project?__sid=xxx&__cookie=true
String sid = request.getParameter("__sid");
if (StringUtils.isNotBlank(sid)) {
// 是否将sid保存到cookie,浏览器模式下使用此参数。
if (WebUtils.isTrue(request, "__cookie")){
HttpServletRequest rq = (HttpServletRequest)request;
HttpServletResponse rs = (HttpServletResponse)response;
Cookie template = getSessionIdCookie();
Cookie cookie = new SimpleCookie(template);
cookie.setValue(sid); cookie.saveTo(rq, rs);
}
// 设置当前session状态
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE,
ShiroHttpServletRequest.URL_SESSION_ID_SOURCE); // session来源与url
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sid);
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
return sid;
}else{
return super.getSessionId(request, response);
}
}
@Override
public void validateSessions() {
super.validateSessions();
}
protected Session retrieveSession(SessionKey sessionKey) {
try{
return super.retrieveSession(sessionKey);
}catch (UnknownSessionException e) {
// 获取不到SESSION不抛出异常
return null;
}
}
public Date getStartTimestamp(SessionKey key) {
try{
return super.getStartTimestamp(key);
}catch (InvalidSessionException e) {
// 获取不到SESSION不抛出异常
return null;
}
}
public Date getLastAccessTime(SessionKey key) {
try{
return super.getLastAccessTime(key);
}catch (InvalidSessionException e) {
// 获取不到SESSION不抛出异常
return null;
}
}
public long getTimeout(SessionKey key){
try{
return super.getTimeout(key);
}catch (InvalidSessionException e) {
// 获取不到SESSION不抛出异常
return 0;
}
}
public void setTimeout(SessionKey key, long maxIdleTimeInMillis) {
try{
super.setTimeout(key, maxIdleTimeInMillis);
}catch (InvalidSessionException e) {
// 获取不到SESSION不抛出异常
}
}
public void touch(SessionKey key) {
try{
super.touch(key);
}catch (InvalidSessionException e) {
// 获取不到SESSION不抛出异常
}
}
public String getHost(SessionKey key) {
try{
return super.getHost(key);
}catch (InvalidSessionException e) {
// 获取不到SESSION不抛出异常
return null;
}
}
public Collection<Object> getAttributeKeys(SessionKey key) {
try{
return super.getAttributeKeys(key);
}catch (InvalidSessionException e) {
// 获取不到SESSION不抛出异常
return null;
}
}
public Object getAttribute(SessionKey sessionKey, Object attributeKey) {
try{
return super.getAttribute(sessionKey, attributeKey);
}catch (InvalidSessionException e) {
// 获取不到SESSION不抛出异常
return null;
}
}
public void setAttribute(SessionKey sessionKey, Object attributeKey, Object value) {
try{
super.setAttribute(sessionKey, attributeKey, value);
}catch (InvalidSessionException e) {
// 获取不到SESSION不抛出异常
}
}
public Object removeAttribute(SessionKey sessionKey, Object attributeKey) {
try{
return super.removeAttribute(sessionKey, attributeKey);
}catch (InvalidSessionException e) {
// 获取不到SESSION不抛出异常
return null;
}
}
public void stop(SessionKey key) {
try{
super.stop(key);
}catch (InvalidSessionException e) {
// 获取不到SESSION不抛出异常
}
}
public void checkValid(SessionKey key) {
try{
super.checkValid(key);
}catch (InvalidSessionException e) {
// 获取不到SESSION不抛出异常
}
}
@Override
protected Session doCreateSession(SessionContext context) {
try{
return super.doCreateSession(context);
}catch (IllegalStateException e) {
return null;
}
}
@Override
protected Session newSessionInstance(SessionContext context) {
Session session = super.newSessionInstance(context);
session.setTimeout(getGlobalSessionTimeout());
return session;
}
@Override
public Session start(SessionContext context) {
try{
return super.start(context);
}catch (NullPointerException e) {
SimpleSession session = new SimpleSession();
session.setId(0);
return session;
}
}
}
\ No newline at end of file
/**
* Copyright &copy; 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package com.jeespring.common.service;
import com.jeespring.common.persistence.InterfaceBaseDao;
import com.jeespring.common.persistence.AbstractBaseEntity;
import com.jeespring.common.persistence.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Service基类
*
* @author 黄炳桂 516821420@qq.com
* @version 2014-05-16
*/
@Transactional(readOnly = true)
public abstract class AbstractBaseService<Dao extends InterfaceBaseDao<T>, T extends AbstractBaseEntity<T>> extends AbstractService {
/**
* 持久层对象
*/
@Autowired
protected Dao dao;
/**
* 获取单条数据
*
* @param id
* @return
*/
public T get(String id) {
return dao.get(id);
}
/**
* 获取单条数据
*
* @param entity
* @return
*/
public T get(T entity) {
return dao.get(entity);
}
/**
* 查询统计数据
*
* @param entity
* @return
*/
public List<T> total(T entity) {
return dao.total(entity);
}
/**
* 查询列表数据
*
* @param entity
* @return
*/
public List<T> findList(T entity) {
return dao.findList(entity);
}
/**
* 查询所有
*
* @param entity
* @return
*/
public List<T> findAllList(T entity) {
return dao.findAllList(entity);
}
/**
* 查询分页数据
*
* @param page 分页对象
* @param entity
* @return
*/
public Page<T> findPage(Page<T> page, T entity) {
entity.setPage(page);
page.setList(dao.findList(entity));
return page;
}
/**
* 保存数据(插入或更新)
*
* @param entity
*/
@Transactional(readOnly = false)
public void save(T entity) {
int result=0;
if (entity.getIsNewRecord()) {
entity.preInsert();
result=dao.insert(entity);
} else {
entity.preUpdate();
result=dao.update(entity);
}
}
/**
* 删除数据
*
* @param entity
*/
@Transactional(readOnly = false)
public void delete(T entity) {
dao.delete(entity);
}
/**
* 删除数据(逻辑删除,更新del_flag字段为1,在表包含字段del_flag时,可以调用此方法,将数据隐藏)
* @param entity
* @return
*/
@Transactional(readOnly = false)
public void deleteByLogic(T entity) {
dao.deleteByLogic(entity);
}
}
/**
* Copyright &copy; 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package com.jeespring.common.service;
import java.util.List;
import com.jeespring.common.persistence.AbstractEntity;
import com.jeespring.common.utils.StringUtils;
import com.jeespring.modules.sys.entity.Role;
import com.jeespring.modules.sys.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import com.google.common.collect.Lists;
/**
* Service基类
* @author 黄炳桂 516821420@qq.com
* @version 2014-05-16
*/
@Transactional(readOnly = true)
public abstract class AbstractService implements InterfaceService {
/**
* 日志对象
*/
protected Logger logger = LoggerFactory.getLogger(getClass());
/**
* 数据范围过滤
* @param user 当前用户对象,通过“entity.getCurrentUser()”获取
* @param officeAlias 机构表别名,多个用“,”逗号隔开。
* @param userAlias 用户表别名,多个用“,”逗号隔开,传递空,忽略此参数
* @return 标准连接条件对象
*/
public static String dataScopeFilter(User user, String officeAlias, String userAlias) {
StringBuilder sqlString = new StringBuilder();
// 进行权限过滤,多个角色权限范围之间为或者关系。
List<String> dataScope = Lists.newArrayList();
// 超级管理员,跳过权限过滤
if (!user.isAdmin()){
boolean isDataScopeAll = false;
for (Role r : user.getRoleList()){
for (String oa : StringUtils.split(officeAlias, ",")){
if (!dataScope.contains(r.getDataScope()) && StringUtils.isNotBlank(oa)){
if (Role.DATA_SCOPE_ALL.equals(r.getDataScope())){
isDataScopeAll = true;
}
else if (Role.DATA_SCOPE_COMPANY_AND_CHILD.equals(r.getDataScope())){
sqlString.append(" OR " + oa + ".id = '" + user.getCompany().getId() + "'");
sqlString.append(" OR " + oa + ".parent_ids LIKE '" + user.getCompany().getParentIds() + user.getCompany().getId() + ",%'");
}
else if (Role.DATA_SCOPE_COMPANY.equals(r.getDataScope())){
sqlString.append(" OR " + oa + ".id = '" + user.getCompany().getId() + "'");
// 包括本公司下的部门 (type=1:公司;type=2:部门)
sqlString.append(" OR (" + oa + ".parent_id = '" + user.getCompany().getId() + "' AND " + oa + ".type = '2')");
}
else if (Role.DATA_SCOPE_OFFICE_AND_CHILD.equals(r.getDataScope())){
sqlString.append(" OR " + oa + ".id = '" + user.getOffice().getId() + "'");
sqlString.append(" OR " + oa + ".parent_ids LIKE '" + user.getOffice().getParentIds() + user.getOffice().getId() + ",%'");
}
else if (Role.DATA_SCOPE_OFFICE.equals(r.getDataScope())){
sqlString.append(" OR " + oa + ".id = '" + user.getOffice().getId() + "'");
}
else if (Role.DATA_SCOPE_CUSTOM.equals(r.getDataScope())){
sqlString.append(" OR EXISTS (SELECT 1 FROM sys_role_office WHERE role_id = '" + r.getId() + "'");
sqlString.append(" AND office_id = " + oa +".id)");
}
//else if (Role.DATA_SCOPE_SELF.equals(r.getDataScope())){
dataScope.add(r.getDataScope());
}
}
}
// 如果没有全部数据权限,并设置了用户别名,则当前权限为本人;如果未设置别名,当前无权限为已植入权限
if (!isDataScopeAll){
if (StringUtils.isNotBlank(userAlias)){
for (String ua : StringUtils.split(userAlias, ",")){
sqlString.append(" OR " + ua + ".id = '" + user.getId() + "'");
}
}else {
for (String oa : StringUtils.split(officeAlias, ",")){
//sqlString.append(" OR " + oa + ".id = " + user.getOffice().getId());
sqlString.append(" OR " + oa + ".id IS NULL");
}
}
}else{
// 如果包含全部权限,则去掉之前添加的所有条件,并跳出循环。
sqlString = new StringBuilder();
}
}
if (StringUtils.isNotBlank(sqlString.toString())){
return " AND (" + sqlString.substring(4) + ")";
}
return "";
}
/**
* 数据范围过滤(符合业务表字段不同的时候使用,采用exists方法)
* @param entity 当前过滤的实体类
* @param sqlMapKey sqlMap的键值,例如设置“dsf”时,调用方法:${sqlMap.sdf}
* @param officeWheres office表条件,组成:部门表字段=业务表的部门字段
* @param userWheres user表条件,组成:用户表字段=业务表的用户字段
* @example
* dataScopeFilter(user, "dsf", "id=a.office_id", "id=a.create_by");
* dataScopeFilter(entity, "dsf", "code=a.jgdm", "no=a.cjr"); // 适应于业务表关联不同字段时使用,如果关联的不是机构id是code。
*/
public static void dataScopeFilter(AbstractEntity<?> entity, String sqlMapKey, String officeWheres, String userWheres) {
User user = entity.getCurrentUser();
// 如果是超级管理员,则不过滤数据
if (user.isAdmin()) {
return;
}
// 数据范围(1:所有数据;2:所在公司及以下数据;3:所在公司数据;4:所在部门及以下数据;5:所在部门数据;8:仅本人数据;9:按明细设置)
StringBuilder sqlString = new StringBuilder();
// 获取到最大的数据权限范围
String roleId = "";
int dataScopeInteger = 8;
for (Role r : user.getRoleList()){
int ds = Integer.valueOf(r.getDataScope());
if (ds == 9){
roleId = r.getId();
dataScopeInteger = ds;
break;
}else if (ds < dataScopeInteger){
roleId = r.getId();
dataScopeInteger = ds;
}
}
String dataScopeString = String.valueOf(dataScopeInteger);
// 生成部门权限SQL语句
for (String where : StringUtils.split(officeWheres, ",")){
if (Role.DATA_SCOPE_COMPANY_AND_CHILD.equals(dataScopeString)){
// 包括本公司下的部门 (type=1:公司;type=2:部门)
sqlString.append(" AND EXISTS (SELECT 1 FROM SYS_OFFICE");
sqlString.append(" WHERE type='2'");
sqlString.append(" AND (id = '" + user.getCompany().getId() + "'");
sqlString.append(" OR parent_ids LIKE '" + user.getCompany().getParentIds() + user.getCompany().getId() + ",%')");
sqlString.append(" AND " + where +")");
}
else if (Role.DATA_SCOPE_COMPANY.equals(dataScopeString)){
sqlString.append(" AND EXISTS (SELECT 1 FROM SYS_OFFICE");
sqlString.append(" WHERE type='2'");
sqlString.append(" AND id = '" + user.getCompany().getId() + "'");
sqlString.append(" AND " + where +")");
}
else if (Role.DATA_SCOPE_OFFICE_AND_CHILD.equals(dataScopeString)){
sqlString.append(" AND EXISTS (SELECT 1 FROM SYS_OFFICE");
sqlString.append(" WHERE (id = '" + user.getOffice().getId() + "'");
sqlString.append(" OR parent_ids LIKE '" + user.getOffice().getParentIds() + user.getOffice().getId() + ",%')");
sqlString.append(" AND " + where +")");
}
else if (Role.DATA_SCOPE_OFFICE.equals(dataScopeString)){
sqlString.append(" AND EXISTS (SELECT 1 FROM SYS_OFFICE");
sqlString.append(" WHERE id = '" + user.getOffice().getId() + "'");
sqlString.append(" AND " + where +")");
}
else if (Role.DATA_SCOPE_CUSTOM.equals(dataScopeString)){
sqlString.append(" AND EXISTS (SELECT 1 FROM sys_role_office ro123456, sys_office o123456");
sqlString.append(" WHERE ro123456.office_id = o123456.id");
sqlString.append(" AND ro123456.role_id = '" + roleId + "'");
sqlString.append(" AND o123456." + where +")");
}
}
// 生成个人权限SQL语句
for (String where : StringUtils.split(userWheres, ",")){
if (Role.DATA_SCOPE_SELF.equals(dataScopeString)){
sqlString.append(" AND EXISTS (SELECT 1 FROM sys_user");
sqlString.append(" WHERE id='" + user.getId() + "'");
sqlString.append(" AND " + where + ")");
}
}
// 设置到自定义SQL对象
entity.getSqlMap().put(sqlMapKey, sqlString.toString());
}
}
/**
* Copyright &copy; 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package com.jeespring.common.service;
import com.jeespring.common.persistence.Page;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Service基类
*
* @author HuangBingGui
* @version 2014-05-16
*/
public interface ICommonService<T> {
/**
* 获取单条数据
*
* @param id
* @return
*/
T get(String id);
/**
* 获取单条数据
*
* @param entity
* @return
*/
T get(T entity);
/**
* 查询列表数据
*
* @param entity
* @return
*/
List<T> findList(T entity);
/**
* 查询所有
*
* @param entity
* @return
*/
List<T> findAllList(T entity);
/**
* 查询分页数据
*
* @param page 分页对象
* @param entity
* @return
*/
Page<T> findPage(Page<T> page, T entity) ;
/**
* 保存数据(插入或更新)
*
* @param entity
*/
@Transactional(readOnly = false)
void save(T entity) ;
/**
* 删除数据
*
* @param entity
*/
@Transactional(readOnly = false)
void delete(T entity);
}
package com.jeespring.common.service;
import com.jeespring.modules.sys.entity.User;
public interface InterfaceService {
}
/**
* Copyright &copy; 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package com.jeespring.common.service;
/**
* Service层公用的Exception, 从由Spring管理事务的函数中抛出时会触发事务回滚.
* @author 黄炳桂 516821420@qq.com
*/
public class ServiceException extends RuntimeException {
private static final long serialVersionUID = 1L;
public ServiceException(String message) {
super(message);
}
public ServiceException(Throwable cause) {
super(cause);
}
}
/**
* Copyright &copy; 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package com.jeespring.common.service;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
import com.jeespring.common.persistence.TreeDao;
import com.jeespring.common.persistence.TreeEntity;
import com.jeespring.common.utils.Reflections;
import com.jeespring.common.utils.StringUtils;
/**
* Service基类
* @author 黄炳桂 516821420@qq.com
* @version 2014-05-16
*/
@Transactional(readOnly = true)
public abstract class TreeService<D extends TreeDao<T>, T extends TreeEntity<T>> extends AbstractBaseService<D, T> {
@Override
@Transactional(readOnly = false)
public void save(T entity) {
@SuppressWarnings("unchecked")
Class<T> entityClass = Reflections.getClassGenricType(getClass(), 1);
// 如果没有设置父节点,则代表为跟节点,有则获取父节点实体
if (entity.getParent() == null || StringUtils.isBlank(entity.getParentId())
|| "0".equals(entity.getParentId())){
entity.setParent(null);
}else{
entity.setParent(super.get(entity.getParentId()));
}
if (entity.getParent() == null){
T parentEntity = null;
try {
parentEntity = entityClass.getConstructor(String.class).newInstance("0");
} catch (Exception e) {
throw new ServiceException(e);
}
entity.setParent(parentEntity);
entity.getParent().setParentIds(StringUtils.EMPTY);
}
// 获取修改前的parentIds,用于更新子节点的parentIds
String oldParentIds = entity.getParentIds();
// 设置新的父节点串
entity.setParentIds(entity.getParent().getParentIds()+entity.getParent().getId()+",");
// 保存或更新实体
super.save(entity);
// 更新子节点 parentIds
T o = null;
try {
o = entityClass.newInstance();
} catch (Exception e) {
throw new ServiceException(e);
}
o.setParentIds("%,"+entity.getId()+",%");
List<T> list = dao.findByParentIdsLike(o);
for (T e : list){
if (e.getParentIds() != null && oldParentIds != null){
e.setParentIds(e.getParentIds().replace(oldParentIds, entity.getParentIds()));
preUpdateChild(entity, e);
dao.updateParentIds(e);
}
}
}
/**
* 预留接口,用户更新子节前调用
* @param childEntity
*/
protected void preUpdateChild(T entity, T childEntity) {
}
}
/**
* Copyright &copy; 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package com.jeespring.common.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ckfinder.connector.ConnectorServlet;
import com.jeespring.common.config.Global;
import com.jeespring.common.utils.FileUtils;
import com.jeespring.modules.sys.security.SystemAuthorizingRealm.Principal;
import com.jeespring.modules.sys.utils.UserUtils;
/**
* CKFinderConnectorServlet
* @author 黄炳桂 516821420@qq.com
* @version 2014-06-25
*/
@WebServlet(urlPatterns = "/static/ckfinder/core/connector/java/connector.java", initParams = {
@WebInitParam(name = "XMLConfig", value = "classpath:ckfinder.xml"),
@WebInitParam(name = "debug", value = "false"),
@WebInitParam(name = "configuration", value = "com.jeespring.common.web.CKFinderConfig")
}, loadOnStartup = 1)
public class CKFinderConnectorServlet extends ConnectorServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
prepareGetResponse(request, response, false);
super.doGet(request, response);
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
prepareGetResponse(request, response, true);
super.doPost(request, response);
}
private void prepareGetResponse(final HttpServletRequest request,
final HttpServletResponse response, final boolean post) throws ServletException {
Principal principal = UserUtils.getPrincipal();
if (principal == null) {
return;
}
String command = request.getParameter("command");
String type = request.getParameter("type");
// 初始化时,如果startupPath文件夹不存在,则自动创建startupPath文件夹
if ("Init".equals(command)) {
String startupPath = request.getParameter("startupPath");// 当前文件夹可指定为模块名
if (startupPath != null) {
String[] ss = startupPath.split(":");
if (ss.length == 2) {
String realPath = Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL
+ principal + "/" + ss[0] + ss[1];
FileUtils.createDirectory(FileUtils.path(realPath));
}
}
}
// 快捷上传,自动创建当前文件夹,并上传到该路径
else if ("QuickUpload".equals(command) && type != null) {
String currentFolder = request.getParameter("currentFolder");// 当前文件夹可指定为模块名
String realPath = Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL
+ principal + "/" + type + (currentFolder != null ? currentFolder : "");
FileUtils.createDirectory(FileUtils.path(realPath));
}
}
}
package com.jeespring.common.servlet;
import com.jeespring.common.config.Global;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.util.UriUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/**
* 查看CK上传的图片
*
* @author 黄炳桂 516821420@qq.com
* @version 2014-06-25
*/
@WebServlet(urlPatterns = "/userfiles/*")
public class UserfilesDownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private Logger logger = LoggerFactory.getLogger(getClass());
public void fileOutputStream(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String filepath = req.getRequestURI();
int index = filepath.indexOf(Global.USERFILES_BASE_URL);
if (index >= 0) {
filepath = filepath.substring(index + Global.USERFILES_BASE_URL.length());
}
try {
filepath = UriUtils.decode(filepath, "UTF-8");
} catch (UnsupportedEncodingException e1) {
logger.error(String.format("解释文件路径失败,URL地址为%s", filepath), e1);
}
File file = new File(Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL + filepath);
try {
FileCopyUtils.copy(new FileInputStream(file), resp.getOutputStream());
resp.setHeader("Content-Type", "application/octet-stream");
return;
} catch (FileNotFoundException e) {
req.setAttribute("exception", new FileNotFoundException("请求的文件不存在"));
req.getRequestDispatcher("/webapp/WEB-INF/views/error/404.jsp").forward(req, resp);
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
fileOutputStream(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
fileOutputStream(req, resp);
}
}
/**
* Copyright &copy; 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package com.jeespring.common.servlet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
/**
* 生成随机验证码
* @author 黄炳桂 516821420@qq.com
* @version 2014-7-27
*/
@SuppressWarnings("serial")
@WebServlet(urlPatterns = "/servlet/validateCodeServlet")
public class ValidateCodeServlet extends HttpServlet {
public static final String VALIDATE_CODE = "validateCode";
//private int w = 70;
//private int h = 26;
private int w = 80;
private int h = 40;
public ValidateCodeServlet() {
super();
}
public void destroy() {
super.destroy();
}
public static boolean validate(HttpServletRequest request, String validateCode){
String code = (String)request.getSession().getAttribute(VALIDATE_CODE);
return validateCode.toUpperCase().equals(code);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String validateCode = request.getParameter(VALIDATE_CODE); // AJAX验证,成功返回true
if (StringUtils.isNotBlank(validateCode)){
response.getOutputStream().print(validate(request, validateCode)?"true":"false");
}else{
this.doPost(request, response);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
createImage(request,response);
}
private void createImage(HttpServletRequest request,
HttpServletResponse response) throws IOException {
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
/*
* 得到参数高,宽,都为数字时,则使用设置高宽,否则使用默认值
*/
String width = request.getParameter("width");
String height = request.getParameter("height");
if (StringUtils.isNumeric(width) && StringUtils.isNumeric(height)) {
w = NumberUtils.toInt(width);
h = NumberUtils.toInt(height);
}
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
/*
* 生成背景
*/
createBackground(g);
/*
* 生成字符
*/
String s = createCharacter(g);
createLine(g);
request.getSession().setAttribute(VALIDATE_CODE, s);
g.dispose();
OutputStream out = response.getOutputStream();
ImageIO.write(image, "JPEG", out);
out.close();
}
private Color getRandColor(int fc,int bc) {
int f = fc;
int b = bc;
Random random=new Random();
if(f>255) {
f=255;
}
if(b>255) {
b=255;
}
return new Color(f+random.nextInt(b-f),f+random.nextInt(b-f),f+random.nextInt(b-f));
}
private void createBackground(Graphics g) {
// 填充背景
//g.setColor(getRandColor(220,250));
g.setColor(new Color(255,255,255));
g.fillRect(0, 0, w, h);
// 加入干扰线条
//干扰线条先注释
for (int i = 0; i < 20; i++) {
/*g.setColor(getRandColor(40,150));
Random random = new Random();
int x = random.nextInt(w);
int y = random.nextInt(h);
int x1 = random.nextInt(w);
int y1 = random.nextInt(h);
g.drawLine(x, y, x1, y1);*/
}
}
private void createLine(Graphics g) {
// 加入干扰线条
//干扰线条先注释
Random randomTimes = new Random();
int times=randomTimes.nextInt(25);
for (int i = 0; i <times; i++) {
//g.setColor(getRandColor(40,150));
g.setColor(new Color(255,255,255));
Random random = new Random();
int x = random.nextInt(w);
int y = random.nextInt(h);
int x1 = random.nextInt(w);
int y1 = random.nextInt(h);
g.drawLine(x, y, x1, y1);
}
}
private String createCharacter(Graphics g) {
/*char[] codeSeq = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J',
'K', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9' };*/
char[] codeSeq = {'0','1', '2', '3', '4', '5', '6', '7', '8', '9' };
//String[] fontTypes = {"Arial","Arial Black","AvantGarde Bk BT","Calibri"};
String[] fontTypes = {"Ravie","Antique Olive Compact","Fixedsys","Wide Latin","Gill Sans Ultra Bold"};
Random random = new Random();
StringBuilder s = new StringBuilder();
for (int i = 0; i < 4; i++) {
String r = String.valueOf(codeSeq[random.nextInt(codeSeq.length)]);//random.nextInt(10));
//g.setColor(new Color(50 + random.nextInt(100), 50 + random.nextInt(100), 50 + random.nextInt(100)));
g.setColor(new Color(70, 70, 70));
//g.setFont(new Font(fontTypes[random.nextInt(fontTypes.length)],Font.BOLD,26));
g.setFont(new Font("Arial",Font.ITALIC,18));
//g.drawString(r, 15 * i + 5, 19 + random.nextInt(8));
g.drawString(r, 20 * i + 4, 26 );
s.append(r);
}
return s.toString();
}
}
package com.jeespring.common.sms;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import com.jeespring.common.security.Digests;
/*
功能: 企信通PHP HTTP接口 发送短信
修改日期: 2014-03-19
说明: http://api.cnsms.cn/?ac=send&uid=用户账号&pwd=MD5位32密码&mobile=号码&content=内容
状态:
100 发送成功
101 验证失败
102 短信不足
103 操作失败
104 非法字符
105 内容过多
106 号码过多
107 频率过快
108 号码内容空
109 账号冻结
110 禁止频繁单条发送
111 系统暂定发送
112 号码不正确
120 系统升级
*/
public class SMSUtils {
//发送短信,uid,pwd,参数值请向企信通申请, tel:发送的手机号, content:发送的内容
public static String send(String uid, String pwd, String tel, String content) throws IOException {
try{
// 创建StringBuffer对象用来操作字符串
StringBuffer sb = new StringBuffer("http://api.cnsms.cn/?");
// 向StringBuffer追加用户名
sb.append("ac=send&uid="+uid);//在此申请企信通uid,并进行配置用户名
// 向StringBuffer追加密码(密码采用MD5 32位 小写)
sb.append("&encode=utf8");
// 向StringBuffer追加密码(密码采用MD5 32位 小写)
sb.append("&pwd="+Digests.string2MD5(pwd));//在此申请企信通uid,并进行配置密码
// 向StringBuffer追加手机号码
sb.append("&mobile="+tel);
// 向StringBuffer追加消息内容转URL标准码
sb.append("&content="+URLEncoder.encode(content,"utf8"));
// 创建url对象
URL url = new URL(sb.toString());
// 打开url连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置url请求方式 ‘get’ 或者 ‘post’
connection.setRequestMethod("POST");
// 发送
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
// 返回发送结果
String inputline = in.readLine();
return inputline;
}catch (Exception e){
return "";
}
}
public static String sendPass(String tel, String password) throws IOException {
//发送内容
String content = "您的新密码是:"+password+",请登录系统,重新设置密码。";
// 创建StringBuffer对象用来操作字符串
StringBuffer sb = new StringBuffer("http://api.cnsms.cn/?");
// 向StringBuffer追加用户名
sb.append("ac=send&uid=");//设置用户名
// 向StringBuffer追加密码(密码采用MD5 32位 小写)
sb.append("&encode=utf8");
// 向StringBuffer追加密码(密码采用MD5 32位 小写)
sb.append("&pwd=");//设置密码
// 向StringBuffer追加手机号码
sb.append("&mobile="+tel);
// 向StringBuffer追加消息内容转URL标准码
sb.append("&content="+URLEncoder.encode(content,"utf8"));
// 创建url对象
URL url = new URL(sb.toString());
// 打开url连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置url请求方式 ‘get’ 或者 ‘post’
connection.setRequestMethod("POST");
// 发送
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
// 返回发送结果
String inputline = in.readLine();
return inputline;
}
}
\ No newline at end of file
package com.jeespring.common.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 JeeSpring
*/
@Component
public final class SpringUtils implements BeanFactoryPostProcessor
{
/** Spring应用上下文环境 */
private static ConfigurableListableBeanFactory beanFactory;
@Override
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.jeespring.common.swagger;
import com.google.common.base.Predicates;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Swagger {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) //这里采用包含注解的方式来确定要显示的接口
//.apis(RequestHandlerSelectors.basePackage("com.jeespring.modules.*")) //这里采用包扫描的方式来确定要显示的接口
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger2构建RESTful APIs")
.description("更多JeeSpring相关文章")
.termsOfServiceUrl("http://www.jeespring.com/")
.contact("contact")
.version("1.0")
.build();
}
/*注解
@ApiOperation(value="创建用户", notes="根据User对象创建用户")
@ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
@ApiOperation("生成代码")
@ApiImplicitParams({
@ApiImplicitParam(name = "moduleName", value = "模块名称", required = true, dataType = "String"),
@ApiImplicitParam(name = "bizChName", value = "业务名称", required = true, dataType = "String"),
@ApiImplicitParam(name = "bizEnName", value = "业务英文名称", required = true, dataType = "String"),
@ApiImplicitParam(name = "path", value = "项目生成类路径", required = true, dataType = "String")
})
*/
}
\ No newline at end of file
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment