Commit 27bcb257 authored by zhaoaiqing's avatar zhaoaiqing

task By zhaoaiqing : 项目1.0.0.RELEASE 发布

parents
## .gitignore for Grails 1.2 and 1.3
# .gitignore for maven
target/
*.releaseBackup
# web application files
#/web-app/WEB-INF
# IDE support files
/.classpath
/.launch
/.project
/.settings
/*.launch
/*.tmproj
/ivy*
/eclipse
# default HSQL database files for production mode
/prodDb.*
# general HSQL database files
*Db.properties
*Db.script
# logs
/stacktrace.log
/test/reports
/logs
*.log
*.log.*
# project release file
/*.war
# plugin release file
/*.zip
/*.zip.sha1
# older plugin install locations
/plugins
/web-app/plugins
/web-app/WEB-INF/classes
# "temporary" build files
target/
out/
build/
# other
*.iws
#.gitignore for java
*.class
# Package Files #
*.jar
*.war
*.ear
## .gitignore for eclipse
*.pydevproject
.project
.metadata
bin/**
tmp/**
tmp/**/*
*.tmp
*.bak
*.swp
*~.nib
local.properties
.classpath
.settings/
.loadpath
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# CDT-specific
.cproject
# PDT-specific
.buildpath
## .gitignore for intellij
*.iml
*.ipr
*.iws
.idea/
## .gitignore for linux
.*
!.gitignore
!.gitattributes
!.editorconfig
!.eslintrc
!.travis.yml
*~
## .gitignore for windows
# Windows image file caches
Thumbs.db
ehthumbs.db
# Folder config file
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
## .gitignore for mac os x
.DS_Store
.AppleDouble
.LSOverride
# Thumbnails
._*
# Files that might appear on external disk
.Spotlight-V100
.Trashes
## hack for graddle wrapper
!wrapper/*.jar
!**/wrapper/*.jar
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.cesgroup.zw.spring.boot</groupId>
<artifactId>codetable-spring-boot</artifactId>
<version>1.0.0.RELEASE</version>
</parent>
<artifactId>codetable-spring-boot-autoconfigure</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.cesgroup.zw.codetable</groupId>
<artifactId>codetable</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>0.2.23</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
package com.cesgroup.zw.codetable;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.sql.DataSource;
import org.springframework.core.io.Resource;
import com.cesgroup.zw.common.parse.query.ParseQuery;
import com.cesgroup.zw.core.codetable.CodeGroup;
import com.cesgroup.zw.core.codetable.CodeTableCache;
public class WEBCodeTableCache {
private CodeTableCache codeTableCache = CodeTableCache.getInstance();
private ParseQuery query;
public WEBCodeTableCache(ParseQuery query) {
this.query = query;
}
/**
* 加载CODETABLE数据
* @throws Exception
*/
public void loadData() throws Exception {
if(null != dbCodeFiles ) {
// XML数据流
InputStream[] dbCodeInputStreams = new InputStream[dbCodeFiles.length];
for(int i = 0;i < dbCodeFiles.length;i++) {
dbCodeInputStreams[i] = dbCodeFiles[i].getInputStream();
}
codeTableCache.setDbCodeInputStreams(dbCodeInputStreams);
}
if(null != xmlCodeFiles ) {
// DB数据流
InputStream[] xmlCodeInputStreams = new InputStream[xmlCodeFiles.length];
for(int i = 0;i < xmlCodeFiles.length;i++) {
xmlCodeInputStreams[i] = xmlCodeFiles[i].getInputStream();
}
codeTableCache.setXmlCodeInputStreams(xmlCodeInputStreams);
}
codeTableCache.setQuery(query);
codeTableCache.loadData();
}
public synchronized CodeGroup getGroup(String cacheKey) throws Exception {
return codeTableCache.getGroup(cacheKey);
}
/**
* 通过字段取得组信息
* @param cacheKey group 名
* @param valueName 字段的名称
* @param value 字段的值
* @return
* @throws Exception
*/
public synchronized CodeGroup getGroup(String cacheKey,String valueName,String value) throws Exception {
CodeGroup codeGroup = codeTableCache.getGroup(cacheKey);
Map<String, Object> dataMap = codeGroup.getCodeMap(valueName, value);
if(null != dataMap) {
return new CodeGroup(dataMap,cacheKey,codeGroup.getCodeClass(),codeGroup.getKeyField());
}
return new CodeGroup(new HashMap(),cacheKey,codeGroup.getCodeClass(),codeGroup.getKeyField());
}
private Set<Object> getDataSourceTypes(ParseQuery query) {
DataSource dataSource = null;
Class<?> clazz = query.getClass();
for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
try{
Field field = clazz.getDeclaredField("dataSource");
if(null != field ){
field.setAccessible(true);
dataSource = (DataSource) field.get(query);
}
} catch (Exception e) {
}
}
if(null != dataSource /*&& dataSource instanceof CustomerRoutingDataSource*/) {
try {
Method method = dataSource.getClass().getDeclaredMethod("getCodeTableDataSources",new Class[]{});
if(null != method ){
method.setAccessible(true);
return (HashSet<Object>) method.invoke(dataSource,new Object[]{});
}
} catch (Exception e) {
//e.printStackTrace();
e.printStackTrace();
}
//return ((CustomerRoutingDataSource)dataSource).getCodeTableDataSources();
}
return new HashSet<Object>();
}
private Resource[] dbCodeFiles;
private Resource[] xmlCodeFiles;
public Resource[] getDbCodeFiles() {
return dbCodeFiles;
}
public void setDbCodeFiles(Resource[] dbCodeFiles) {
this.dbCodeFiles = dbCodeFiles;
}
public Resource[] getXmlCodeFiles() {
return xmlCodeFiles;
}
public void setXmlCodeFiles(Resource[] xmlCodeFiles) {
this.xmlCodeFiles = xmlCodeFiles;
}
}
package com.cesgroup.zw.codetable.query;
import com.cesgroup.zw.core.codetable.query.IQuery;
/**
* DB业务字典查询扩展类
* @author Roger
* @version 1.0.0
*
*/
public class CodeTableQueryDAOImpl extends ParseQueryDAOImpl implements IQuery{
}
package com.cesgroup.zw.codetable.query;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import com.cesgroup.zw.common.parse.query.ParseQuery;
public class ParseQueryDAOImpl extends JdbcTemplate implements ParseQuery {
public List<Map<String, Object>> queryForList(String sql) {
return super.queryForList(sql);
}
public int insert(String sql, Object[] params) {
return super.update(sql,params);
}
public int execute(String sql, Object[] params) {
return super.update(sql,params);
}
public long insertAndGetKey(final String sql) {
KeyHolder keyHolder = new GeneratedKeyHolder();
super.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection con)
throws SQLException {
PreparedStatement ps = con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
return ps;
}
}, keyHolder);
return keyHolder.getKey().longValue();
}
public long count(String sql, Object[] params) {
return super.queryForObject(sql, params, Long.class);
}
}
package com.cesgroup.zw.codetable.web.freemarker.taglib;
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Field;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.cesgroup.zw.core.codetable.CodeGroup;
import com.cesgroup.zw.core.codetable.CodeTableCache;
import com.cesgroup.zw.core.codetable.util.StringUtils;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
/**
* CODE TABLE 输出自定义标签
* @author Roger
*
*/
public class CodeTableWriteTag implements TemplateDirectiveModel{
public static String TAGNAME = "Write";
private Log logger = LogFactory.getLog(CodeTableWriteTag.class);
// CODETABLE 组的名称
private final String PARAM_NAME_GROUP_NAME = "groupName";
// CODETABLE 每一个主键的名称
private final String PARAM_NAME_KEY = "key";
// CODETABLE 要显示的字段名称
private final String PARAM_NAME_DISPLAY_NAME = "displayName";
private final String DEFAULT_DISPLAY_NAME = "display";
public void execute(Environment env, Map params, TemplateModel[] loopVars,
TemplateDirectiveBody body) throws TemplateException, IOException {
// 取得CODETABLE的实例
CodeTableCache codeTableCache = CodeTableCache.getInstance();
// 取得要处理的组的名称
String groupName = null != params.get(PARAM_NAME_GROUP_NAME)?params.get(PARAM_NAME_GROUP_NAME).toString():null;
// 取得主KEY的名称
String key = null != params.get(PARAM_NAME_KEY)?params.get(PARAM_NAME_KEY).toString():null;
if(StringUtils.isEmpty(groupName)) {
logger.warn("业务组名的信息不能为空。");
return ;
}
if( StringUtils.isEmpty(key)) {
logger.warn("业务组名为"+groupName+"的对应的业务信息不能为空。");
return ;
}
// 取得要显示的字段名称
String displayName = null != params.get(PARAM_NAME_DISPLAY_NAME)?params.get(PARAM_NAME_DISPLAY_NAME).toString():null;
if(StringUtils.isEmpty(displayName)) {
displayName = DEFAULT_DISPLAY_NAME;
}
try {
if(codeTableCache.containsGroup(groupName)) {
CodeGroup group = codeTableCache.getGroup(groupName);
if(group.containsCode(key)) {
Object obj = group.getCode(key);
Field field = obj.getClass().getDeclaredField(displayName);
field.setAccessible(true);
Writer out = env.getOut();
String value = (String)field.get(obj);
if(null != value) {
out.write(value);
if(null != body )
body.render(out);
}
}
}
} catch (Exception e) {
logger.error("业务组名为"+groupName+"的对应的业务信息取得时发生异常",e);
}
}
}
package com.cesgroup.zw.codetable.web.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.cesgroup.zw.codetable.WEBCodeTableCache;
public class CodeTableServletContextListener implements ServletContextListener{
final String COMPONENT = "CODE_TABLE";
final WEBCodeTableCache webCodeTableCache;
public CodeTableServletContextListener(WEBCodeTableCache webCodeTableCache) {
super();
this.webCodeTableCache = webCodeTableCache;
}
public void contextDestroyed(ServletContextEvent arg0) {
}
public void contextInitialized(ServletContextEvent event) {
event.getServletContext().setAttribute(COMPONENT, webCodeTableCache);
}
}
package com.cesgroup.zw.spring.boot.autoconfigure;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.cesgroup.zw.codetable.WEBCodeTableCache;
import com.cesgroup.zw.codetable.query.CodeTableQueryDAOImpl;
import com.cesgroup.zw.codetable.web.freemarker.taglib.CodeTableWriteTag;
import com.cesgroup.zw.codetable.web.listener.CodeTableServletContextListener;
@Configuration
@ConditionalOnProperty(name = "codetable.enable", havingValue = "true")
@ConditionalOnClass({ WEBCodeTableCache.class})
@EnableConfigurationProperties(CodeTableProperties.class)
//在指定的配置类初始化后再加载
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class CodeTableAutoConfiguration {
private static final Logger logger = LoggerFactory.getLogger(CodeTableAutoConfiguration.class);
private CodeTableProperties properties;
public CodeTableAutoConfiguration(CodeTableProperties properties) {
super();
this.properties = properties;
}
@Bean
@ConditionalOnMissingBean
public WEBCodeTableCache webCodeTableCache(DataSource dataSource) {
CodeTableQueryDAOImpl codeTableQuery = new CodeTableQueryDAOImpl();
codeTableQuery.setDataSource(dataSource);
WEBCodeTableCache webCodeTableCache = new WEBCodeTableCache(codeTableQuery);
webCodeTableCache.setXmlCodeFiles(properties.getXmlCodeFiles());
webCodeTableCache.setDbCodeFiles(properties.getDbCodeFiles());
try {
webCodeTableCache.loadData();
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return webCodeTableCache;
}
@Configuration
@ConditionalOnProperty(name = "codetable.webEnable", havingValue = "true")
@ConditionalOnWebApplication
public class CodeTableWebConfiguration {
/*@Bean
public CodeTableWriteTag codeTableWriteTag() {
return new CodeTableWriteTag();
}*/
@Autowired
private freemarker.template.Configuration configuration;
@PostConstruct
public void setSharedVariable(){
configuration.setSharedVariable(CodeTableWriteTag.TAGNAME,new CodeTableWriteTag());//标签名与标签类
}
@Bean
public ServletListenerRegistrationBean<CodeTableServletContextListener> serssionListenerBean(WEBCodeTableCache webCodeTableCache){
ServletListenerRegistrationBean<CodeTableServletContextListener>
sessionListener = new ServletListenerRegistrationBean<CodeTableServletContextListener>(new CodeTableServletContextListener(webCodeTableCache));
return sessionListener;
}
}
}
package com.cesgroup.zw.spring.boot.autoconfigure;
import java.io.IOException;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
@ConfigurationProperties(prefix = CodeTableProperties.PREFIX)
public class CodeTableProperties {
public static final String PREFIX = "codetable";
private static final ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
private String dbFileLocation;
private String xmlFileLocation;
private String enable;
private String webEnable;
public String getDbFileLocation() {
return dbFileLocation;
}
public void setDbFileLocation(String dbFileLocation) {
this.dbFileLocation = dbFileLocation;
}
public String getXmlFileLocation() {
return xmlFileLocation;
}
public void setXmlFileLocation(String xmlFileLocation) {
this.xmlFileLocation = xmlFileLocation;
}
public Resource[] getDbCodeFiles() {
return getResources(dbFileLocation);
}
public Resource[] getXmlCodeFiles() {
return getResources(xmlFileLocation);
}
private Resource[] getResources(String location) {
if(null == location) {
return new Resource[0];
}
try {
return resourceResolver.getResources(location);
} catch (IOException e) {
return new Resource[0];
}
}
public String getEnable() {
return enable;
}
public void setEnable(String enable) {
this.enable = enable;
}
public String getWebEnable() {
return webEnable;
}
public void setWebEnable(String webEnable) {
this.webEnable = webEnable;
}
}
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.cesgroup.zw.spring.boot.autoconfigure.CodeTableAutoConfiguration
\ No newline at end of file
package com.cesgroup.zw.spring.boot.autoconfigure;
import org.junit.Test;
import org.springframework.core.io.Resource;
import com.cesgroup.zw.spring.boot.autoconfigure.CodeTableProperties;
public class CodetablePropertiesTest {
@Test
public void xmlLocations() {
CodeTableProperties codeTableProperties = new CodeTableProperties();
codeTableProperties.setXmlFileLocation("classpath:/codetable/xml-code-table-*.xml");
Resource[] resources = codeTableProperties.getXmlCodeFiles();
System.out.println(resources.length);
}
@Test
public void dbLocations() {
CodeTableProperties codeTableProperties = new CodeTableProperties();
codeTableProperties.setDbFileLocation("classpath:/codetable/db-code-table-define.xml");
Resource[] resources = codeTableProperties.getDbCodeFiles();
System.out.println(resources.length);
}
}
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.cesgroup.zw.spring.boot</groupId>
<artifactId>codetable-spring-boot</artifactId>
<version>1.0.0.RELEASE</version>
</parent>
<artifactId>codetable-spring-boot-samples</artifactId>
<properties>
<codetable.version>1.0.0.RELEASE</codetable.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<dependency>
<groupId>com.cesgroup.zw.spring.boot</groupId>
<artifactId>codetable-spring-boot-starter</artifactId>
<version>${codetable.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
1、使用xml codetable
1.1、引用jar包
<dependency>
<groupId>com.youshine.spring.boot</groupId>
<artifactId>codetable-spring-boot-starter</artifactId>
<version>1.0.0.RELEASE</version>
</dependency>
1.2、追加配置
codetable.enable = true
codetable.xml-file-location=classpath:/codetable/xml-code-table-*.xml
2、如果要使用db codetable
2.1、引用jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<version>1.5.4.RELEASE</version>
</dependency>
2.2、追加配置
codetable.db-file-location=classpath:/codetable/db-code-table-*.xml
3、如果要再画面要使用code table,现在只开发了freemarker版本
3.1、引用jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
<version>1.5.4.RELEASE</version>
</dependency>
2.2、追加配置 ,不需要就不要设定
codetable.web-enable = true
\ No newline at end of file
package com.cesgroup.zw.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CodeTableApplication {
public static void main(String[] args) {
SpringApplication.run(CodeTableApplication.class, args);
}
}
package com.cesgroup.zw.boot.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class Sample2Controller {
@RequestMapping("/sample2")
public String index(HttpServletRequest request) {
request.setAttribute("val1", "0000");
return "sample2/index";
}
}
package com.cesgroup.zw.boot.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.cesgroup.zw.boot.vo.User;
import com.cesgroup.zw.core.codetable.Code;
import com.cesgroup.zw.core.codetable.util.CodeTableUtil;
@RestController
public class SampleController {
@RequestMapping("/index")
public Code index() {
Code code = CodeTableUtil.getCodeByKey(Code.class,"SITE_BAR", "0000");
return code;
}
@RequestMapping("/index1")
public Code index1() {
Code code = CodeTableUtil.getCodeByKey(Code.class,"SEC_USER", "1");
return code;
}
@RequestMapping("/index2")
public User index2() {
User code = CodeTableUtil.getCodeByKey(User.class,"SEC_USER1", "1");
return code;
}
}
package com.cesgroup.zw.boot.vo;
public class User {
private String userId;
private String userName;
private String delFlag;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getDelFlag() {
return delFlag;
}
public void setDelFlag(String delFlag) {
this.delFlag = delFlag;
}
}
/*
Navicat MySQL Data Transfer
Source Server : 192.168.127.10
Source Server Version : 50640
Source Host : 192.168.127.10:3306
Source Database : Test1
Target Server Type : MYSQL
Target Server Version : 50640
File Encoding : 65001
Date: 2018-08-19 00:16:22
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`user_id` varchar(255) NOT NULL DEFAULT '',
`user_name` varchar(255) DEFAULT NULL,
`del_flag` varchar(255) DEFAULT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', '2323', '0');
#dataSource configure
spring.datasource.url=jdbc:mysql://192.168.127.10:3306/Test1
#\u7528\u6237\u540d
spring.datasource.username=root
#\u5bc6\u7801
spring.datasource.password=123456
#\u6570\u636e\u5e93\u9a71\u52a8
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
codetable.enable = true
codetable.xml-file-location=classpath:/codetable/xml-code-table-*.xml
codetable.db-file-location=classpath:/codetable/db-code-table-*.xml
codetable.web-enable = true
spring.freemarker.allow-request-override=false
spring.freemarker.cache=true
spring.freemarker.check-template-location=true
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=false
spring.freemarker.suffix=.html
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<db-code-table-value>
<group name="SEC_USER">
<sql>
select * from user where del_flag = '0'
</sql>
<code-table-class>com.cesgroup.zw.core.codetable.Code</code-table-class>
<key-mapping field="key"/>
<value-mapping name="user_id" field="key"/>
<value-mapping name="user_name" field="display"/>
</group>
<group name="SEC_USER1">
<sql>
select * from user where del_flag = '0'
</sql>
<code-table-class>com.cesgroup.zw.boot.vo.User</code-table-class>
<key-mapping field="userId"/>
<value-mapping name="user_id" field="userId"/>
<value-mapping name="user_name" field="userName"/>
</group>
</db-code-table-value>
<?xml version="1.0" encoding="UTF-8"?>
<xml-code-table-value>
<group name="SITE_BAR" primaryField="key">
<code-table-class>com.cesgroup.zw.core.codetable.Code</code-table-class>
<code key="0000">
<display>5666</display>
<displayA>64</displayA>
<sortA>1</sortA>
</code>
<code key="00001">
<display>null</display>
<displayA>64</displayA>
<sortA>1</sortA>
</code>
</group>
<group name="SITE_BAR11" primaryField="key">
<code key="1111">
<display>null</display>
</code>
<code key="1122">
<display>null</display>
</code>
</group>
</xml-code-table-value>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<xml-code-table-value>
<group name="SITE_BAR22" primaryField="key">
<code-table-class>com.cesgroup.zw.core.codetable.Code</code-table-class>
<code key="222">
<display>5666</display>
<displayA>64</displayA>
<sortA>1</sortA>
</code>
<code key="2222">
<display>null</display>
<displayA>64</displayA>
<sortA>1</sortA>
</code>
</group>
<group name="SITE_BAR33" primaryField="key">
<code key="3333">
<display>null</display>
</code>
<code key="33333">
<display>null</display>
</code>
</group>
</xml-code-table-value>
\ No newline at end of file
<html>
<body>
<#list CODE_TABLE.getGroup('SEC_USER1').codes as code>
姓名:${code.userName}
<br>
</#list>
</body>
</html>
\ No newline at end of file
<html>
<body>
<#list CODE_TABLE.getGroup('SEC_USER1').codes as code>
姓名:${code.userName}
<br>
</#list>
用法一:
<@Write groupName='SITE_BAR' key='0000' />
用法二:
<@Write groupName='SITE_BAR' key='${val1}' displayName='displayA' />
</body>
</html>
\ No newline at end of file
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.cesgroup.zw.spring.boot</groupId>
<artifactId>codetable-spring-boot</artifactId>
<version>1.0.0.RELEASE</version>
</parent>
<artifactId>codetable-spring-boot-starter</artifactId>
<dependencies>
<dependency>
<groupId>com.cesgroup.zw.spring.boot</groupId>
<artifactId>codetable-spring-boot-autoconfigure</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
provides: codetable-spring-boot-autoconfigure,codetable
\ No newline at end of file
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.cesgroup.zw.spring.boot</groupId>
<artifactId>codetable-spring-boot</artifactId>
<version>1.0.0.RELEASE</version>
</parent>
<groupId>com.cesgroup.zw.codetable</groupId>
<artifactId>codetable</artifactId>
<dependencies>
<dependency>
<groupId>commons-digester</groupId>
<artifactId>commons-digester</artifactId>
</dependency>
<dependency>
<groupId>ognl</groupId>
<artifactId>ognl</artifactId>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.cesgroup.zw.common.parse;
import java.util.List;
import java.util.Map;
/**
* 参数解析接口
* @author Roger
* @version 1.0.0
*/
public interface ParameterParse {
/**
* 解析表达式中的内容
* @param expression 表达式
* @param context 解析的容器
* @param params 解析的参数源
* @return 解析后的结果
*/
public Object parse(String expression,Map<String,Object> context,Object[] params);
/**
* 从表达式中取出要解析的参数名
* @param expression 表达式
* @return 解析的参数名集合
*/
public List<String> getParameterName(String expression);
/**
* 解析器的类型
* @return OGNL解析器,WEB解析器,默认的解析器,业务字典解析器,环境变量解析器
*/
public Type getType();
enum Type {
OGNL,WEB,DEFAULT,CODE_TABLE,ENV;
}
public final String EMPTY_KEY = "EMPTY_KEY";
}
package com.cesgroup.zw.common.parse;
import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;
import com.cesgroup.zw.common.parse.ParameterParse.Type;
/**
* 解析器的工厂类
* @author Roger
* @version 1.0.0
*/
public class ParameterParseFactory {
// 解析器的源
public static Map<Type,ParameterParse> pool = new HashMap<Type,ParameterParse>();
public static ServiceLoader<ParameterParse> serviceLoader = ServiceLoader.load(ParameterParse.class);
/**
* 根据表达式的内容,生成所需要的解析器
* OGNL解析器 解析#arg,#result的表达式
* WEB解析器解析#request,#session,#application的表达式
* 业务字典解析器解析#code_table的表达式
* 环境变量解析器 解析#env的表达式
* 默认的解析器解析 ${},%{},空的表达式
* @param expression 要解析的表达式
* @return 相应的解析器
* @throws Exception
*/
public static ParameterParse create(String expression) throws Exception {
Type type = Type.DEFAULT;
if(expression.startsWith("#")){
// OGNL解析器 解析#arg,#result的表达式
if(expression.startsWith("#arg") || expression.startsWith("#result")) {
type = Type.OGNL;
} // WEB解析器解析#request,#session,#application的表达式
else if(expression.startsWith("#request") || expression.startsWith("#session") || expression.startsWith("#application")) {
type = Type.WEB;
} //业务字典解析器解析#code_table的表达式
else if(expression.startsWith("#code_table")) {
type = Type.CODE_TABLE;
} // 环境变量解析器 解析#env的表达式
else if(expression.startsWith("#env")) {
type = Type.ENV;
} // 默认的解析器解析 ${},%{},空的表达式
else {
type = Type.DEFAULT;
}
}
// 从数据源中取得
ParameterParse parse = pool.get(type);
if(null == parse) {
for(ParameterParse parameterParse:serviceLoader) {
if(parameterParse.getType().equals(type)){
parse = parameterParse;
pool.put(type, parse);
}
}
}
if(null == parse) {
throw new Exception("对应的解析器没有。"+"type->"+expression);
}
return parse;
}
public Map<Type, ParameterParse> getMap() {
return ParameterParseFactory.pool;
}
public void setMap(Map<Type, ParameterParse> map) {
ParameterParseFactory.pool = map;
}
}
package com.cesgroup.zw.common.parse;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import ognl.Ognl;
/**
* 解析器中的共通类
* @author Roger
* @version 1.0.0
*
*/
public class Parse {
protected Log logger = LogFactory.getLog(getClass());
/**
* 解析数据
* @param expression 表达式
* @param context 数据容器
* @return 解析结果
*/
protected Object getValue(String expression,Object context) {
try {
return Ognl.getValue(expression, context);
} catch (Exception e) {
logger.debug("参数["+expression+"]从"+context+"转换有错", e);
}
return null;
}
/**
* 从表达式中取出要解析的参数名
* ${}中的变量名
* @param expression 表达式
* @return 解析的参数名集合
*/
public List<String> getParameterName(String expression){
List<String> names = new ArrayList<String>();
while(true) {
int index = expression.indexOf("${");
if(index < 0){
break;
}
names.add(expression.substring(index+2,expression.indexOf("}")));
expression = expression.substring(expression.indexOf("}")+1,expression.length());
}
return names;
}
}
package com.cesgroup.zw.common.parse.query;
import java.util.List;
import java.util.Map;
/**
* 查询器
* @author Roger
* @version 1.0.0
*
*/
public interface ParseQuery {
public List<Map<String,Object>> queryForList(String sql);
public int insert(String sql,Object[] params);
public int execute(String sql,Object[] params);
public long insertAndGetKey(String sql);
public long count(String sql,Object[] params);
}
package com.cesgroup.zw.common.parse.util;
import java.io.File;
import java.io.InputStream;
import org.apache.commons.digester.Digester;
import org.apache.commons.digester.xmlrules.DigesterLoader;
import org.xml.sax.InputSource;
/**
* 配置文件映射成BEAN的工具
* @author Roger
* @version 1.0.0
*
*/
@SuppressWarnings("unchecked")
public class DigesterUtil {
/**
* 根据配置文件和规则文件将一个配置文件转换成一个具体的类
* @param <T>
* @param clz
* @param inputStream 配置文件的流
* @param ruleName 规则文件名
* @return 映射成BEAN
* @throws Exception
*/
public static <T> T parseXML(Class<T> clz,File file,String ruleName) throws Exception {
InputStream inputRuleStream = clz.getClassLoader().getResourceAsStream(clz.getPackage().getName().replaceAll("[.]", "/")+"/"+ruleName+".xml");
InputSource source = new InputSource(inputRuleStream);
Digester digester = DigesterLoader.createDigester(source);
try {
return (T)digester.parse(file);
} catch(Exception e) {
throw e;
}
}
/**
* 根据配置文件和规则文件将一个配置文件转换成一个具体的类
* @param <T>
* @param clz
* @param inputStream 配置文件的流
* @param ruleName 规则文件名
* @return 映射成BEAN
* @throws Exception
*/
public static <T> T parseXML(Class<T> clz,InputStream inputStream,String ruleName) throws Exception {
InputStream inputRuleStream = clz.getClassLoader().getResourceAsStream(clz.getPackage().getName().replaceAll("[.]", "/")+"/"+ruleName+".xml");
InputSource source = new InputSource(inputRuleStream);
Digester digester = DigesterLoader.createDigester(source);
try {
return (T)digester.parse(inputStream);
} catch(Exception e) {
throw e;
}
}
/**
* 根据配置文件和规则文件将一个配置文件转换成一个具体的类
* @param <T>
* @param clz
* @param inputStream 配置文件
* @param ruleName 规则文件名
* @return 映射成BEAN
* @throws Exception
*/
public static <T> T parseXML(Class<T> clz,String fileName,String ruleName) throws Exception {
InputStream inputStream = clz.getClassLoader().getResourceAsStream(fileName);
InputStream inputRuleStream = clz.getClassLoader().getResourceAsStream(clz.getPackage().getName().replaceAll("[.]", "/")+"/"+ruleName+".xml");
InputSource source = new InputSource(inputRuleStream);
Digester digester = DigesterLoader.createDigester(source);
try {
return (T)digester.parse(inputStream);
} catch(Exception e) {
throw e;
}
}
}
/**
* @(#)Code.java 0.0.1 2012/06/14
*
* Copyright (c) 2010 SHANGHAI YOUSHINE INFOTECH CO.,LTD
* All rights reserved
*
* This software is the confidential and proprietary information of
* SHANGHAI YOUSHINE.("Confidential Information"). You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with SHANGHAI YOUSHINE.
*/
package com.cesgroup.zw.core.codetable;
public class Code extends CodeBase {
private static final long serialVersionUID = -1899485732327562762L;
public String key;
public String display;
private String displayA;
public String displayB;
public String displayC;
public String displayD;
public String displayE;
public String displayF;
public String displayG;
public String sortA;
public String sortB;
public String sortC;
public String sortD;
public String sortE;
public String sortF;
public String sortG;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getDisplay() {
return display;
}
public void setDisplay(String display) {
this.display = display;
}
public String getDisplayA() {
return displayA;
}
public void setDisplayA(String displayA) {
this.displayA = displayA;
}
public String getDisplayB() {
return displayB;
}
public void setDisplayB(String displayB) {
this.displayB = displayB;
}
public String getDisplayC() {
return displayC;
}
public void setDisplayC(String displayC) {
this.displayC = displayC;
}
public String getDisplayD() {
return displayD;
}
public void setDisplayD(String displayD) {
this.displayD = displayD;
}
public String getDisplayE() {
return displayE;
}
public void setDisplayE(String displayE) {
this.displayE = displayE;
}
public String getDisplayF() {
return displayF;
}
public void setDisplayF(String displayF) {
this.displayF = displayF;
}
public String getDisplayG() {
return displayG;
}
public void setDisplayG(String displayG) {
this.displayG = displayG;
}
public String getSortA() {
return sortA;
}
public void setSortA(String sortA) {
this.sortA = sortA;
}
public String getSortB() {
return sortB;
}
public void setSortB(String sortB) {
this.sortB = sortB;
}
public String getSortC() {
return sortC;
}
public void setSortC(String sortC) {
this.sortC = sortC;
}
public String getSortD() {
return sortD;
}
public void setSortD(String sortD) {
this.sortD = sortD;
}
public String getSortE() {
return sortE;
}
public void setSortE(String sortE) {
this.sortE = sortE;
}
public String getSortF() {
return sortF;
}
public void setSortF(String sortF) {
this.sortF = sortF;
}
public String getSortG() {
return sortG;
}
public void setSortG(String sortG) {
this.sortG = sortG;
}
@Override
public String toString() {
return "Code [key=" + key + ", display=" + display + ", displayA="
+ displayA + ", displayB=" + displayB + ", displayC="
+ displayC + ", displayD=" + displayD + ", displayE="
+ displayE + ", displayF=" + displayF + ", displayG="
+ displayG + ", sortA=" + sortA + ", sortB=" + sortB
+ ", sortC=" + sortC + ", sortD=" + sortD + ", sortE=" + sortE
+ ", sortF=" + sortF + ", sortG=" + sortG + "]";
}
}
/**
* @(#)CodeBase.java 0.0.1 2012/06/14
*
* Copyright (c) 2010 SHANGHAI YOUSHINE INFOTECH CO.,LTD
* All rights reserved
*
* This software is the confidential and proprietary information of
* SHANGHAI YOUSHINE.("Confidential Information"). You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with SHANGHAI YOUSHINE.
*/
package com.cesgroup.zw.core.codetable;
import java.lang.reflect.Field;
public abstract class CodeBase {
public Object getValue(String valueName) throws Exception {
Field f = getClass().getField(valueName);
return f.get(this);
}
public boolean containsValue(String valueName) throws Exception {
Field f = getClass().getField(valueName);
if (f == null) {
return false;
} else {
String filedValue = (String) f.get(this);
if (filedValue == null) {
return false;
} else {
return true;
}
}
}
}
package com.cesgroup.zw.core.codetable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.cesgroup.zw.core.codetable.util.StringUtils;
@SuppressWarnings({"unchecked","rawtypes"})
public class CodeGroup<T> {
private Log log = LogFactory.getLog(CodeGroup.class);
private Object cacheKey = null;
private Map<String, T> codeMap = null;
private String keyField = null;
private Class<T> codeClass = null;
public CodeGroup(Map<String, T> codeMap, Object cacheKey, Class<T> codeClass, String keyField) {
super();
this.codeMap = codeMap;
if (codeMap == null) {
codeMap = new LinkedHashMap<String, T>();
}
this.cacheKey = cacheKey;
this.codeClass = codeClass;
this.keyField = keyField;
}
public Class<T> getCodeClass() {
return codeClass;
}
public String getKeyField() {
return keyField;
}
public String[] getCodeKeys() {
Set<String> keySet = codeMap.keySet();
String[] codeKeys = (String[]) keySet.toArray(new String[0]);
return codeKeys;
}
public T[] getCodes() {
if(null == codeMap || codeMap.values() == null ) {
return (T[])new Object[]{};
}
return (T[])(codeMap.values().toArray());
}
public List<T> getCodes(String valueName,String value) {
List<T> beanList = new ArrayList<T>();
try {
for (T code : getCodes()) {
Field field = null;
field = code.getClass().getDeclaredField(valueName);
field.setAccessible(true);
Object ob = field.get(code);
if (null != ob && String.valueOf(ob).equals(value)) {
beanList.add(code);
}
}
} catch (Exception e) {
log.error("数据转换异常", e);
}
return null;
}
public Map<String, T> getCodeMap(String valueName,String value) {
Map<String, T> beanMap = new HashMap<String, T>();
try {
for (Map.Entry<String, T> code : codeMap.entrySet()) {
Field field = null;
field = code.getValue().getClass().getDeclaredField(valueName);
field.setAccessible(true);
Object ob = field.get(code.getValue());
if (null != ob && String.valueOf(ob).equals(value)) {
beanMap.put(code.getKey(), code.getValue());
}
}
} catch (Exception e) {
log.error("数据转换异常", e);
}
return beanMap;
}
public List<T> getCodes(String valueName) {
List<T> beanList = new ArrayList<T>();
Field field = null;
try {
for (T code : getCodes()) {
if (field == null) {
field = code.getClass().getDeclaredField(valueName);
field.setAccessible(true);
}
if (null != field.get(code)) {
beanList.add(code);
}
}
return beanList;
} catch (Exception e) {
log.error("数据转换异常", e);
}
return beanList;
}
public Object[] getCodeValues(String valueName) {
List<Object> valueList = new ArrayList<Object>();
Field field = null;
try {
for (Object code : getCodes()) {
if (field == null) {
field = code.getClass().getDeclaredField(valueName);
field.setAccessible(true);
}
valueList.add(field.get(code));
}
return valueList.toArray();
} catch (Exception e) {
log.error("数据转换异常", e);
}
return null;
}
public int getCodeCount() {
return codeMap.size();
}
public T getCode(String key) {
if (!containsCode(key)) {
}
return codeMap.get(key);
}
public T getCodeByIndexOf(int index) {
if (getCodeCount() - 1 < index) {
}
return getCodes()[index];
}
public boolean containsCode(String key) {
return codeMap.containsKey(key);
}
public CodeGroup<T> getASC(String valueName) {
return getSortByValueName(valueName, Order.ASC, true);
}
public CodeGroup<T> getASCByNum(String valueName) {
return getSortByValueName(valueName, Order.ASC, false);
}
public CodeGroup<T> getASCSortByValueName(String valueName) {
return getSortByValueName(valueName, Order.ASC, true);
}
public CodeGroup<T> getASCSortByValueNameNum(String valueName) {
return getSortByValueName(valueName, Order.ASC, false);
}
public CodeGroup<T> getDESC(String valueName) {
return getSortByValueName(valueName, Order.DESC, true);
}
public CodeGroup<T> getDESCByNum(String valueName) {
return getSortByValueName(valueName, Order.DESC, false);
}
public CodeGroup<T> getDESCSortByValueName(String valueName) {
return getSortByValueName(valueName, Order.DESC, true);
}
public CodeGroup<T> getDESCSortByValueNameNum(String valueName) {
return getSortByValueName(valueName, Order.DESC, false);
}
private CodeGroup<T> getSortByValueName(String fieldName, Order order, boolean type) {
if(codeMap == null || codeMap.values() == null) {
return this;
}
List<T> cacheList = (List<T>) Arrays.asList(codeMap.values().toArray());
String sortField = StringUtils.isEmpty(fieldName) ? keyField : fieldName;
if (type) {
Collections.sort(cacheList, new FieldObjectComparator<T>(codeClass, sortField, order));
} else {
Collections.sort(cacheList, new FieldNumberComparator<T>(codeClass, sortField, order));
}
Map<String, T> beanMap = new LinkedHashMap<String, T>();
try {
Field field = codeClass.getDeclaredField(keyField);
field.setAccessible(true);
for (T code : cacheList) {
beanMap.put(String.valueOf(field.get(code)), code);
}
} catch (Exception e) {
log.error("数据转换异常", e);
}
return new CodeGroup(beanMap, cacheKey, codeClass, keyField);
}
@Override
public String toString() {
return "CodeGroup [cacheKey=" + cacheKey + ", codeMap=" + codeMap + "]";
}
}
package com.cesgroup.zw.core.codetable;
public interface Context {
public void initMethod() throws Exception;
}
package com.cesgroup.zw.core.codetable;
import java.util.ArrayList;
import java.util.List;
public class DBCodeTable {
private List<Group> groupList = new ArrayList<Group>();
public void addChild(Group group) {
groupList.add(group);
}
public List<Group> getGroupList() {
return groupList;
}
public void setGroupList(List<Group> groupList) {
this.groupList = groupList;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("<xml-code-table-value>\r\n");
for (Group group : groupList) {
sb.append(group);
}
sb.append("</xml-code-table-value>\r\n");
return sb.toString();
}
}
package com.cesgroup.zw.core.codetable;
import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.cesgroup.zw.common.parse.query.ParseQuery;
import com.cesgroup.zw.common.parse.util.DigesterUtil;
@SuppressWarnings({"unchecked","unused"})
public class DBCodeTableMaker {
private Log log = LogFactory.getLog(DBCodeTableMaker.class);
private ParseQuery query;
public DBCodeTableMaker(ParseQuery query) {
this.query = query;
}
public DBCodeTable makeDBCodeTable(String dbCodeDef) throws Exception {
try{
File file = new File(getClass().getClassLoader().getResource(dbCodeDef).getFile());
return DigesterUtil.parseXML(DBCodeTable.class, file, "db-code-table-define-Rule");
} catch(Exception e){
log.error("",e);
throw new Exception(e);
}
}
public DBCodeTable makeDBCodeTable(InputStream inputStream) throws Exception {
try{
return DigesterUtil.parseXML(DBCodeTable.class, inputStream, "db-code-table-define-Rule");
}catch(Exception e){
log.error("",e);
throw new Exception(e);
}
}
public <T extends Object> Map<String, T> createDbCodeGroup(
String dbCodeFile, Class<T> clazz, String key, String keyField)
throws Exception {
DBCodeTable codeTable = makeDBCodeTable(dbCodeFile);
for (Group group : codeTable.getGroupList()) {
if (null == group.getName() || "".equals(group.getName())
|| null == group.getSql()) {
continue;
}
return createDbCodeGroup(group, group.getClazz(), key, keyField);
}
return null;
}
public <T extends Object> Map<String, T> createDbCodeGroup(Group group,
Class<T> clazz, String key, String keyField) throws Exception {
List<Map<String, Object>> beanMapList = new ArrayList<Map<String, Object>>();
List<ValueMapping> valueMappingList = group.getValueMappingList();
String groupName = group.getName();
String sql = group.getSql();
if ((null != groupName && key.equals(groupName)) && null != sql) {
Map<String, Object> paramMap = new HashMap<String, Object>();
beanMapList = query.queryForList(sql);
List<Map<String, Object>> tempList = new ArrayList<Map<String, Object>>();
for (Map<String, Object> beanMap : beanMapList) {
tempList.add(replaceBeanMapKey(beanMap, valueMappingList));
}
List<T> codeList = new ArrayList<T>();
for (Map<String, Object> beanMap : tempList) {
T codeClass = clazz.newInstance();
Field[] fields = clazz.getDeclaredFields();
for(Field field:fields) {
if(beanMap.containsKey(field.getName())) {
field.setAccessible(true);
field.set(codeClass, beanMap.get(field.getName()));
}
}
codeList.add(codeClass);
}
return beanListToMap(codeList, clazz, keyField);
}
return null;
}
private Map<String, Object> replaceBeanMapKey(Map<String, Object> beanMap,
List<ValueMapping> valueMappingList) {
Map<String, Object> tempBeanMap = new HashMap<String, Object>();
for (ValueMapping valueMapping : valueMappingList) {
String valueName = valueMapping.getName();
String valueField = valueMapping.getField();
Object value = beanMap.get(valueName);
tempBeanMap.put(valueField, value);
}
return tempBeanMap;
}
private <T extends Object> Map<String, T> beanListToMap(List<T> beanList,
Class<T> clazz, String keyField) {
Map<String, T> map = new LinkedHashMap<String, T>();
try {
Field field = clazz.getDeclaredField(keyField);
field.setAccessible(true);
for (T bean : beanList) {
map.put(field.get(bean).toString(), bean);
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
}
package com.cesgroup.zw.core.codetable;
import java.lang.reflect.Field;
import java.util.Comparator;
public abstract class FieldComparator<T> implements Comparator<T> {
protected Class<T> clazz;
protected Field field;
protected String sortFieldName;
protected Order order = Order.ASC;
public FieldComparator(Class<T> clazz, String sortFieldName) {
super();
this.clazz = clazz;
this.sortFieldName = sortFieldName;
init();
}
public FieldComparator(Class<T> clazz, String sortFieldName, Order order) {
super();
this.clazz = clazz;
this.sortFieldName = sortFieldName;
this.order = order;
init();
}
private void init() {
try {
field = clazz.getDeclaredField(sortFieldName);
} catch (Exception e) {
}
field.setAccessible(true);
}
}
package com.cesgroup.zw.core.codetable;
@SuppressWarnings({"unchecked","rawtypes"})
public class FieldNumberComparator<T> extends FieldComparator<T> {
public FieldNumberComparator(Class<T> clazz, String sortFieldName) {
super(clazz, sortFieldName);
}
public FieldNumberComparator(Class<T> clazz, String sortFieldName, Order order) {
super(clazz, sortFieldName, order);
}
public int compare(T o1, T o2) {
if (o1 == null || o2 == null) {
return 1;
}
Object _o1 = null;
Object _o2 = null;
try {
_o1 = field.get( o1);
_o2 = field.get(o2);
} catch (Exception e1) {
}
if (_o1 == null || _o2 == null) {
return 1;
}
Double d1 = null;
Double d2 = null;
try {
d1 = Double.valueOf(_o1.toString());
d2 = Double.valueOf(_o2.toString());
} catch (NumberFormatException e) {
}
return ((Comparable) d1).compareTo((Comparable) d2) * order.getSort();
}
}
package com.cesgroup.zw.core.codetable;
@SuppressWarnings({"unchecked","rawtypes"})
public class FieldObjectComparator<T> extends FieldComparator<T> {
public FieldObjectComparator(Class<T> clazz, String sortFieldName) {
super(clazz, sortFieldName);
}
public FieldObjectComparator(Class<T> clazz, String sortFieldName, Order order) {
super(clazz, sortFieldName, order);
}
public int compare(T o1, T o2) {
if (o1 == null || o2 == null) {
return 0;
}
Object _o1 = null;
Object _o2 = null;
try {
_o1 = field.get( o1);
_o2 = field.get( o2);
} catch (Exception e) {
}
if (_o1 == null || _o2 == null) {
return 0;
}
return ((Comparable) _o1).compareTo((Comparable) _o2) * order.getSort();
}
}
package com.cesgroup.zw.core.codetable;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings({"rawtypes"})
public class Group {
private String name;
private String sql;
private String ibatisId;
private Class clazz;
private KeyMapping keyMapping;
private List<ValueMapping> valueMappingList = new ArrayList<ValueMapping>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIbatisId() {
return ibatisId;
}
public void setIbatisId(String ibatisId) {
this.ibatisId = ibatisId;
}
public Class getClazz() {
return clazz;
}
public void setClassName(String className) {
try {
this.clazz =Class.forName(className);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public KeyMapping getKeyMapping() {
return keyMapping;
}
public void setKeyMapping(KeyMapping keyMapping) {
this.keyMapping = keyMapping;
}
public void addChild(ValueMapping valueMapping) {
valueMappingList.add(valueMapping);
}
public List<ValueMapping> getValueMappingList() {
return valueMappingList;
}
public void setValueMappingList(List<ValueMapping> valueMappingList) {
this.valueMappingList = valueMappingList;
}
private List<Code> codeList = new ArrayList<Code>();
public void addChild(Code code) {
codeList.add(code);
}
public List<Code> getCodeList() {
return codeList;
}
public void setCodeList(List<Code> codeList) {
this.codeList = codeList;
}
public String getSql() {
return sql;
}
public void setSql(String sql) {
this.sql = sql;
}
}
package com.cesgroup.zw.core.codetable;
public class KeyMapping {
private String field;
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
}
package com.cesgroup.zw.core.codetable;
public enum Order{
ASC(1),DESC(-1);
int sort;
private Order(int sort){
this.sort = sort;
}
public int getSort(){
return sort;
}
}
\ No newline at end of file
package com.cesgroup.zw.core.codetable;
public class ValueMapping {
private String field;
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.cesgroup.zw.core.codetable.parse.impl;
import java.util.Map;
import com.cesgroup.zw.common.parse.ParameterParse;
import com.cesgroup.zw.common.parse.Parse;
public class CodeTableParameterParseImpl extends Parse implements ParameterParse {
public Object parse(String expression, Map<String, Object> context,
Object[] params) {
return "";
}
public Type getType() {
return Type.CODE_TABLE;
}
}
package com.cesgroup.zw.core.codetable.query;
import com.cesgroup.zw.common.parse.query.ParseQuery;
public interface IQuery extends ParseQuery {
}
package com.cesgroup.zw.core.codetable.query.impl;
import java.util.List;
import java.util.Map;
import com.cesgroup.zw.core.codetable.query.IQuery;
public class DefaultCodeTableQueryImpl implements IQuery {
public List<Map<String, Object>> queryForList(String sql) {
return null;
}
public int insert(String sql, Object[] params) {
// TODO Auto-generated method stub
return 0;
}
public int update(String sql, Object[] params) {
// TODO Auto-generated method stub
return 0;
}
public int execute(String sql, Object[] params) {
// TODO Auto-generated method stub
return 0;
}
public long insertAndGetKey(String sql) {
// TODO Auto-generated method stub
return 0;
}
public long count(String sql, Object[] params) {
// TODO Auto-generated method stub
return 0;
}
}
package com.cesgroup.zw.core.codetable.util;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.cesgroup.zw.core.codetable.CodeGroup;
import com.cesgroup.zw.core.codetable.CodeTableCache;
public class CodeTableUtil {
private static Log logger = LogFactory.getLog(CodeTableUtil.class);
/**
* 根据主键从业务字典取得相应的对象
* @param <T>
* @param clz
* @param groupName
* @param primaryId
* @return
*/
public static <T> T getCodeByKey(Class<T> clz,String groupName,String primaryId) {
CodeTableCache codeTableCache = CodeTableCache.getInstance();
try {
return codeTableCache.getGroup(groupName,clz).getCode(primaryId);
} catch (Exception e) {
logger.error( e.getMessage(),e);
}
return null;
}
/**
* 根据主键从业务字典取得相应的对象
* @param <T>
* @param clz
* @param groupName
* @param primaryId
* @return
*/
public static Object getCodeByKey(String groupName,String primaryId) {
CodeTableCache codeTableCache = CodeTableCache.getInstance();
try {
return codeTableCache.getGroup(groupName).getCode(primaryId);
} catch (Exception e) {
logger.error( e.getMessage(),e);
}
return null;
}
public static Object[] getCodeValues(String groupName,String valueName) {
CodeTableCache codeTableCache = CodeTableCache.getInstance();
try {
CodeGroup group = codeTableCache.getGroup(groupName);
return group.getCodeValues(valueName);
} catch (Exception e) {
}
return null;
}
/**
* 根据组名称从业务字典取得相应的对象
* @param <T>
* @param clz
* @param groupName
* @return
*/
public static <T> List<T> getGroupByName(Class<T> clz,String groupName) {
List<T> dataList = new ArrayList<T>();
CodeTableCache codeTableCache = CodeTableCache.getInstance();
try {
CodeGroup<T> group = codeTableCache.getGroup(groupName,clz);
for(T t:group.getCodes()) {
dataList.add(t);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dataList;
}
/**
* 根据组名称和相应的字段值从业务字典取得相应的对象
* @param <T>
* @param clz
* @param groupName 业务字典的组名
* @param valueName 相应的字段
* @param value 相应的字段的值
* @param isSystemData 支付类型【是否系统主句状态 系统数据时:不可删除】(true:系统数据 false非系统数据)
* @return
* @throws Exception
*/
public static <T> Collection<T> getGroupByNameSelective(Class<T> clz,String groupName,String valueName,String value,boolean isSystemData) throws Exception {
CodeTableCache codeTableCache = CodeTableCache.getInstance();
// 根据组名取得相应的组信息
CodeGroup<T> group = codeTableCache.getGroup(groupName,clz);
Map<String,T> result = new HashMap<String,T>();
// 根据过滤条件取得相应的数据
Map<String, T> dataMap = group.getCodeMap(valueName, value);
if(null != dataMap) {
result.putAll(dataMap);
}
if(isSystemData) {
// 根据过滤条件取得相应的数据
dataMap = group.getCodeMap("isSystemData", "0");
if(null != dataMap) {
result.putAll(dataMap);
}
}
return result.values();
}
@SuppressWarnings("unchecked")
public static <T> T[] getCodes( T[] codes,String valueName,String value) {
Class<T> clz = null;
List<T> list = new ArrayList<T>();
try {
for (T ob:codes) {
clz = (Class<T>) ob.getClass();
Field field = null;
field = ob.getClass().getDeclaredField(valueName);
field.setAccessible(true);
Object val = field.get(ob);
if (null != val && String.valueOf(val).equals(value)) {
list.add(ob);
}
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
if(!list.isEmpty()) {
T[] tt = (T[]) Array.newInstance(clz, list.size());
return list.toArray(tt);
} else {
return null;
}
}
public static <T> List<T> getCodeByNameAndFieldName(Class<T> clz,String groupName,String fieldName,Object fieldValue) throws Exception{
List<T> list=CodeTableUtil.getGroupByName(clz, groupName);
return ConvertUtil.groupByFieldName(fieldName,list).get(fieldValue);
}
public static Object getFieldValueByKey(String groupName, String enterpriseId,
String fieldName) throws Exception {
Object obj=CodeTableUtil.getCodeByKey(groupName, enterpriseId);
if(obj==null)
return null;
return FieldUtil.getValue(obj, fieldName);
}
}
package com.cesgroup.zw.core.codetable.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class ConvertUtil {
/**
* 根据fieldName的值进行分组
* @param <T>
* @param clz
* @param fieldName 分组的关键字
* @param dataList 要分组的集合
* @return
* @throws Exception
*/
public static <T> Map<Object,List<T>> groupByFieldName(Class<T> clz,String fieldName,List<T> dataList) throws Exception {
Map<Object,List<T>> map = new HashMap<Object,List<T>>();
for(T bean:dataList) {
// 取出到分组的值
Object value = FieldUtil.getValue(bean, fieldName);
List<T> list = map.get(value);
if(null == list) {
list = new ArrayList<T>();
map.put(value, list);
}
list.add(bean);
}
return map;
}
/**
* 根据fieldName的值进行分组
* @param <T>
* @param clz
* @param fieldName 分组的关键字
* @param dataList 要分组的集合
* @return
* @throws Exception
*/
public static <T> Map<Object,T> groupByField(Class<T> clz,String fieldName,List<T> dataList) throws Exception {
Map<Object,T> map = new HashMap<Object,T>();
for(T bean:dataList) {
// 取出到分组的值
Object value = FieldUtil.getValue(bean, fieldName);
map.put(value, bean);
}
return map;
}
/**
* 根据fieldName的值进行分组
* @param <T>
* @param fieldName 分组的关键字
* @param dataList 要分组的集合
* @return
* @throws Exception
*/
public static <T> Map<Object,T> groupByField(String fieldName,List<T> dataList) throws Exception {
Map<Object,T> map = new HashMap<Object,T>();
for(T bean:dataList) {
// 取出到分组的值
Object value = FieldUtil.getValue(bean, fieldName);
map.put(value, bean);
}
return map;
}
/**
* 根据fieldName的值进行分组,按key排序
* @param <T>
* @param fieldName 分组的关键字
* @param dataList 要分组的集合
* @return
* @throws Exception
*/
public static <T> Map<Object,T> groupByFieldSort(String fieldName,List<T> dataList) throws Exception {
Map<Object,T> map = new LinkedHashMap<Object,T>();
for(T bean:dataList) {
// 取出到分组的值
Object value = FieldUtil.getValue(bean, fieldName);
map.put(value, bean);
}
return map;
}
/**
* map 转换为List
* @param <T>
* @param clz
* @param fieldName 分组的关键字
* @param dataList 要分组的集合
* @return
*/
public static <T> List<T> mapToList(Map<Object,T> map){
List<T> list = new ArrayList<T>();
for(Map.Entry<Object,T> entry :map.entrySet()) {
// 取出到分组的值
T value = entry.getValue();
list.add(value);
}
return list;
}
/**
* map 转换为List
* @param <T>
* @param clz
* @param fieldName 分组的关键字
* @param dataList 要分组的集合
* @return
*/
public static <T> List<T> mapListToList(Map<String,List<T>> map){
List<T> list = new ArrayList<T>();
for(Map.Entry<String,List<T>> entry :map.entrySet()) {
// 取出到分组的值
List<T> value = entry.getValue();
list.addAll(value);
}
return list;
}
public static <T> Map<Object, List<T>> groupByFieldName(String fieldName,
List<T> dataList) throws Exception {
Map<Object, List<T>> map = new HashMap<Object, List<T>>();
for (T bean : dataList) {
// 取出到分组的值
String[] fieldNames = fieldName.split("\\.");
Object value = bean;
for (String fn : fieldNames) {
value = FieldUtil.getValue(value, fn);
}
List<T> list = map.get(value);
if (null == list) {
list = new ArrayList<T>();
map.put(value, list);
}
list.add(bean);
}
return map;
}
public static <T> Map<Object, List<T>> groupByFieldName(
List<T> dataList,String ... fieldName) throws Exception {
Map<Object, List<T>> map = new HashMap<Object, List<T>>();
for (T bean : dataList) {
// 取出到分组的值
String key="";
for(String fn:fieldName){
String[] fieldNames = fn.split("\\.");
Object value = bean;
for (String fName : fieldNames) {
value = FieldUtil.getValue(value, fName);
}
key+=value;
}
List<T> list = map.get(key);
if (null == list) {
list = new ArrayList<T>();
map.put(key, list);
}
list.add(bean);
}
return map;
}
/**
* @author LinXiaodong
* @createDate 2013-12-17
* @param str
* @param splitFlg
* @Desc 将String 转换成 String[]
* @return
*/
public static String[] strConvertToArray(String str,String splitFlg){
String[] array = null;
if(str != null && str !=""){
if(str.indexOf(splitFlg) > 0){
array = str.split(",");
}else{
array = new String[]{str};
}
}
return array;
}
}
package com.cesgroup.zw.core.codetable.util;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* 类变量共通类
* @author Roger
* @version 1.0
*/
public class FieldUtil {
/**
* 取得一个实例的变量的值
* @param ob 类实例
* @param fieldNm 类实例的变量名
* @return 指定变量的值
* @throws Exception
*/
public static Object getValue(Object ob,String fieldNm) throws Exception {
// 类实例为空,返回NULL
if(null == ob){
return null;
}
Field field = null;
try {
// 取得申名的变量名
field = getDeclaredField(ob,fieldNm);
field.setAccessible(true);
return field.get(ob);
} catch (Exception e) {
throw e;
}
}
public static Field getDeclaredField(Object object, String fieldName){
Field field = null ;
Class<?> clazz = object.getClass() ;
for(; clazz != Object.class ; clazz = clazz.getSuperclass()) {
try {
field = clazz.getDeclaredField(fieldName) ;
return field ;
} catch (Exception e) {
}
}
return null;
}
/**
*
* @param o
* @param fieldName
* @return
* @throws Exception
*/
public static Object getFieldValueByName( Object o,String fieldName) throws Exception {
try {
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String getter = "get" + firstLetter + fieldName.substring(1);
Method method = o.getClass().getMethod(getter, new Class[] {});
Object value = method.invoke(o, new Object[] {});
return value;
} catch (Exception e) {
throw e;
}
}
/**
* 对指定的实例对象设定其变量的值
* @param ob 类实例
* @param fieldNm 类实例的变量名
* @param value
* @throws Exception
*/
public static void setValue(Object ob,String fieldNm,Object value) throws Exception {
// 类实例为空,返回NULL
if(null == ob){
return ;
}
Field field = null;
try {
// 取得申名的变量名
field = ob.getClass().getDeclaredField(fieldNm);
field.setAccessible(true);
field.set(ob,value);
} catch (Exception e) {
throw e;
}
}
public static Map<String,String> getStringFileds(Object ob) {
Map<String,String> map = new HashMap<String,String>();
try{
BeanInfo beanInfo = Introspector.getBeanInfo(ob.getClass());
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
for(PropertyDescriptor pd : pds)
{
Method method = pd.getReadMethod();
if(method.getReturnType().equals(String.class)) {
map.put(pd.getName(), (String)method.invoke(ob)) ;
}
}
}catch(Exception e) {
}
return map;
}
/**
* 取得所有BEAN属性
* @param ob
* @return
*/
public static <T> Map<String,Object> getFileds(Class<T> clz,Object ob) {
Map<String,Object> map = new HashMap<String,Object>();
try{
BeanInfo beanInfo = Introspector.getBeanInfo(ob.getClass());
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
for(PropertyDescriptor pd : pds)
{
if(!StringUtils.equals(pd.getName(), "class")) {
Method method = pd.getReadMethod();
map.put(pd.getName(), method.invoke(ob)) ;
}
}
}catch(Exception e) {
}
return map;
}
/**
* 取得所有BEAN属性
* @param ob
* @return
*/
public static <T> Map<String,Method> getFileds(Class<T> clz) {
Map<String,Method> map = new HashMap<String,Method>();
try{
BeanInfo beanInfo = Introspector.getBeanInfo(clz);
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
for(PropertyDescriptor pd : pds)
{
if(!StringUtils.equals(pd.getName(), "class")) {
map.put(pd.getName(),pd.getWriteMethod());
}
}
}catch(Exception e) {
}
return map;
}
/**
* 取得一个实例的父类的变量的值
* @param ob 类实例
* @param fieldNm 类实例的变量名
* @return 指定变量的值
* @throws Exception
*/
public static Object getSuperValue(Object ob,String fieldNm) throws Exception {
// 类实例为空,返回NULL
if(null == ob){
return null;
}
Field field = null;
try {
// 取得申名的变量名
field = ob.getClass().getSuperclass().getDeclaredField(fieldNm);
field.setAccessible(true);
return field.get(ob);
} catch (Exception e) {
throw e;
}
}
}
package com.cesgroup.zw.core.codetable.xml;
import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import com.cesgroup.zw.core.codetable.Code;
import com.cesgroup.zw.core.codetable.util.StringUtils;
public class CodeTableXml {
protected CodeTableXmlHandler handler;
protected XmlNode root;
protected ClassLoader classLoader;
protected int retryCount;
protected long lastModified;
private File xmlFile;
private InputStream xmlStream;
private boolean isDynamicLoad;
public CodeTableXml(String filepath) {
this(filepath, 3, false);
}
public CodeTableXml(InputStream xmlStream) {
this(xmlStream, 3, false);
}
public CodeTableXml(String filepath, boolean isOgnl) {
this(filepath, 3, isOgnl);
}
public CodeTableXml(String filepath, int retryCount, boolean isOgnl) {
if (this.xmlFile == null) {
this.xmlStream = this.getClass().getClassLoader().getResourceAsStream(filepath);
}
this.retryCount = retryCount;
this.handler = new CodeTableXmlHandler(isOgnl);
this.isDynamicLoad = false;
this.load();
}
public CodeTableXml(InputStream xmlStream, int retryCount, boolean isOgnl) {
if (this.xmlStream == null) {
this.xmlStream = xmlStream;
}
this.retryCount = retryCount;
this.handler = new CodeTableXmlHandler(isOgnl);
this.isDynamicLoad = false;
this.load();
}
public XmlNode getRootNode() {
this.update(0);
return this.root;
}
public void setDynamicLoad(boolean isDynamicLoad) {
this.isDynamicLoad = isDynamicLoad;
}
public <T extends Object> List<T> copyToBean(String xpath, Class<T> clazz) {
return this.copyToBean(xpath, clazz, null);
}
public <T extends Object> List<T> copyToBean(String xpath, Class<T> clazz, String attName) {
List<T> beanList = new ArrayList<T>();
try {
List<XmlNode> nodeList =
this.getRootNode().getNodeListByXPath(xpath);
Field[] fields = clazz.getDeclaredFields();
for (XmlNode node : nodeList) {
List<XmlNode> children = node.getChildren();
T bean = clazz.newInstance();
for (Field field : fields) {
field.setAccessible(true);
List<XmlNode> selectedChildren =
node.getChildren(field.getName());
if (selectedChildren != null && selectedChildren.size() > 0) {
field.set( bean, selectedChildren.get(0).getValue());
} else if (node.getAttributes().containsKey(field.getName())) {
field.set(bean, node.getAttributes().get(field.getName()));
} else if (StringUtils.isNotEmpty(attName)) {
for (XmlNode child : children) {
if (StringUtils.equals(
child.getAttributes().get(attName),
field.getName())) {
field.set(bean, child.getValue());
}
}
}
}
beanList.add(bean);
}
} catch (Exception e) {
}
return beanList;
}
public <T extends Object> Map<String, T> copyToBeanMap(String xpath, Class<T> clazz, String keyField) {
return this.copyToBeanMap(xpath, clazz, null, keyField);
}
public <T extends Object> Map<String, T> copyToBeanMap(String xpath, Class<T> clazz, String attName, String keyField) {
List<T> beanList = this.copyToBean(xpath, clazz, attName);
return beanListToMap(beanList, clazz, keyField);
}
public List<XMLGroup> getXMLGroupList() throws Exception {
List<XMLGroup> xmlList = new ArrayList<XMLGroup>();
if(null != this.getRootNode()) {
List<XmlNode> list = this.getRootNode().getChildren();
if(null != list && !list.isEmpty()) {
for(XmlNode node:list) {
XMLGroup xmlGroup = new XMLGroup();
xmlGroup.setPrimaryField(node.getAttributes().get("primaryField"));
xmlGroup.setGroupName(node.getAttributes().get("name"));
xmlGroup.setXpath("group@name("+xmlGroup.getGroupName()+")/code");
String xmlGroupClazzName = Code.class.getName();
if(null != node.getChildren("code-table-class") && !node.getChildren("code-table-class").isEmpty()) {
xmlGroupClazzName = (String) node.getChildren("code-table-class").get(0).getValue();
}
if(null == xmlGroupClazzName) {
xmlGroupClazzName = Code.class.getName();
}
xmlGroup.setClazz(Class.forName(xmlGroupClazzName));
xmlList.add(xmlGroup);
}
}
}
return xmlList;
}
static <T extends Object> Map<String, T> beanListToMap(List<T> beanList,Class<T> clazz,String keyField){
try {
Map<String, T> beanMap = new LinkedHashMap<String, T>();
Field field = clazz.getDeclaredField(keyField);
field.setAccessible(true);
for (T bean : beanList) {
beanMap.put((String)field.get(bean), bean);
}
return beanMap;
} catch (Exception e) {
}
return null;
}
public boolean isUpdate() {
if (this.xmlFile == null) {
return false;
}
return this.isDynamicLoad &&
this.lastModified < this.xmlFile.lastModified();
}
protected void load() {
synchronized (this) {
try {
SAXParserFactory spfactory = SAXParserFactory.newInstance();
SAXParser parser = spfactory.newSAXParser();
this.handler.initialize();
if (this.xmlFile != null &&
this.xmlFile.exists() && this.xmlFile.isFile()) {
parser.parse(this.xmlFile, this.handler);
this.root = this.handler.getRootNode();
} else if (this.xmlStream != null) {
parser.parse(this.xmlStream, this.handler);
this.root = this.handler.getRootNode();
}
} catch (Exception e) {
}
}
}
private void update(int retry) {
if (this.isUpdate()) {
try {
this.load();
} catch (Exception e) {
if (retry < this.retryCount) {
this.update(retry+1);
return;
}
}
this.lastModified = (this.xmlFile == null) ?
0L : this.xmlFile.lastModified();
}
}
}
package com.cesgroup.zw.core.codetable.xml;
import java.util.Stack;
import ognl.Ognl;
import ognl.OgnlContext;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class CodeTableXmlHandler extends DefaultHandler {
protected boolean isOgnl = false;
protected Stack<XmlNode> nodeStack;
protected XmlNode root;
protected OgnlContext context;
public CodeTableXmlHandler(boolean isOgnl) {
this.isOgnl = isOgnl;
this.initialize();
}
public void initialize() {
this.nodeStack = null;
this.root = null;
if (this.isOgnl) {
this.context = new OgnlContext();
}
}
public XmlNode getRootNode() {
return this.root;
}
@Override
public void startDocument() throws SAXException {
this.nodeStack = new Stack<XmlNode>();
}
@Override
public void endDocument() throws SAXException {
//NOP
}
@Override
public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
XmlNode node = new XmlNode(name);
int attributeLength = attributes.getLength();
for (int i = 0; i < attributeLength; i++) {
node.addAttribute(attributes.getQName(i), attributes.getValue(i));
}
if (this.root == null) {
this.root = node;
} else {
XmlNode parent = this.nodeStack.peek();
parent.addChild(node);
node.setParent(parent);
}
this.nodeStack.push(node);
}
@Override
public void endElement(String uri, String localName, String name) throws SAXException {
XmlNode node = this.nodeStack.pop();
Object nodeValue = node.getValue();
if (nodeValue != null) {
String nodeValueString = nodeValue.toString().trim();
if (this.isOgnl &&
!nodeValueString.startsWith("<") && !nodeValueString.endsWith(">")) {
Object obj = null;
try {
Object parseExpression = Ognl.parseExpression(nodeValue.toString());
} catch (Exception e) {
}
node.setValue(obj);
} else {
node.setValue(nodeValueString);
}
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
XmlNode node = this.nodeStack.peek();
if (node.getValue() == null) {
node.setValue(new String(ch, start, length));
} else {
node.setValue(node.getValue() + new String(ch, start, length));
}
}
}
package com.cesgroup.zw.core.codetable.xml;
public class XMLGroup {
private String xpath;
private String groupName;
private Class<?> clazz;
private String primaryField;
public String getXpath() {
return xpath;
}
public void setXpath(String xpath) {
this.xpath = xpath;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public Class<?> getClazz() {
return clazz;
}
public void setClazz(Class<?> clazz) {
this.clazz = clazz;
}
public String getPrimaryField() {
return primaryField;
}
public void setPrimaryField(String primaryField) {
this.primaryField = primaryField;
}
}
package com.cesgroup.zw.core.codetable.xml;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import com.cesgroup.zw.core.codetable.util.StringUtils;
@SuppressWarnings("unchecked")
public class XmlNode {
private static final long serialVersionUID = -2224946250718469933L;
private static final Pattern VAL_PATTERN = Pattern.compile("[^@]+\\(.+\\)");
private static final Pattern ATT_PATTERN = Pattern.compile(".+@.+\\(.+\\)");
protected String name;
protected Object value;
protected Map<String, String> attributes;
protected List<XmlNode> children;
protected XmlNode parent;
public XmlNode(String name) {
this.name = name;
this.attributes = new LinkedHashMap<String, String>();
this.children = new ArrayList<XmlNode>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Object getValue() {
return value;
}
public <T extends Object> T getValue(Class<T> clazz) {
return (T)value;
}
public void setValue(Object value) {
this.value = value;
}
public Map<String, String> getAttributes() {
return attributes;
}
public void setAttributes(Map<String, String> attributes) {
this.attributes = attributes;
}
public void addAttribute(String name, String value) {
this.attributes.put(name, value);
}
public List<XmlNode> getChildren() {
return children;
}
public List<XmlNode> getChildren(String qname) {
List<XmlNode> childList = new ArrayList<XmlNode>();
for (XmlNode node : this.children) {
if (node.getName().equals(qname)) {
childList.add(node);
}
}
return childList;
}
public List<XmlNode> getChildrenByValue(String qname, Object value) {
List<XmlNode> childList = new ArrayList<XmlNode>();
for (XmlNode node : this.children) {
if (node.getName().equals(qname) &&
StringUtils.equals((String)node.getValue(), (String)value)) {
childList.add(node);
}
}
return childList;
}
public List<XmlNode> getChildrenByAttribute(String qname, String name, String value) {
List<XmlNode> childList = new ArrayList<XmlNode>();
for (XmlNode node : this.children) {
if (node.getName().equals(qname) &&
StringUtils.equals((String)node.getAttributes().get(name), value)) {
childList.add(node);
}
}
return childList;
}
public void addChild(XmlNode child) {
this.children.add(child);
}
public XmlNode getParent() {
return parent;
}
public void setParent(XmlNode parent) {
this.parent = parent;
}
public List<XmlNode> getNodeListByXPath(String xpath) {
List<XmlNode> nodeList = new ArrayList<XmlNode>();
if (xpath == null) {
return nodeList;
}
List<XmlNode> xmlNodeList = this.getChildren();
//String[] paths = xpath.split("[/]");
for(XmlNode xmlNode:xmlNodeList) {
if("group".equals(xmlNode.getName())) {
List<XmlNode> codeXmlNodes = xmlNode.getChildren();
String tempPath = xmlNode.getName() + "@name("+xmlNode.getAttributes().get("name")+")";
if(xpath.startsWith(tempPath)) {
for(XmlNode codeNode:codeXmlNodes) {
if("code".equals(codeNode.getName())) {
nodeList.add(codeNode);
}
}
}
}
}
return nodeList;
}
}
<?xml version="1.0"?>
<digester-rules>
<pattern value="db-code-table-value"> 
<object-create-rule classname="com.cesgroup.zw.core.codetable.DBCodeTable"/>
<pattern value="group">
<object-create-rule classname="com.cesgroup.zw.core.codetable.Group"/>
<set-next-rule methodname="addChild"/>
<set-properties-rule/>
<pattern value="sql">
<call-method-rule methodname="setSql" paramcount="0"/>
</pattern>
<pattern value="code-table-class">
<call-method-rule methodname="setClassName" paramcount="0"/>
</pattern>
<pattern value="key-mapping">
<object-create-rule classname="com.cesgroup.zw.core.codetable.KeyMapping"/>
<set-next-rule methodname="setKeyMapping"/>
<set-properties-rule/>
</pattern>
<pattern value="value-mapping">
<object-create-rule classname="com.cesgroup.zw.core.codetable.ValueMapping"/>
<set-next-rule methodname="addChild"/>
<set-properties-rule/>
</pattern>
</pattern>    
</pattern>  
</digester-rules>
package com.cesgroup.core.codetable;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import com.cesgroup.zw.core.codetable.CodeTableCache;
public class CodeTableCacheTest {
@Test
public void codeTable() throws Exception {
CodeTableCache XML_CODE_TABLE = CodeTableCache.getInstance();
List<String> list = new ArrayList<String>();
list.add("/codetable/xml-code-table-value.xml");
loadXmlData(list,XML_CODE_TABLE);
System.out.println(XML_CODE_TABLE.getGroup("SITE_BAR11"));
XML_CODE_TABLE = CodeTableCache.getInstance();
list = new ArrayList<String>();
list.add("/codetable/xml-code-table-value1.xml");
loadXmlData(list,XML_CODE_TABLE);
System.out.println(XML_CODE_TABLE.getGroup("SITE_BAR22"));
System.out.println(XML_CODE_TABLE.getGroup("SITE_BAR33"));
System.out.println(XML_CODE_TABLE.getGroup("SITE_BAR11"));
System.out.println(XML_CODE_TABLE.getGroup("SITE_BAR"));
XML_CODE_TABLE.reload("SITE_BAR33");
System.out.println("TESt");
System.out.println(XML_CODE_TABLE.getGroup("SITE_BAR"));
}
private void loadXmlData(List<String> list,CodeTableCache XML_CODE_TABLE) {
InputStream[] xmlCodeInputStreams = new InputStream[list.size()];
for(int i =0 ;i < list.size();i++) {
xmlCodeInputStreams[i] = CodeTableCacheTest.class.getResourceAsStream(list.get(i));
}
XML_CODE_TABLE.setXmlCodeInputStreams(xmlCodeInputStreams);
try {
XML_CODE_TABLE.loadData();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void dbCodeTable() throws Exception {
CodeTableCache XML_CODE_TABLE = CodeTableCache.getInstance();
List<String> list = new ArrayList<String>();
list.add("/codetable/db-code-table-define.xml");
loadDBData(list,XML_CODE_TABLE);
System.out.println(XML_CODE_TABLE.getGroup("SEC_USER"));
}
private void loadDBData(List<String> list,CodeTableCache XML_CODE_TABLE) {
InputStream[] dbCodeInputStreams = new InputStream[list.size()];
for(int i =0 ;i < list.size();i++) {
dbCodeInputStreams[i] = CodeTableCacheTest.class.getResourceAsStream(list.get(i));
}
XML_CODE_TABLE.setDbCodeInputStreams(dbCodeInputStreams);
try {
XML_CODE_TABLE.loadData();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<db-code-table-value>
<group name="SEC_USER">
<sql>
select * from user where del_flag = '0'
</sql>
<code-table-class>com.cesgroup.zw.core.codetable.Code</code-table-class>
<key-mapping field="key"/>
<value-mapping name="user_id" field="key"/>
<value-mapping name="user_name" field="display"/>
</group>
</db-code-table-value>
<?xml version="1.0" encoding="UTF-8"?>
<xml-code-table-value>
<group name="SITE_BAR" primaryField="key">
<code-table-class>com.cesgroup.zw.core.codetable.Code</code-table-class>
<code key="0000">
<display>5666</display>
<displayA>64</displayA>
<sortA>1</sortA>
</code>
<code key="00001">
<display>null</display>
<displayA>64</displayA>
<sortA>1</sortA>
</code>
</group>
<group name="SITE_BAR11" primaryField="key">
<code key="1111">
<display>null</display>
</code>
<code key="1122">
<display>null</display>
</code>
</group>
</xml-code-table-value>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<xml-code-table-value>
<group name="SITE_BAR22" primaryField="key">
<code-table-class>com.cesgroup.zw.core.codetable.Code</code-table-class>
<code key="222">
<display>5666</display>
<displayA>64</displayA>
<sortA>1</sortA>
</code>
<code key="2222">
<display>null</display>
<displayA>64</displayA>
<sortA>1</sortA>
</code>
</group>
<group name="SITE_BAR33" primaryField="key">
<code key="3333">
<display>null</display>
</code>
<code key="33333">
<display>null</display>
</code>
</group>
</xml-code-table-value>
\ No newline at end of file
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cesgroup.zw.spring.boot</groupId>
<artifactId>codetable-spring-boot</artifactId>
<version>1.0.0.RELEASE</version>
<packaging>pom</packaging>
<distributionManagement>
<repository>
<id>nexus-releases</id>
<name>Nexus Release Repository</name>
<url>http://180.168.156.212:2905/repository/maven-releases</url>
</repository>
<snapshotRepository>
<id>nexus-snapshots</id>
<name>Nexus Snapshot Repository</name>
<url>http://180.168.156.212:2905/repository/maven-snapshots</url>
<uniqueVersion>false</uniqueVersion>
</snapshotRepository>
</distributionManagement>
<properties>
<spring.boot.version>2.0.4.RELEASE</spring.boot.version>
<digester.version>1.8</digester.version>
<ognl.version>3.0</ognl.version>
<javassist.version>3.12.0.GA</javassist.version>
<codetable.version>1.0.0.RELEASE</codetable.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<dependency>
<groupId>commons-digester</groupId>
<artifactId>commons-digester</artifactId>
<version>${digester.version}</version>
</dependency>
<dependency>
<groupId>ognl</groupId>
<artifactId>ognl</artifactId>
<version>${ognl.version}</version>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>${javassist.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>com.cesgroup.zw.codetable</groupId>
<artifactId>codetable</artifactId>
<version>${codetable.version}</version>
</dependency>
<dependency>
<groupId>com.cesgroup.zw.spring.boot</groupId>
<artifactId>codetable-spring-boot-autoconfigure</artifactId>
<version>${codetable.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<modules>
<module>codetable-spring-boot-autoconfigure</module>
<module>codetable-spring-boot-starter</module>
<module>codetable</module>
<module>codetable-spring-boot-samples</module>
</modules>
</project>
\ No newline at end of file
@echo off
echo [Pre-Requirement] Makesure install JDK 6.0+ and set the JAVA_HOME.
echo [Pre-Requirement] Makesure install Maven 3.0.4+ and set the PATH.
set MVN=mvn
set MAVEN_OPTS=%MAVEN_OPTS% -XX:MaxPermSize=128m
echo [Step 1] Install all SCMMoudle modules to local maven repository.
call %MVN% clean source:jar compile install -Dmaven.test.skip=true
pause
\ No newline at end of file
@echo off
echo [Pre-Requirement] Makesure install JDK 6.0+ and set the JAVA_HOME.
echo [Pre-Requirement] Makesure install Maven 3.0.4+ and set the PATH.
set MVN=mvn
set MAVEN_OPTS=%MAVEN_OPTS% -XX:MaxPermSize=128m
echo [Step 1] Install all SCMMoudle modules to local maven repository.
call %MVN% clean compile install deploy -Dmaven.test.skip=true
pause
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment