项目初始导入

This commit is contained in:
dell
2017-12-29 16:18:40 +08:00
commit 0788f42ae7
3221 changed files with 500217 additions and 0 deletions

View File

@@ -0,0 +1,8 @@
package com.nis.web.service;
import org.springframework.stereotype.Service;
@Service
public class ArchiveServcie extends BaseService{
}

View File

@@ -0,0 +1,44 @@
package com.nis.web.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.google.common.collect.Lists;
import com.nis.domain.SysArea;
import com.nis.util.StringUtil;
import com.nis.web.dao.SysAreaDao;
import com.nis.web.security.UserUtils;
@Service
public class AreaService extends TreeService<SysAreaDao, SysArea> {
@Autowired
private SysAreaDao areaDao;
public List<SysArea> findAll() {
return UserUtils.getAreaList();
}
public List<SysArea> findAllAreaList(SysArea area) {
if (!StringUtil.isEmpty(area.getId())) {
area.setParentIds(area.getParentIds()+area.getId()+","+"%");
} else {
//area.setParentIds(area.getParentIds()+"%");
return Lists.newArrayList();
}
return areaDao.findByParentIdsLike(area);
}
public void saveOrUpdate(SysArea sysArea) {
if (StringUtil.isEmpty(sysArea.getId())) {
sysArea.setDelFlag(1);
}
this.save(sysArea);
UserUtils.removeCache(UserUtils.CACHE_AREA_LIST);
}
}

View File

@@ -0,0 +1,153 @@
package com.nis.web.service;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
import com.nis.domain.SysRole;
import com.nis.domain.SysUser;
import com.nis.util.StringUtils;
/**
* Service基类
* @author ThinkGem
* @version 2014-05-16
*/
public abstract class BaseService {
/**
* 日志对象
*/
protected Logger logger = LoggerFactory.getLogger(getClass());
/**
* 数据范围过滤
* @param user 当前用户对象通过“entity.getCurrentUser()”获取
* @param officeAlias 机构表别名,多个用“,”逗号隔开。
* @param userAlias 用户表别名,多个用“,”逗号隔开,传递空,忽略此参数
* @return 标准连接条件对象
*/
public static String dataScopeFilter(SysUser user, String officeAlias, String userAlias) {
StringBuilder sqlString = new StringBuilder();
// 进行权限过滤,多个角色权限范围之间为或者关系。
List<Integer> dataScope = Lists.newArrayList();
if (StringUtils.isBlank(user.getLoginId())){
return "";
}
// 超级管理员,跳过权限过滤
if (user.isAdmin()){
boolean isDataScopeAll = isContainsDataScopeAll(user.getUserRoleList());
for (SysRole r : user.getUserRoleList()) {
for (String oa : StringUtils.split(officeAlias, ",")){
if (!dataScope.contains(r.getDataScope()) && StringUtils.isNotBlank(oa)){
sqlString.append(createScopeSql(r.getDataScope(),oa,user));
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 "";
}
/**
* 测试数据是否包含全集
* @return
*/
private static boolean isContainsDataScopeAll(List<SysRole> roleList) {
boolean isDataScopeAll = false;
for(SysRole role : roleList) {
if(SysRole.DATA_SCOPE_ALL.equals(role.getDataScope())){
isDataScopeAll = true;
break;
}
}
return isDataScopeAll;
}
/**
* 过滤机构信息
* @param dataScope 数据范围1所有数据2所在公司及以下数据3所在公司数据4所在部门及以下数据5所在部门数据6所在单位及以下数据7所在单位数据
* @return
*/
private static String createScopeSql(int dataScope,String officeAlias,SysUser user) {
StringBuilder scopeSql = new StringBuilder(1024);
if (SysRole.DATA_SCOPE_COMPANY_AND_CHILD.equals(dataScope)){
scopeSql.append(" OR " + officeAlias + ".id = " + user.getCompany().getId());
scopeSql.append(" OR " + officeAlias + ".parent_ids LIKE '" + user.getCompany().getParentIds() + user.getCompany().getId() + ",%'");
}
else if (SysRole.DATA_SCOPE_COMPANY.equals(dataScope)){
scopeSql.append(" OR " + officeAlias + ".id = " + user.getCompany().getId());
// 包括本公司下的部门 type=1:公司type=2单位 3.部门)
scopeSql.append(" OR (" + officeAlias + ".parent_id = '" + user.getCompany().getId() + "' AND " + officeAlias + ".type>1)");
}
else if (SysRole.DATA_SCOPE_OFFICE_AND_CHILD.equals(dataScope)){
scopeSql.append(" OR " + officeAlias + ".id = " + user.getOffice().getId());
scopeSql.append(" OR " + officeAlias + ".parent_ids LIKE '" + user.getOffice().getParentIds() + user.getOffice().getId() + ",%'");
}
else if (SysRole.DATA_SCOPE_OFFICE.equals(dataScope)){
scopeSql.append(" OR " + officeAlias + ".id = " + user.getOffice().getId());
}
else if (SysRole.DATA_SCOPE_ENTITY_AND_CHILD.equals(dataScope)){
scopeSql.append(" OR " + officeAlias + ".id = " + user.getEntity().getId());
scopeSql.append(" OR " + officeAlias + ".parent_ids LIKE '" + user.getEntity().getParentIds() + user.getEntity().getId() + ",%'");
} else if (SysRole.DATA_SCOPE_ENTITY.equals(dataScope)){
scopeSql.append(" OR " + officeAlias + ".id = " + user.getEntity().getId());
// 包括本公司下的部门 type=1:公司type=2单位 3.部门)
scopeSql.append(" OR (" + officeAlias + ".parent_id = '" + user.getEntity().getId() + "' AND " + officeAlias + ".type>1)");
}
return scopeSql.toString();
}
}

View File

@@ -0,0 +1,6 @@
package com.nis.web.service;
public interface CommonService {
}

View File

@@ -0,0 +1,180 @@
/**
* Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.nis.web.service;
import java.lang.reflect.Field;
import java.util.List;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.nis.domain.BaseEntity;
import com.nis.domain.Page;
import com.nis.util.Constants;
import com.nis.web.dao.CrudDao;
/**
* Service基类
* @author ThinkGem
* @version 2014-05-16
*/
public abstract class CrudService<D extends CrudDao<T>, T extends BaseEntity<T>> extends BaseService {
/**
* 持久层对象
*/
@Autowired
protected D dao;
/**
* 获取单条数据
* @param id
* @return
*/
public T get(Long id) {
return dao.get(id);
}
/**
* 获取单条数据
* @param entity
* @return
*/
public T get(T entity) {
return dao.get(entity);
}
/**
* 查询列表数据
* @param entity
* @return
*/
public List<T> findList(T entity) {
return dao.findList(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
*/
public void save(T entity) {
if (entity.getIsNewRecord()){
dao.insert(entity);
}else{
dao.update(entity);
}
}
/**
* 删除数据
* @param entity
*/
public void delete(T entity) {
dao.delete(entity);
}
/**
*
* saveBatch(批量全部保存数据)
* (这里描述这个方法适用条件 可选)
* @param data 数据集合
* @param mClass 传入的dao.xml里的mapper
* @author wx
* @since 1.0.0
*/
@SuppressWarnings("unchecked")
public void saveBatch(List<T> data,@SuppressWarnings("rawtypes")Class mClass) {
SqlSessionFactory sqlSessionFactory=SpringContextHolder.getBean(SqlSessionFactory.class);
SqlSession batchSqlSession = null;
try{
batchSqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
for(int index = 0; index < data.size();index++){
T t = data.get(index);
((CrudDao<T>) batchSqlSession.getMapper(mClass)).insert(t);
}
batchSqlSession.commit();
// }catch (Exception e){
// batchSqlSession.rollback();
// throw e;
}finally {
if(batchSqlSession != null){
batchSqlSession.close();
}
}
}
/**
*
* updateBatch(批量更新全部数据)
* (这里描述这个方法适用条件 可选)
* @param data 数据集合
* @param mClass 传入的dao.xml里的mapper
* @author wx
* @since 1.0.0
*/
@SuppressWarnings("unchecked")
public void updateBatch(List<T> data,@SuppressWarnings("rawtypes") Class mClass) {
SqlSessionFactory sqlSessionFactory=SpringContextHolder.getBean(SqlSessionFactory.class);
SqlSession batchSqlSession = null;
try{
batchSqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
for(int index = 0; index < data.size();index++){
T t = data.get(index);
((CrudDao<T>) batchSqlSession.getMapper(mClass)).update(t);
}
batchSqlSession.commit();
// }catch (Exception e){
// batchSqlSession.rollback();
// throw e;
}finally {
if(batchSqlSession != null){
batchSqlSession.close();
}
}
}
/**
*
* deleteBatch(批量删除全部数据)
* (这里描述这个方法适用条件 可选)
* @param data 数据集合
* @param mClass 传入的dao.xml里的mapper
* @author wx
* @since 1.0.0
*/
@SuppressWarnings("unchecked")
public void deleteBatch(List<T> data,@SuppressWarnings("rawtypes") Class mClass) {
SqlSessionFactory sqlSessionFactory=SpringContextHolder.getBean(SqlSessionFactory.class);
SqlSession batchSqlSession = null;
try{
batchSqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
for(int index = 0; index < data.size();index++){
T t = data.get(index);
((CrudDao<T>) batchSqlSession.getMapper(mClass)).delete(t);
}
batchSqlSession.commit();
// }catch (Exception e){
// batchSqlSession.rollback();
// throw e;
}finally {
if(batchSqlSession != null){
batchSqlSession.close();
}
}
}
}

View File

@@ -0,0 +1,108 @@
package com.nis.web.service;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.nis.domain.Page;
import com.nis.domain.SysDataDictionaryItem;
import com.nis.domain.SysDataDictionaryName;
import com.nis.util.DateUtil;
import com.nis.util.StringUtil;
import com.nis.web.dao.SysDictDao;
import com.nis.web.security.UserUtils;
@Service
public class DictService extends BaseService {
/**@Resource**/
@Autowired
private SysDictDao dictDao;
public Page<SysDataDictionaryName> findDictList(Page<SysDataDictionaryName> page, SysDataDictionaryName sysDictName) {
// 设置分页参数
sysDictName.setPage(page);
// 执行分页查询
page.setList(dictDao.findDictList(sysDictName));
return page;
}
public void saveOrUpdate(SysDataDictionaryName sysDictName) {
if(StringUtil.isEmpty(sysDictName.getId())) {//新增
sysDictName.setCreateTime(new Date());
sysDictName.setModifyTime(new Date());
sysDictName.setStatus(1);
dictDao.insertDictName(sysDictName);
List<SysDataDictionaryItem> dictItemList = sysDictName.getDictItemList();
if(!StringUtil.isEmpty(dictItemList) && dictItemList.size()>0) {
for (SysDataDictionaryItem dictItem : dictItemList) {
dictItem.setDictionaryId(sysDictName.getId().intValue());
dictDao.insertDictItem(dictItem);
}
}
}else {//修改
//累加修改记录
String newRevision = "用户"+UserUtils.getUser().getName()+",在"+DateUtil.getCurrentDate(DateUtil.YYYY_MM_DD_HH24_MM_SS)+"修改!";
StringBuilder revisionBuilder = new StringBuilder(newRevision);
String oldRevision = sysDictName.getRevision();
if(!StringUtil.isBlank(oldRevision)){
if(oldRevision.split("\\|").length<10){
revisionBuilder.append("|").append(oldRevision);
}else {
revisionBuilder.append("|").append(oldRevision.substring(0,oldRevision.lastIndexOf("|")));
}
}
sysDictName.setRevision(revisionBuilder.toString());
sysDictName.setModifyTime(new Date());
sysDictName.setStatus(1);
dictDao.updateDictName(sysDictName);
dictDao.deleteDictItem(sysDictName.getId().intValue());//删除所有词条项信息
List<SysDataDictionaryItem> dictItemList = sysDictName.getDictItemList();
if(!StringUtil.isEmpty(dictItemList) && dictItemList.size()>0) {
for (SysDataDictionaryItem dictItem : dictItemList) {
dictItem.setDictionaryId(sysDictName.getId().intValue());
dictDao.insertDictItem(dictItem);
}
}
}
}
public void deleteDict(Integer dictId) {
//删除词典项
dictDao.deleteDictItem(dictId);
//删除词典标识
dictDao.deleteDictName(dictId);
}
public SysDataDictionaryName getDictByIdWithRelation(Integer id) {
return dictDao.getDictById(1,id);
}
}

View File

@@ -0,0 +1,628 @@
package com.nis.web.service;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.mapping.ResultMapping;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;
import com.nis.domain.Page;
import com.nis.util.Configurations;
import com.nis.util.Constants;
import com.nis.util.HiveDataSource;
import com.nis.util.HiveJDBC;
import com.nis.util.StringUtil;
import com.nis.util.redis.SaveRedisThread;
public class HiveSqlService {
private final static Logger logger = Logger.getLogger(HiveJDBC.class);
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static ResultSet getResultSet(Page page, Object bean, String tableName,
Map<String, Map<String, String>> col2col, String orderBy, String searchActiveSys) throws Exception {
tableName = tableName.toLowerCase();
tableName = Configurations.getStringProperty(tableName, "t_" + tableName).trim();
String showColmun = getFiledsSql(bean.getClass().getSimpleName(), page.getFields());
StringBuffer sql = new StringBuffer();
Map<String, String> filedAndColumnMap = getFiledAndColumnMap(bean.getClass());
if (null == showColmun || showColmun.equals("")) {
for (String key : filedAndColumnMap.keySet()) {
if (!filedAndColumnMap.get(key).toLowerCase().equals("id")) {
sql.append(filedAndColumnMap.get(key) + ",");
}
}
} else {
sql.append(showColmun);
}
String sqlTrim = sql.toString().trim();
if (sqlTrim.endsWith(",")) {
sqlTrim = sqlTrim.substring(0, sqlTrim.length() - 1);
}
sql.setLength(0);
sql.append(" select " + sqlTrim + " from " + tableName + " t where 1=1 ");
if (bean != null) {
Class<?> clazz = bean.getClass();
for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
// 获取所有的字段包括public,private,protected,private
// Field[] fields = bean.getClass().getDeclaredFields();
Field[] fields = clazz.getDeclaredFields();
Long foundTimePartStart = null;
Long foundTimePartEnd = null;
for (int i = 0; i < fields.length; i++) {
Field f = fields[i];
String key = f.getName();// 获取字段名
if (f.getType().getName().equals("java.lang.String") && key.startsWith("search")) {
Object value = getFieldValue(bean, key);
if (value != null) {
setFieldValue(bean, key, value.toString().trim());
if (key.endsWith("Time")) {// 日期开始或结束的字段
if (col2col.containsKey(key)) {
value = sdf.parse(value.toString().trim()).getTime() / 1000;
if (key.toLowerCase().equals("searchfoundstarttime")) {
foundTimePartStart = Long.parseLong(value.toString()) / 3600;
}
if (key.toLowerCase().equals("searchfoundendtime")) {
foundTimePartEnd = Long.parseLong(value.toString()) / 3600;
}
if (col2col.get(key).get("start") != null) {
// sql.append(" and " +
// filedAndColumnMap.get(col2col.get(key).get("start"))
// + ">=to_date('" +
// value.toString().trim()
// + "','yyyy-mm-dd HH24:mi:ss')");
sql.append(" and " + filedAndColumnMap.get(col2col.get(key).get("start")) + ">="
+ value + "L");
} else {
// sql.append(" and " +
// filedAndColumnMap.get(col2col.get(key).get("end"))
// + "<=to_date('" +
// value.toString().trim()
// + "','yyyy-mm-dd HH24:mi:ss')");
sql.append(" and " + filedAndColumnMap.get(col2col.get(key).get("end")) + "<"
+ value + "L");
}
}
} else {
if (key.toLowerCase().startsWith("search")) {
key = key.replace("search", "");
key = key.substring(0, 1).toLowerCase() + key.substring(1);
}
if (!value.toString().trim().equals("") && filedAndColumnMap.containsKey(key)
&& (key.toLowerCase().equals("cfgid")
|| key.toLowerCase().equals("entranceid"))) {
sql.append(
" and " + filedAndColumnMap.get(key) + "=" + value.toString().trim() + "L");
} else if (!value.toString().trim().equals("") && filedAndColumnMap.containsKey(key)
&& (key.toLowerCase().equals("protocol") || key.toLowerCase().equals("serverip")
|| key.toLowerCase().equals("clientip")
|| key.toLowerCase().equals("url")
|| key.toLowerCase().equals("mailfrom")
|| key.toLowerCase().equals("mailto")
|| key.toLowerCase().equals("encryptmode")
|| key.toLowerCase().equals("exprotocol")
|| key.toLowerCase().equals("cljip"))) {
sql.append(" and " + filedAndColumnMap.get(key) + "='" + value.toString().trim()
+ "'");
} else if (!value.toString().trim().equals("") && filedAndColumnMap.containsKey(key)
&& key.toLowerCase().equals("servicetype")) {
sql.append(" and " + filedAndColumnMap.get(key) + "=" + value.toString().trim());
}
}
}
}
}
//if (null != searchActiveSys && !searchActiveSys.equals(Constants.ACTIVESYS_A)) {// B版数据库才有found_time_partition字段,A版毛衣found_time_partition分区字段
if (null != searchActiveSys){//为A版日志库添加分区字段
if (null != foundTimePartStart) {
sql.append(" and found_time_partition>=" + foundTimePartStart + "L");
}
if (null != foundTimePartEnd) {
sql.append(" and found_time_partition<" + foundTimePartEnd + "L");
}
}
}
}
Integer startNum = (page.getPageNo() - 1) * page.getPageSize() + 1;
Integer endNum = startNum - 1 + page.getPageSize();
// sql.append(" order by " + orderBy + " limit 10000) t1) t2 where
// row_Num between " + startNum + " and " + endNum);
sql.append(" limit " + Constants.EVERY_GETHIVEDATANUM);
logger.info("获取数据中心日志sql===================" + sql);
// ResultSet query = HiveJDBC.query(sql.toString());
ResultSet query = HiveDataSource.query(sql.toString(), searchActiveSys);
logger.info("获取数据中心日志成功");
return query;
}
public static Long getHivePageCount(Object bean, String countKey, String tableName,
Map<String, Map<String, String>> col2col, String searchActiveSys) throws Exception {
tableName = tableName.toLowerCase();
tableName = Configurations.getStringProperty(tableName, "t_" + tableName).trim();
StringBuffer countSql = new StringBuffer();
Map<String, String> filedAndColumnMap = getFiledAndColumnMap(bean.getClass());
countSql.append("select count(1) from " + tableName + " where 1=1 ");
if (bean != null) {
Class<?> clazz = bean.getClass();
for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
// 获取所有的字段包括public,private,protected,private
// Field[] fields = bean.getClass().getDeclaredFields();
Field[] fields = clazz.getDeclaredFields();
Long foundTimePartStart = null;
Long foundTimePartEnd = null;
for (int i = 0; i < fields.length; i++) {
Field f = fields[i];
String key = f.getName();// 获取字段名
if (f.getType().getName().equals("java.lang.String") && key.startsWith("search")) {
Object value = getFieldValue(bean, key);
if (value != null) {
setFieldValue(bean, key, value.toString().trim());
if (key.endsWith("Time")) {// 日期开始或结束的字段
if (col2col.containsKey(key)) {
value = sdf.parse(value.toString().trim()).getTime() / 1000;
if (key.toLowerCase().equals("searchfoundstarttime")) {
foundTimePartStart = Long.parseLong(value.toString()) / 3600;
}
if (key.toLowerCase().equals("searchfoundendtime")) {
foundTimePartEnd = Long.parseLong(value.toString()) / 3600;
}
if (col2col.get(key).get("start") != null) {
countSql.append(" and " + filedAndColumnMap.get(col2col.get(key).get("start"))
+ ">=" + value + "L");
} else {
countSql.append(" and " + filedAndColumnMap.get(col2col.get(key).get("end"))
+ "<" + value + "L");
}
}
} else {
if (key.toLowerCase().startsWith("search")) {
key = key.replace("search", "");
key = key.substring(0, 1).toLowerCase() + key.substring(1);
}
if (!value.toString().trim().equals("") && filedAndColumnMap.containsKey(key)
&& (key.toLowerCase().equals("cfgid")
|| key.toLowerCase().equals("entranceid"))) {
countSql.append(
" and " + filedAndColumnMap.get(key) + "=" + value.toString().trim() + "L");
} else if (!value.toString().trim().equals("") && filedAndColumnMap.containsKey(key)
&& (key.toLowerCase().equals("protocol") || key.toLowerCase().equals("serverip")
|| key.toLowerCase().equals("clientip")
|| key.toLowerCase().equals("url")
|| key.toLowerCase().equals("mailfrom")
|| key.toLowerCase().equals("mailto")
|| key.toLowerCase().equals("encryptmode")
|| key.toLowerCase().equals("exprotocol")
|| key.toLowerCase().equals("cljip"))) {
countSql.append(" and " + filedAndColumnMap.get(key) + "='"
+ value.toString().trim() + "'");
} else if (!value.toString().trim().equals("") && filedAndColumnMap.containsKey(key)
&& key.toLowerCase().equals("servicetype")) {
countSql.append(
" and " + filedAndColumnMap.get(key) + "=" + value.toString().trim());
}
}
}
}
}
//if (null != searchActiveSys && !searchActiveSys.equals(Constants.ACTIVESYS_A)) {// B版数据库才有found_time_partition字段,A版毛衣found_time_partition分区字段
if (null != searchActiveSys){
if (null != foundTimePartStart) {
countSql.append(" and found_time_partition>=" + foundTimePartStart + "L");
}
if (null != foundTimePartEnd) {
countSql.append(" and found_time_partition<" + foundTimePartEnd + "L");
}
}
}
}
logger.info("获取数据中心日志总条数sql==================" + countSql.toString());
// ResultSet countRs = HiveJDBC.query(countSql.toString());
ResultSet countRs = HiveDataSource.query(countSql.toString(), searchActiveSys);
String countStr = null;
while (countRs.next()) {
countStr = countRs.getObject(1).toString();
break;
}
if (countStr == null || countStr.equals("")) {
logger.info("获取数据中心日志总条数成功总共===================0条配置");
return 0l;
}
Long count = Long.valueOf(countStr);
logger.info("获取数据中心日志总条数成功总共===================" + count + "条配置");
// HiveJDBC.closeConn();
if (Constants.IS_OPEN_REDIS && Constants.DATACENTER_OPEN_REDIS) {
new SaveRedisThread(countKey, count, Constants.HIVE_EXPIRE).start();
}
return count;
}
public static ResultSet getResultSet2(Page page, Object bean, String tableName,
Map<String, Map<String, String>> col2col, String orderBy, String searchActiveSys) throws Exception {
tableName = tableName.toLowerCase();
tableName = Configurations.getStringProperty(tableName, "t_" + tableName).trim();
String showColmun = getFiledsSql(bean.getClass().getSimpleName(), page.getFields());
StringBuffer sql = new StringBuffer();
Map<String, String> filedAndColumnMap = getFiledAndColumnMap(bean.getClass());
if (null == showColmun || showColmun.equals("")) {
for (String key : filedAndColumnMap.keySet()) {
if (!filedAndColumnMap.get(key).toLowerCase().equals("id")) {
sql.append(filedAndColumnMap.get(key) + ",");
}
}
} else {
sql.append(showColmun);
}
String sqlTrim = sql.toString().trim();
if (sqlTrim.endsWith(",")) {
sqlTrim = sqlTrim.substring(0, sqlTrim.length() - 1);
}
sql.setLength(0);
sql.append("select " + sqlTrim + " from(select " + sqlTrim + ",row_Num from(select " + sqlTrim
+ ",row_number() over() as row_Num from " + tableName + " t where 1=1 ");
if (bean != null) {
Class<?> clazz = bean.getClass();
for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
// 获取所有的字段包括public,private,protected,private
// Field[] fields = bean.getClass().getDeclaredFields();
Field[] fields = clazz.getDeclaredFields();
Long foundTimePartStart = null;
Long foundTimePartEnd = null;
for (int i = 0; i < fields.length; i++) {
Field f = fields[i];
String key = f.getName();// 获取字段名
if (f.getType().getName().equals("java.lang.String") && key.startsWith("search")) {
Object value = getFieldValue(bean, key);
if (value != null) {
setFieldValue(bean, key, value.toString().trim());
if (key.endsWith("Time")) {// 日期开始或结束的字段
if (col2col.containsKey(key)) {
value = sdf.parse(value.toString().trim()).getTime() / 1000;
if (key.toLowerCase().equals("searchfoundstarttime")) {
foundTimePartStart = Long.parseLong(value.toString()) / 3600;
}
if (key.toLowerCase().equals("searchfoundendtime")) {
foundTimePartEnd = Long.parseLong(value.toString()) / 3600;
}
if (col2col.get(key).get("start") != null) {
// sql.append(" and " +
// filedAndColumnMap.get(col2col.get(key).get("start"))
// + ">=to_date('" +
// value.toString().trim()
// + "','yyyy-mm-dd HH24:mi:ss')");
sql.append(" and " + filedAndColumnMap.get(col2col.get(key).get("start")) + ">="
+ value + "L");
} else {
// sql.append(" and " +
// filedAndColumnMap.get(col2col.get(key).get("end"))
// + "<=to_date('" +
// value.toString().trim()
// + "','yyyy-mm-dd HH24:mi:ss')");
sql.append(" and " + filedAndColumnMap.get(col2col.get(key).get("end")) + "<"
+ value + "L");
}
}
} else {
if (key.toLowerCase().startsWith("search")) {
key = key.replace("search", "");
key = key.substring(0, 1).toLowerCase() + key.substring(1);
}
if (!value.toString().trim().equals("") && filedAndColumnMap.containsKey(key)
&& (key.toLowerCase().equals("cfgid")
|| key.toLowerCase().equals("entranceid"))) {
sql.append(
" and " + filedAndColumnMap.get(key) + "=" + value.toString().trim() + "L");
} else if (!value.toString().trim().equals("") && filedAndColumnMap.containsKey(key)
&& (key.toLowerCase().equals("protocol") || key.toLowerCase().equals("serverip")
|| key.toLowerCase().equals("clientip")
|| key.toLowerCase().equals("cljip"))) {
sql.append(" and " + filedAndColumnMap.get(key) + "='" + value.toString().trim()
+ "'");
} else if (!value.toString().trim().equals("") && filedAndColumnMap.containsKey(key)
&& key.toLowerCase().equals("servicetype")) {
sql.append(" and " + filedAndColumnMap.get(key) + "=" + value.toString().trim());
}
}
}
}
}
if (null != searchActiveSys && !searchActiveSys.equals(Constants.ACTIVESYS_A)) {// B版数据库才有found_time_partition字段,A版毛衣found_time_partition分区字段
if (null != foundTimePartStart) {
sql.append(" and found_time_partition>=" + foundTimePartStart + "L");
}
if (null != foundTimePartEnd) {
sql.append(" and found_time_partition<" + foundTimePartEnd + "L");
}
}
}
}
Integer startNum = (page.getPageNo() - 1) * page.getPageSize() + 1;
Integer endNum = startNum - 1 + page.getPageSize();
sql.append(
" order by " + orderBy + " limit 10000) t1) t2 where row_Num between " + startNum + " and " + endNum);
logger.info("获取数据中心日志sql===================" + sql);
ResultSet query = HiveJDBC.query(sql.toString(), searchActiveSys);
logger.info("获取数据中心日志成功");
return query;
}
public static Long getHivePageCount2(Object bean, String tableName, Map<String, Map<String, String>> col2col,
String searchActiveSys) throws Exception {
tableName = tableName.toLowerCase();
tableName = Configurations.getStringProperty(tableName, "t_" + tableName).trim();
StringBuffer countSql = new StringBuffer();
Map<String, String> filedAndColumnMap = getFiledAndColumnMap(bean.getClass());
countSql.append("select count(1) from " + tableName + " where 1=1 ");
if (bean != null) {
Class<?> clazz = bean.getClass();
for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
// 获取所有的字段包括public,private,protected,private
// Field[] fields = bean.getClass().getDeclaredFields();
Field[] fields = clazz.getDeclaredFields();
Long foundTimePartStart = null;
Long foundTimePartEnd = null;
for (int i = 0; i < fields.length; i++) {
Field f = fields[i];
String key = f.getName();// 获取字段名
if (f.getType().getName().equals("java.lang.String") && key.startsWith("search")) {
Object value = getFieldValue(bean, key);
if (value != null) {
setFieldValue(bean, key, value.toString().trim());
if (key.endsWith("Time")) {// 日期开始或结束的字段
if (col2col.containsKey(key)) {
value = sdf.parse(value.toString().trim()).getTime() / 1000;
if (key.toLowerCase().equals("searchfoundstarttime")) {
foundTimePartStart = Long.parseLong(value.toString()) / 3600;
}
if (key.toLowerCase().equals("searchfoundendtime")) {
foundTimePartEnd = Long.parseLong(value.toString()) / 3600;
}
if (col2col.get(key).get("start") != null) {
countSql.append(" and " + filedAndColumnMap.get(col2col.get(key).get("start"))
+ ">=" + value + "L");
} else {
countSql.append(" and " + filedAndColumnMap.get(col2col.get(key).get("end"))
+ "<" + value + "L");
}
}
} else {
if (key.toLowerCase().startsWith("search")) {
key = key.replace("search", "");
key = key.substring(0, 1).toLowerCase() + key.substring(1);
}
if (!value.toString().trim().equals("") && filedAndColumnMap.containsKey(key)
&& (key.toLowerCase().equals("cfgid")
|| key.toLowerCase().equals("entranceid"))) {
countSql.append(
" and " + filedAndColumnMap.get(key) + "=" + value.toString().trim() + "L");
} else if (!value.toString().trim().equals("") && filedAndColumnMap.containsKey(key)
&& (key.toLowerCase().equals("protocol") || key.toLowerCase().equals("serverip")
|| key.toLowerCase().equals("clientip")
|| key.toLowerCase().equals("cljip"))) {
countSql.append(" and " + filedAndColumnMap.get(key) + "='"
+ value.toString().trim() + "'");
} else if (!value.toString().trim().equals("") && filedAndColumnMap.containsKey(key)
&& key.toLowerCase().equals("servicetype")) {
countSql.append(
" and " + filedAndColumnMap.get(key) + "=" + value.toString().trim());
}
}
}
}
}
if (null != searchActiveSys && !searchActiveSys.equals(Constants.ACTIVESYS_A)) {// B版数据库才有found_time_partition字段,A版毛衣found_time_partition分区字段
if (null != foundTimePartStart) {
countSql.append(" and found_time_partition>=" + foundTimePartStart + "L");
}
if (null != foundTimePartEnd) {
countSql.append(" and found_time_partition<" + foundTimePartEnd + "L");
}
}
}
}
logger.info("获取数据中心日志总条数sql==================" + countSql.toString());
ResultSet countRs = HiveJDBC.query(countSql.toString(), searchActiveSys);
String countStr = null;
while (countRs.next()) {
countStr = countRs.getObject(1).toString();
break;
}
if (countStr == null || countStr.equals("")) {
logger.info("获取数据中心日志总条数成功总共===================0条配置");
return 0l;
}
Long count = Long.valueOf(countStr);
logger.info("获取数据中心日志总条数成功总共===================" + count + "条配置");
HiveJDBC.closeConn();
return count;
}
public static String getFiledsSql(String mapName, String fileds) throws Exception {
String[] fieldsColoumn = null;
String orderByStr = "";
// 所有字段名
List<String> columnList = new ArrayList<String>();
// 所有属性名
List<String> propertyList = new ArrayList<String>();
// 属性名称为key字段名称为value
Map<String, String> columnMap = new HashMap<String, String>();
if (!StringUtil.isBlank(fileds)) {
// 解析Fileds的字段/属性名称
fieldsColoumn = fileds.split(",");
// 从resultMap中获取字段名称和属性名称
if (fieldsColoumn != null) {
SqlSessionFactory sqlSessionFactory = SpringContextHolder.getBean(SqlSessionFactory.class);
ResultMap map = sqlSessionFactory.getConfiguration().getResultMap(mapName + "Map");
List<ResultMapping> mapping = map.getResultMappings();
for (ResultMapping mapp : mapping) {
columnList.add(mapp.getColumn().toLowerCase());
propertyList.add(mapp.getProperty());
columnMap.put(mapp.getProperty(), mapp.getColumn());
}
}
if (fieldsColoumn != null) {
fileds = "";
for (String column : fieldsColoumn) {
if (!StringUtil.isBlank(column)) {
column = column.trim();
if (columnList.contains(column)) {
fileds += "," + column;
} else if (propertyList.contains(column)) {
fileds += "," + columnMap.get(column).toString();
}
}
}
if (!StringUtil.isBlank(fileds)) {
fileds = fileds.substring(1);
}
}
}
return fileds;
}
public static Map<String, String> getFiledAndColumnMap(Class clazz) {
Map<String, String> map = new HashMap<String, String>();
SqlSessionFactory sqlSessionFactory = SpringContextHolder.getBean(SqlSessionFactory.class);
ResultMap resultMap = sqlSessionFactory.getConfiguration().getResultMap(clazz.getSimpleName() + "Map");
List<ResultMapping> mapping = resultMap.getResultMappings();
for (ResultMapping mapp : mapping) {
map.put(mapp.getProperty(), mapp.getColumn().toLowerCase());
}
return map;
}
/**
* 利用反射通过get方法获取bean中字段fieldName的值
*
* @param bean
* @param fieldName
* @return
* @throws Exception
*/
private static Object getFieldValue(Object bean, String fieldName) throws Exception {
StringBuffer result = new StringBuffer();
String methodName = result.append("get").append(fieldName.substring(0, 1).toUpperCase())
.append(fieldName.substring(1)).toString();
Object rObject = null;
Method method = null;
@SuppressWarnings("rawtypes")
Class[] classArr = new Class[0];
method = bean.getClass().getMethod(methodName, classArr);
rObject = method.invoke(bean, new Object[0]);
return rObject;
}
/**
* 利用发射调用bean.set方法将value设置到字段
*
* @param bean
* @param fieldName
* @param value
* @throws Exception
*/
private static void setFieldValue(Object bean, String fieldName, Object value) throws Exception {
StringBuffer result = new StringBuffer();
String methodName = result.append("set").append(fieldName.substring(0, 1).toUpperCase())
.append(fieldName.substring(1)).toString();
/**
* 利用发射调用bean.set方法将value设置到字段
*/
Class[] classArr = new Class[1];
classArr[0] = "java.lang.String".getClass();
Method method = bean.getClass().getMethod(methodName, classArr);
method.invoke(bean, value);
}
/**
* 比较开始时间或者结束时间是否比当前系统时间早48小时
*
* @param startTime
* 开始时间
* @param endTime
* 结束时间
* @return
* @throws ParseException
*/
public static boolean ifTimeGreaterThan48(String startTime, String endTime) throws Exception {
logger.info("ifTimeGreaterThan48方法开始" + System.currentTimeMillis());
if (null != startTime && !startTime.equals("") && null != endTime && !endTime.equals("")) {// 开始和结束时间都不为空
Date startDate = sdf.parse(startTime);
Date endDate = sdf.parse(endTime);
if (startDate.getTime() < endDate.getTime()) {// 开始时间比结束时间早
logger.info("ifTimeGreaterThan48方法结束" + System.currentTimeMillis());
return gt48(endTime);
} else {// 开始时间比结束时间晚,不符合一般情况
logger.info("ifTimeGreaterThan48方法结束" + System.currentTimeMillis());
return false;
}
} else if (null != endTime && !endTime.equals("")) {// 开始时间为空,结束时间不为空
logger.info("ifTimeGreaterThan48方法结束" + System.currentTimeMillis());
return gt48(endTime);
} else if (null != startTime && !startTime.equals("")) {// 结束时间为空,开始时间不为空
logger.info("ifTimeGreaterThan48方法结束" + System.currentTimeMillis());
return gt48(startTime);
} else {// 开始和结束时间都为空
logger.info("ifTimeGreaterThan48方法结束" + System.currentTimeMillis());
return false;
}
}
public static boolean gt48(String eqTime) throws ParseException {
logger.info("gt48方法开始" + System.currentTimeMillis());
Date eqDate = sdf.parse(eqTime);
Long dateNum = eqDate.getTime();
Long currentDate = new Date().getTime();
Long time = 0l;
if (dateNum < currentDate) {
time = currentDate - dateNum;// 获取结束时间与当前系统时间的时间差毫秒数
} else {
logger.info("gt48方法结束" + System.currentTimeMillis());
return false;// 结束时间比当前系统时间晚,不符合从数据中心查询数据要求(当前日期48小时前数据从数据中心查询)
}
double hours = time.doubleValue() / (1000 * 60 * 60);
Long datacenterTime = Constants.DATACENTER_TIME;
double doubleValue = datacenterTime.doubleValue();
if (hours > doubleValue) {
logger.info("gt48方法结束" + System.currentTimeMillis());
return true;// 符合要求
} else {
logger.info("gt48方法结束" + System.currentTimeMillis());
return false;
}
}
public static void main(String[] args) {
Long datacenterTime = Constants.DATACENTER_TIME;
double doubleValue = datacenterTime.doubleValue();
System.out.println(doubleValue);
}
}

View File

@@ -0,0 +1,27 @@
package com.nis.web.service;
import org.springframework.stereotype.Service;
import com.nis.domain.Page;
import com.nis.domain.SysLog;
import com.nis.util.DateUtils;
import com.nis.web.dao.SysLogDao;
@Service
public class LogService extends CrudService<SysLogDao, SysLog> {
public Page<SysLog> findPage(Page<SysLog> page, SysLog sysLog) {
// 设置默认时间范围,默认当前月
if (sysLog.getBeginDate() == null){
sysLog.setBeginDate(DateUtils.setDays(DateUtils.parseDate(DateUtils.getDate()), 1));
}
if (sysLog.getEndDate() == null){
sysLog.setEndDate(DateUtils.addMonths(sysLog.getBeginDate(), 1));
}
return super.findPage(page, sysLog);
}
}

View File

@@ -0,0 +1,97 @@
package com.nis.web.service;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.nis.domain.SysMenu;
import com.nis.domain.SysUser;
import com.nis.util.CacheUtils;
import com.nis.util.LogUtils;
import com.nis.util.StringUtil;
import com.nis.web.dao.SysMenuDao;
import com.nis.web.security.UserUtils;
@Service
public class MenuService extends BaseService {
@Autowired
private SysMenuDao menuDao;
public List<SysMenu> findAllMenu() {
return UserUtils.getMenuList();
}
public SysMenu getMenu(Long id) {
return menuDao.get(id);
}
public void saveOrUpdateMenu(SysMenu menu) {
// 获取父节点实体
menu.setParent(this.getMenu(menu.getParent().getId()));
// 获取修改前的parentIds用于更新子节点的parentIds
String oldParentIds = menu.getParentIds();
// 设置新的父节点串
menu.setParentIds(menu.getParent().getParentIds()+menu.getParent().getId()+",");
SysUser user = UserUtils.getUser();
// 保存或更新实体
if (StringUtil.isEmpty(menu.getId())){
menu.setUpdateBy(user);
menu.setCreateBy(user);
menu.setCreateDate(new Date());
menu.setUpdateDate(menu.getCreateDate());
menu.setDelFlag(1);
menuDao.insert(menu);
}else{
menu.setUpdateBy(user);
menu.setUpdateDate(new Date());
menuDao.update(menu);
}
// 更新子节点 parentIds
SysMenu m = new SysMenu();
m.setParentIds("%,"+menu.getId()+",%");
List<SysMenu> list = menuDao.findByParentIdsLike(m);
for (SysMenu e : list){
e.setParentIds(e.getParentIds().replace(oldParentIds, menu.getParentIds()));
menuDao.updateParentIds(e);
}
// 清除用户菜单缓存
UserUtils.removeCache(UserUtils.CACHE_MENU_LIST);
// // 清除权限缓存
// systemRealm.clearAllCachedAuthorizationInfo();
// 清除日志相关缓存
CacheUtils.remove(LogUtils.CACHE_MENU_NAME_PATH_MAP);
}
public void deleteMenu(SysMenu menu) {
menuDao.delete(menu);
// 清除用户菜单缓存
UserUtils.removeCache(UserUtils.CACHE_MENU_LIST);
// // 清除权限缓存
// systemRealm.clearAllCachedAuthorizationInfo();
// 清除日志相关缓存
CacheUtils.remove(LogUtils.CACHE_MENU_NAME_PATH_MAP);
}
public void updateMenuSort(SysMenu menu) {
menuDao.updateSort(menu);
// 清除用户菜单缓存
UserUtils.removeCache(UserUtils.CACHE_MENU_LIST);
// // 清除权限缓存
// systemRealm.clearAllCachedAuthorizationInfo();
// 清除日志相关缓存
CacheUtils.remove(LogUtils.CACHE_MENU_NAME_PATH_MAP);
}
}

View File

@@ -0,0 +1,108 @@
package com.nis.web.service;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
import com.nis.domain.SysOffice;
import com.nis.util.DictUtils;
import com.nis.util.StringUtil;
import com.nis.web.dao.SysOfficeDao;
import com.nis.web.security.UserUtils;
@Service
public class OfficeService extends TreeService<SysOfficeDao, SysOffice>{
public List<SysOffice> findAll() {
return UserUtils.getOfficeList();
}
public List<SysOffice> findList(Boolean isAll){
if (isAll != null && isAll){
return UserUtils.getOfficeAllList();
}else{
return UserUtils.getOfficeList();
}
}
public SysOffice selectByPrimaryKey(Integer id){
if(id != null){
return dao.selectByPrimaryKey(id);
}else{
return null;
}
}
public List<SysOffice> findAllOfficeList(SysOffice office){
//office.getSqlMap().put("dsf", dataScopeFilter(UserUtils.getUser(), "a", ""));
if (!StringUtil.isEmpty(office.getId()) && office.getId() != 1l) {
office.setParentIds(office.getParentIds()+office.getId()+","+"%");
} else {
office.setParentIds(office.getParentIds()+"%");
}
return dao.findByParentIdsLike(office);
}
public void saveOrUpdate(SysOffice office) {
if (StringUtil.isEmpty(office.getId())) {
office.setCreateTime(new Date());
office.setDelFlag(1);
}
this.save(office);
if(office.getChildDeptList() != null) {
SysOffice childOffice = null;
for(String id : office.getChildDeptList()){
childOffice = new SysOffice();
childOffice.setName(DictUtils.getDictLabel("SYS_OFFICE_COMMON", id, "未知"));
childOffice.setParent(office);
childOffice.setArea(office.getArea());
childOffice.setType(2);
childOffice.setGrade(office.getGrade()+1);
childOffice.setUseable(1);
childOffice.setCreateTime(new Date());
childOffice.setDelFlag(1);
this.save(childOffice);
}
}
UserUtils.removeCache(UserUtils.CACHE_OFFICE_LIST);
}
public void delete(SysOffice office) {
super.delete(office);
UserUtils.removeCache(UserUtils.CACHE_OFFICE_LIST);
}
public List<SysOffice> selectOfficeForDeptment(Map map) {
List<SysOffice> sysOfficeList=dao.selectOfficeForDeptment(map);
return sysOfficeList;
}
public List<SysOffice> selectOfficeForLetter(Map<String, Object> hmap) {
List<SysOffice> sysOfficeList=dao.selectOfficeForLetter(hmap);
return sysOfficeList;
}
public List<SysOffice> selectLowerDeptement(Map<String, Object> hmap) {
List<SysOffice> sysOfficeList=dao.selectLowerDeptement(hmap);
return sysOfficeList;
}
public List<SysOffice> selectSysOffice(SysOffice sysOffice) {
return dao.selectSysOffice(sysOffice);
}
}

View File

@@ -0,0 +1,80 @@
package com.nis.web.service;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.nis.domain.SysRole;
import com.nis.domain.SysUser;
import com.nis.util.StringUtil;
import com.nis.web.dao.SysRoleDao;
import com.nis.web.security.UserUtils;
@Service
public class RoleService extends BaseService {
@Autowired
private SysRoleDao roleDao;
public List<SysRole> findAllRole() {
return UserUtils.getRoleList();
}
public SysRole getRole(Long id) {
return roleDao.get(id);
}
public SysRole getRoleByName(String name) {
SysRole r = new SysRole();
r.setName(name);
return roleDao.getByName(r);
}
public void saveOrUpdate(SysRole role) {
if (StringUtil.isEmpty(role.getId())){
role.setCreateTime(new Date());
role.setStatus(1);
roleDao.insert(role);
// 同步到Activiti
//saveActivitiGroup(role);
}else{
roleDao.update(role);
// 更新角色与菜单关联
roleDao.deleteRoleMenu(role);
}
if (role.getMenuList().size() > 0){
roleDao.insertRoleMenu(role);
}
// 同步到Activiti
//saveActivitiGroup(role);
// 清除用户角色缓存
UserUtils.removeCache(UserUtils.CACHE_ROLE_LIST);
List<SysUser> userList = roleDao.findUserByRole(role);
for (SysUser user : userList) {
UserUtils.clearCache(user);
}
// // 清除权限缓存
// systemRealm.clearAllCachedAuthorizationInfo();
}
public void deleteRole(SysRole role) {
roleDao.delete(role);
// 同步到Activiti
//deleteActivitiGroup(role);
// 清除用户角色缓存
//UserUtils.removeCache(UserUtils.CACHE_ROLE_LIST);
UserUtils.clearCache();
// // 清除权限缓存
// systemRealm.clearAllCachedAuthorizationInfo();
}
}

View File

@@ -0,0 +1,88 @@
/**
* Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.nis.web.service;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
/**
* 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候取出ApplicaitonContext.
*
* @author Zaric
* @date 2013-5-29 下午1:25:40
*/
@Service
@Lazy(false)
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {
private static ApplicationContext applicationContext = null;
private static Logger logger = LoggerFactory.getLogger(SpringContextHolder.class);
/**
* 取得存储在静态变量中的ApplicationContext.
*/
public static ApplicationContext getApplicationContext() {
assertContextInjected();
return applicationContext;
}
/**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
assertContextInjected();
return (T) applicationContext.getBean(name);
}
/**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
public static <T> T getBean(Class<T> requiredType) {
assertContextInjected();
return applicationContext.getBean(requiredType);
}
/**
* 清除SpringContextHolder中的ApplicationContext为Null.
*/
public static void clearHolder() {
if (logger.isDebugEnabled()){
logger.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext);
}
applicationContext = null;
}
/**
* 实现ApplicationContextAware接口, 注入Context到静态变量中.
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
SpringContextHolder.applicationContext = applicationContext;
}
/**
* 实现DisposableBean接口, 在Context关闭时清理静态变量.
*/
@Override
public void destroy() throws Exception {
SpringContextHolder.clearHolder();
}
/**
* 检查ApplicationContext不为空.
*/
private static void assertContextInjected() {
Validate.validState(applicationContext != null, "applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder.");
}
}

View File

@@ -0,0 +1,161 @@
package com.nis.web.service;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.QName;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.om.impl.OMNamespaceImpl;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.rpc.client.RPCServiceClient;
import org.apache.commons.io.FileUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.nis.domain.SrcIp;
import com.nis.domain.SysRole;
import com.nis.domain.SysUser;
import com.nis.util.Configurations;
import com.nis.util.DateUtils;
import com.nis.util.IpUtil;
import com.nis.util.StringUtil;
import com.nis.util.TimeConstants;
import com.nis.web.dao.SrcIpDao;
import com.nis.web.dao.SysOfficeDao;
import com.nis.web.dao.UserDao;
import com.nis.web.security.Servlets;
import com.nis.web.security.SessionDAO;
import com.nis.web.security.UserUtils;
@Service
public class SystemService extends BaseService{
@Autowired
private SessionDAO sessionDao;
@Autowired
private UserDao userDao;
@Autowired
private SysOfficeDao sysOfficeDao;
@Autowired
private SrcIpDao srcIpDao;
public Collection<Session> getActiveSessions(boolean includeLeave) {
return sessionDao.getActiveSessions(includeLeave);
}
public Collection<Session> getActiveSessions(boolean includeLeave, Object principal, Session filterSession) {
return sessionDao.getActiveSessions(includeLeave, principal, filterSession);
}
public void deleteSession(Session session) {
sessionDao.delete(session);
}
public SysUser getUserByLoginName(String loginName) {
return UserUtils.getByLoginName(loginName);
}
public List<SrcIp> ipLookUp(String ip) {
return srcIpDao.getIpInfo(IpUtil.getIpHostDesimal(ip));
}
public SysUser assignUserToRole(SysRole role, SysUser user) {
if (user == null){
return null;
}
List<Long> roleIds = user.getRoleIdList();
if (roleIds.contains(role.getId())) {
return null;
}
user.getUserRoleList().clear();
user.getUserRoleList().add(role);
userDao.insertUserRole(user);
UserUtils.clearCache(user);
return user;
}
public Boolean outUserInRole(SysRole role, SysUser user) {
List<SysRole> roles = user.getUserRoleList();
for (SysRole e : roles){
if (e.getId().equals(role.getId())){
roles.remove(e);
userDao.removeUserInRole(user.getId(),role.getId());
return true;
}
}
return false;
}
public boolean officeIsValid(Long officeId, Long companyId) {
return userDao.officeIsExistOfCompany(officeId, companyId) >0 ? true : false;
}
/**
* 结果信息存入文件
* @param result
* @throws IOException
*/
private void saveToFile(String prefixName, String result) throws IOException{
String flieName = prefixName + DateUtils.formatDate(new Date(), TimeConstants.YYYYMMDDHH24MMSS);
String filePath = Servlets.getRequest().getServletContext().getRealPath(Configurations.getStringProperty("userfiles.basedir", "")) + File.separator
+ "upload" + File.separator + flieName + ".txt";
FileUtils.writeStringToFile(new File(filePath), result, false);
}
/**
* 新增设置header信息需要修改里面rid、sid对应的值、sid为服务唯一标识、 rid为请求者唯一标识
*/
private static OMElement setHeader(String ns, String rid, String sid) {
OMFactory fac = OMAbstractFactory.getOMFactory();
// OMNamespace指定此SOAP文档名称空间。
OMNamespaceImpl omNs = (OMNamespaceImpl) fac.createOMNamespace(ns, "ns1");
// 创建header元素并指定其在omNs指代的名称空间中,header名称固定为CyberpoliceSBReqHeader。
OMElement method = fac.createOMElement("CyberpoliceSBReqHeader", omNs);
// 指定元素的文本内容。
OMElement ridE = fac.createOMElement("rid", omNs);
// TODO将下面的值修改为请求者在系统中的唯一标识
ridE.setText(rid);
method.addChild(ridE);
OMElement sidE = fac.createOMElement("sid", omNs);
// TODO将下面的值修改要请求服务的唯一标识
sidE.setText(sid);
method.addChild(sidE);
OMElement timeoutE = fac.createOMElement("timeout", omNs);
// TODO将下面的值修改为请求的超时时间单位秒
timeoutE.setText(Configurations.getStringProperty("webservice.request.timeout", "60"));
method.addChild(timeoutE);
OMElement secE = fac.createOMElement("sec", omNs);
// TODO将下面的值修改为请求密码如果使用其他加密方式则根据要求统一修改即可
secE.setText("");
method.addChild(secE);
return method;
}
}

View File

@@ -0,0 +1,81 @@
package com.nis.web.service;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
import com.nis.domain.TreeEntity;
import com.nis.exceptions.ServiceException;
import com.nis.util.Reflections;
import com.nis.util.StringUtil;
import com.nis.util.StringUtils;
import com.nis.web.dao.TreeDao;
/**
* Service基类
* @author ThinkGem
* @version 2014-05-16
*/
public abstract class TreeService<D extends TreeDao<T>, T extends TreeEntity<T>> extends CrudService<D, T> {
public void save(T entity) {
@SuppressWarnings("unchecked")
Class<T> entityClass = Reflections.getClassGenricType(getClass(), 1);
// 如果没有设置父节点,则代表为跟节点,有则获取父节点实体
if (entity.getParent() == null || StringUtil.isEmpty(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(Long.class).newInstance(0l);
} 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) {
}
}

View File

@@ -0,0 +1,162 @@
package com.nis.web.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.nis.domain.Page;
import com.nis.domain.SysUser;
import com.nis.exceptions.ServiceException;
import com.nis.util.CacheUtils;
import com.nis.util.StringUtil;
import com.nis.util.StringUtils;
import com.nis.web.dao.UserDao;
import com.nis.web.security.UserUtils;
@Service
public class UserService extends BaseService {
/**@Resource**/
@Autowired
private UserDao userDao;
/**
* 获取用户
* @param id
* @return
*/
public SysUser getUser(String id) {
return UserUtils.get(id);
}
public Page<SysUser> findUser(Page<SysUser> page, SysUser user) {
// 生成数据权限过滤条件dsf为dataScopeFilter的简写在xml中使用 ${sqlMap.dsf}调用权限SQL
user.getSqlMap().put("dsf", dataScopeFilter(user.getCurrentUser(), "o", "u"));
// 设置分页参数
user.setPage(page);
// 执行分页查询
page.setList(userDao.findList(user));
return page;
}
public SysUser getUserById(Long id) {
return userDao.getUserById(id);
}
public SysUser getUserByLoginName(String loginName) {
return userDao.getUserByLoginName(loginName);
}
public SysUser getUserByIdWithRelation(Long userId) {
return userDao.getUserWithRelation(new SysUser(userId, null));
}
public void saveOrUpdate(SysUser user) {
if (StringUtil.isEmpty(user.getId())) {
user.setCreateTime(new Date());
user.setStatus(1);
userDao.insert(user);
} else {
SysUser oldUser = userDao.getUserWithRelation(user);
// 清除原用户机构用户缓存
if (!StringUtil.isEmpty(oldUser.getOffice())) {
CacheUtils.remove(UserUtils.USER_CACHE, UserUtils.USER_CACHE_LIST_BY_OFFICE_ID_ + oldUser.getOffice().getId());
}
userDao.update(user);
userDao.deleteUserRole(user.getId());
//userDao.deleteUserOffice(user.getId());
}
/*if (!StringUtil.isEmpty(user.getOffice())) {
user.addOffice(user.getOffice());
userDao.insertUserOffice(user);
}else {
throw new ServiceException(user.getLoginId() + "没有设置部门!");
}*/
if (!StringUtil.isEmpty(user.getUserRoleList())) {
userDao.insertUserRole(user);
} else {
throw new ServiceException(user.getLoginId() + "没有设置角色!");
}
// 将当前用户同步到Activiti
//saveActivitiUser(user);
UserUtils.clearCache(user);
// 清除权限缓存
//systemRealm.clearAllCachedAuthorizationInfo();
}
public void deleteUser(SysUser user) {
userDao.delete(user);
// 同步到Activiti
//deleteActivitiUser(user);
// 清除用户缓存
UserUtils.clearCache(user);
// // 清除权限缓存
// systemRealm.clearAllCachedAuthorizationInfo();
}
public void updatePasswordById(Long id, String loginId, String newPassword) {
SysUser user = new SysUser(id,loginId);
user.setPassword(StringUtils.entryptPassword(newPassword));
userDao.updatePasswordById(user);
UserUtils.clearCache(user);
// // 清除权限缓存
// systemRealm.clearAllCachedAuthorizationInfo();
}
public List<SysUser> findUserByRoleId(Long id) {
return userDao.findUserByRoleId(id);
}
public List<SysUser> findUserByOfficeId(Long id) {
return userDao.findUserByOfficeId(id);
}
public void updateUserInfo(SysUser user) {
userDao.updateUserInfo(user);
// 清除用户缓存
UserUtils.clearCache(user);
// // 清除权限缓存
// systemRealm.clearAllCachedAuthorizationInfo();
}
public List<Map> findDeptLeader(Integer DeptementId){
return userDao.findDeptLeader(DeptementId);
}
}