Browse Source

验证添加参数控制,解决jar包运行无法读取配置文件问题

guq 7 years ago
parent
commit
01bc173e7b

+ 24 - 0
eis-wms/src/main/java/com/uas/eiswms/WebAppConfiguration.java

@@ -0,0 +1,24 @@
+package com.uas.eiswms;
+
+import com.uas.eiswms.aop.DataSourceInterceptor;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
+
+@Configuration
+public class WebAppConfiguration extends WebMvcConfigurerAdapter {
+
+    @Bean
+    DataSourceInterceptor dataSourceInterceptor() {
+        return new DataSourceInterceptor();
+    }
+
+    @Override
+    public void addInterceptors(InterceptorRegistry registry) {
+        registry.addInterceptor(dataSourceInterceptor()).addPathPatterns("/**");
+        super.addInterceptors(registry);
+    }
+
+}

+ 44 - 0
eis-wms/src/main/java/com/uas/eiswms/aop/DataSourceInterceptor.java

@@ -0,0 +1,44 @@
+package com.uas.eiswms.aop;
+
+import com.uas.eiswms.dao.BaseDao;
+import com.uas.eiswms.util.BaseUtil;
+import com.uas.eiswms.util.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+import org.springframework.web.servlet.HandlerInterceptor;
+import org.springframework.web.servlet.ModelAndView;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+@Component
+public class DataSourceInterceptor implements HandlerInterceptor {
+
+    @Autowired
+    private BaseDao baseDao;
+    @Override
+    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
+        // 账套处理
+        if (StringUtils.isEmpty(request.getParameter("master"))) {
+            BaseUtil.showError("账套为空!");
+        }
+        String master = request.getParameter("master");
+        baseDao.setJdbcTemplate(master);
+        return true;
+    }
+
+    /**
+     * 该方法将在Controller执行之后,返回视图之前执行,modelAndView表示请求Controller处理之后返回的Model和View对象,所以可以在
+     * 这个方法中修改modelAndView的属性,从而达到改变返回的模型和视图的效果。
+     */
+    @Override
+    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
+                           ModelAndView modelAndView) throws Exception {
+
+    }
+
+
+    @Override
+    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
+                                Object o, Exception e) throws Exception {
+
+    }
+}

+ 0 - 3
eis-wms/src/main/java/com/uas/eiswms/controller/BasicDataController.java

@@ -1,6 +1,5 @@
 package com.uas.eiswms.controller;
 
-import com.uas.eiswms.dao.BaseDao;
 import com.uas.eiswms.service.BasicDataService;
 import com.uas.eiswms.service.LoginService;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -27,8 +26,6 @@ public class BasicDataController {
     @Autowired
     private BasicDataService basicDataService;
     @Autowired
-    private BaseDao baseDao;
-    @Autowired
     private LoginService loginService;
 
     @PostMapping(value = "/basic/getProduct.action")

+ 21 - 14
eis-wms/src/main/java/com/uas/eiswms/controller/ProdIOController.java

@@ -2,6 +2,7 @@ package com.uas.eiswms.controller;
 
 import com.sun.xml.internal.rngom.parse.host.Base;
 import com.uas.eiswms.dao.BaseDao;
+import com.uas.eiswms.service.LoginService;
 import com.uas.eiswms.service.ProdIOService;
 import com.uas.eiswms.util.BaseUtil;
 import com.uas.eiswms.util.StringUtils;
@@ -9,6 +10,7 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
 
+import javax.servlet.http.HttpServletRequest;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -20,25 +22,30 @@ public class ProdIOController {
     @Autowired
     private ProdIOService prodIOService;
     @Autowired
-    private BaseDao baseDao;
+    private LoginService loginService;
+
+    @RequestMapping("/productio/getBill.action")
+    public Map<String, Object> getBill(String master, String pi_class, String lastUpdateTime, String condition,
+                                       String token, Long timestamp, String sign, HttpServletRequest request) {
+        Map<String, Object> resultMap = loginService.checkSign(request);
+        if (!resultMap.get("resCode").equals("00")) {
+            return resultMap;
+        }
+        return prodIOService.getBill(pi_class, lastUpdateTime, condition);
+    }
 
     @RequestMapping("/porductio/post.action")
-    public Map<String, Object> post(String master, String data, String token, Long timestamp, String sign){
-        Map<String, Object> map = new HashMap<String, Object>();
+    public Map<String, Object> post(String master, String data, String token, Long timestamp,
+                                    String sign, HttpServletRequest request){
+        Map<String, Object> resultMap = loginService.checkSign(request);
+        if (!resultMap.get("resCode").equals("00")) {
+            return resultMap;
+        }
         if(StringUtils.isEmpty(data)) {
             BaseUtil.showError("空数据,请检查后进行请求!");
         }
-        baseDao.setJdbcTemplate(master);
-        prodIOService.prePost(data);
-        map.put("success", true);
-        return map;
-    }
-
-    @RequestMapping("/productio/getBill.action")
-    public Map<String, Object> getBill(String master, String pi_class, String lastUpdateTime, String condition,
-         String token, Long timestamp, String sign) {
-        baseDao.setJdbcTemplate(master);
-       return prodIOService.getBill(pi_class, lastUpdateTime, condition);
+        resultMap.put("result", prodIOService.prePost(data));
+        return resultMap;
     }
 
     @RequestMapping("/productio/test.action")

+ 18 - 6
eis-wms/src/main/java/com/uas/eiswms/dao/BaseDao.java

@@ -3,16 +3,16 @@ package com.uas.eiswms.dao;
 
 
 
-import com.alibaba.druid.pool.DruidDataSource;
-import com.sun.xml.internal.rngom.parse.host.Base;
+
 import com.uas.eiswms.model.SqlRowList;
 import com.uas.eiswms.util.BaseUtil;
 
 import com.uas.eiswms.util.Constant;
 import com.uas.eiswms.util.DateUtil;
 import com.uas.eiswms.util.MasterManager;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.core.env.Environment;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 import org.springframework.dao.DataAccessException;
 import org.springframework.jdbc.core.CallableStatementCallback;
 import org.springframework.jdbc.core.CallableStatementCreator;
@@ -31,19 +31,31 @@ import java.util.*;
 @Repository("baseDao")
 public class BaseDao {
 
+
 	static final String CREATE_SEQ = "CREATE SEQUENCE ?" + // 创建序列
 			" MINVALUE 1 MAXVALUE 99999999999 INCREMENT BY 1 START WITH 3000 CACHE 20 NOORDER NOCYCLE ";
 
 	private JdbcTemplate jdbcTemplate;
 
-	public void setJdbcTemplate(String master){
+	private String onLineMaster;
+
+	private Logger logger = LoggerFactory.getLogger(BaseDao.class);
+
+	public synchronized void setJdbcTemplate(String master){
+		logger.info("切换到账套:" + master);
 		DataSource dataSource = MasterManager.getDataSource(master);
 		if (dataSource == null){
 			BaseUtil.showError("数据源不存在");
 		}
 		if (this.jdbcTemplate == null) {
 			this.jdbcTemplate = new JdbcTemplate(dataSource);
+			this.onLineMaster = master;
 		} else {
+			if (this.onLineMaster != null && this.onLineMaster.equals(master)){
+				return;
+			}
+			logger.info("进行切换数据源...");
+			this.onLineMaster = master;
 			this.jdbcTemplate.setDataSource(dataSource);
 		}
 	}
@@ -290,7 +302,7 @@ public class BaseDao {
 	}
 
 	public boolean isDBSetting(String caller, String code) {
-		Integer i = jdbcTemplate.queryForObject("select count(1) from configs where caller='" + caller + "' and code='" + code + "'",
+		Integer i = jdbcTemplate.queryForObject("select count(1) from configs where data =1 and caller='" + caller + "' and code='" + code + "'",
 				Integer.class);
 		if (i >0) {
 			return true;

+ 7 - 7
eis-wms/src/main/java/com/uas/eiswms/service/LoginService.java

@@ -29,7 +29,7 @@ public class LoginService {
             resultMap.put("resMsg", "密码不能为空");
             return resultMap;
         }
-        int count = baseDao.getCount("select count(1) from UserDataInfo where udi_username='" + userName + "' and udi_password='" + passWord + "'");
+        int count = baseDao.getCount("select count(1) from UserDataInfo where udi_username='" + userName.replaceAll("'","''") + "' and udi_password='" + passWord.replaceAll("'","''") + "'");
         if (count < 1) {
             resultMap.put("code", "0001");
             resultMap.put("resMsg", "用户名或密码不正确");
@@ -62,15 +62,16 @@ public class LoginService {
                 paramsMap.put(paramName,value);
             }
         }
+        boolean tokenDisable = baseDao.isDBSetting("WMS2UAS","tokenDisable");
         int count = baseDao.getCount("select count(1) from UserDataInfo where udi_token='" + token + "'");
-        if (count < 1) {
+        if (count < 1 && !tokenDisable) {
             resultMap.put("resCode","01");
             resultMap.put("success", false);
             resultMap.put("result", "token错误");
             return resultMap;
         }
         int isExpireTime = baseDao.getCount("select count(1) from UserDataInfo where udi_token='" + token + "' and (sysdate-udi_updatetime)*24 < 1");
-        if (isExpireTime < 1) {
+        if (isExpireTime < 1 && !tokenDisable) {
             resultMap.put("resCode","02");
             resultMap.put("success", false);
             resultMap.put("result", "token已失效");
@@ -99,16 +100,15 @@ public class LoginService {
         }
         //若字符中存在中文,则一定要指定编码类型
         String signStr = DigestUtils.md5DigestAsHex(temp.toString().getBytes(Charset.forName("UTF-8"))).toUpperCase();
-        System.out.println("签名----》" + signStr);
-        //MD5Util.getMD5(temp.toString()).toUpperCase();
-        if (!signStr.equals(sign)) {
+        System.out.println(signStr);
+        if (!signStr.equals(sign) && !tokenDisable) {
             resultMap.put("resCode","03");
             resultMap.put("success", false);
             resultMap.put("result", "sign签名不正确");
             return resultMap;
         }
         resultMap.put("resCode","00");
-        resultMap.put("success", false);
+        resultMap.put("success", true);
         resultMap.put("result", "sign签名正确");
         return resultMap;
     }

+ 5 - 2
eis-wms/src/main/java/com/uas/eiswms/service/impl/ProdIOServiceImpl.java

@@ -44,15 +44,17 @@ public class ProdIOServiceImpl implements ProdIOService{
         }
         String caller = class2caller(pi_class);
         String con= StringUtils.isEmpty(condition) ? "1=1" : condition.replaceAll("'", "''");
+        logger.info("获取单据字段...");
         List<Object> mainFields = baseDao.getFieldDatasByCondition("form left join formdetail on fo_id=fd_foid", "fd_field",
                 "fo_caller='" + caller + "' and (upper(fd_field) like upper('pi_%') or upper(fd_field) like upper('prodinout%pi_%') ) order by fd_detno");
         List<Object> detailFileds = baseDao.getFieldDatasByCondition("detailgrid", "dg_field", "dg_caller='"+ caller +"' and " +
-                "(upper(dg_field) like upper('pd_%') or upper(dg_field) like upper('prodiodetail.%pd_%')) order by DG_SEQUENCE");
+                "(upper(dg_field) like upper('pd_%') or upper(dg_field) like upper('prodiodetail.%pd_%')) and UPPER(dg_field) not in (select COLUMN_NAME from USER_TAB_COLS where table_name='PURCHASEDETAIL') order by DG_SEQUENCE");
         if (mainFields != null && detailFileds != null) {
             String mainStr = List2Str(mainFields);
             String gridStr = List2Str(detailFileds);
             List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
             //获取主表信息
+            logger.info("获取主表信息...");
             List<Map<String, Object>> list = baseDao.getJdbcTemplate().queryForList("select " + mainStr +
                     " from prodinout where pi_class=? and pi_lastupdatetime_user>to_date('"+ lastUpdateTime +"','yyyy-mm-dd') and " + con + " order by pi_id", pi_class);
             List<Map<String, Object>> maps = BaseUtil.parseListDate(list);
@@ -61,7 +63,8 @@ public class ProdIOServiceImpl implements ProdIOService{
                     Object pi_id = m.get("pi_id");
                     if (!StringUtils.isEmpty(pi_id)) {
                         //从表信息
-                        List<Map<String, Object>> details = baseDao.getJdbcTemplate().queryForList("select " + gridStr + " from prodiodetail where pd_piid=?", pi_id);
+                        logger.info("获取从表信息...");
+                        List<Map<String, Object>> details = baseDao.getJdbcTemplate().queryForList("select " + gridStr + " from prodiodetail  where pd_piid=?", pi_id);
                         m.put("detail", BaseUtil.parseListDate(details));
                         data.add(m);
                     }

+ 96 - 21
eis-wms/src/main/java/com/uas/eiswms/util/MasterManager.java

@@ -5,6 +5,8 @@ import com.alibaba.fastjson.JSONObject;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import java.io.*;
+import java.net.URL;
 import java.sql.SQLException;
 import java.util.HashSet;
 import java.util.Map;
@@ -23,13 +25,11 @@ public class MasterManager {
      */
     private static Set<String> masters = new HashSet<>();
 
-    private static final String DATACONFIG = "{\"UAS_DEV\":{\"password\":\"select!#%*(\",\"driverClassName\":\"oracle.jdbc.driver.OracleDriver\",\"url\":\"jdbc:oracle:thin:@192.168.253.6:1521:orcl\",\"username\":\"UAS_DEV\"},\"UAS\":{\"password\":\"select!#%*(\",\"driverClassName\":\"oracle.jdbc.driver.OracleDriver\",\"url\":\"jdbc:oracle:thin:@192.168.253.6:1521:orcl\",\"username\":\"UAS\"},\"XKN_TEST\":{\"password\":\"select!#%*(\",\"driverClassName\":\"oracle.jdbc.driver.OracleDriver\",\"url\":\"jdbc:oracle:thin:@127.0.0.1:1521:orcl\",\"username\":\"XKN_TEST\"}}";
     private static Logger logger = LoggerFactory.getLogger(MasterManager.class);
 
     static {
         init();
     }
-
     /**
      * 初始化所有数据源
      */
@@ -37,33 +37,36 @@ public class MasterManager {
         clear();
         logger.info("数据源初始化......");
         // 从配置中获取数据源信息
-    /*    File propertyFile = new File("application.properties");
-        if (!propertyFile.exists()) {
+        File propertyFile = new File("application.properties");
+        Properties properties = new Properties();
+        if (!propertyFile.exists() || !propertyFile.isFile()) {
             try {
-                logger.warn("配置文件再次读取......");
-                propertyFile = BaseUtil.getFile("application.properties");
-                if (!propertyFile.exists() && !propertyFile.isFile()) {
-                    BaseUtil.showError("读取配置文件失败");
+                logger.info("配置文件再次读取......");
+                // 是否以 spring boot jar 形式运行
+                URL location = MasterManager.class.getProtectionDomain().getCodeSource().getLocation();
+                if (org.springframework.util.ResourceUtils.isJarURL(location)) {
+                    // 以 spring boot jar 形式运行时,不能直接复制默认配置文件,需以输入流的方式读取默认配置
+                    InputStream inputStream = MasterManager.class.getResourceAsStream("/" + "application.properties");
+                    byte[] data = new byte[inputStream.available()];
+                    inputStream.read(data);
+                    logger.info("配置文件路径:"+ propertyFile.getPath());
+                    write(propertyFile.getPath(), data, false);
+                    logger.info("读取成功......");
+                }else{
+                    logger.info("非jar包运行......");
+                    propertyFile = BaseUtil.getFile("application.properties");
                 }
+                properties.load(new FileInputStream(propertyFile));
             }catch (Exception e){
-                logger.warn("配置文件读取失败......");
                 e.printStackTrace();
+                BaseUtil.showError("读取配置文件失败");
             }
-
         }
-        Properties properties = new Properties();
-        try {
-            properties.load(new FileInputStream(propertyFile));
-        } catch (IOException e) {
-            BaseUtil.showError("读取配置文件失败");
-            e.printStackTrace();
-        }*/
-       // String datasourceConfig = properties.getProperty("datasourceConfig");
-       // String datasourceConfig = "{\"UAS_DEV\":{\"password\":\"select!#%*(\",\"driverClassName\":\"oracle.jdbc.driver.OracleDriver\",\"url\":\"jdbc:oracle:thin:@192.168.253.6:1521:orcl\",\"username\":\"UAS_DEV\"},\"UAS\":{\"password\":\"select!#%*(\",\"driverClassName\":\"oracle.jdbc.driver.OracleDriver\",\"url\":\"jdbc:oracle:thin:@192.168.253.6:1521:orcl\",\"username\":\"UAS\"},\"XKN_TEST\":{\"password\":\"select!#%*(\",\"driverClassName\":\"oracle.jdbc.driver.OracleDriver\",\"url\":\"jdbc:oracle:thin:@127.0.0.1:1521:orcl\",\"username\":\"XKN_TEST\"}}";
-        JSONObject jsonObject = JSONObject.parseObject(DATACONFIG);
+        String datasourceConfig = properties.getProperty("datasourceConfig");
+        logger.info("datasourceConfig:" + datasourceConfig);
+        JSONObject jsonObject = JSONObject.parseObject(datasourceConfig);
         Set<Map.Entry<String, Object>> entrySet = jsonObject.entrySet();
         for (Map.Entry<String, Object> entry : entrySet) {
-            JSONObject object = JSONObject.parseObject(entry.getValue().toString());
             DruidDataSource dataSource = JSONObject.parseObject(entry.getValue().toString(), DruidDataSource.class);
             dataSources.put(entry.getKey().toUpperCase(), dataSource);
             masters.add(entry.getKey().toUpperCase());
@@ -106,4 +109,76 @@ public class MasterManager {
         }
         return dataSource;
     }
+
+    /**
+     * 写入文件
+     *
+     * @param filePath
+     *            文件路径
+     * @param data
+     *            数据
+     * @param allowNoData
+     *            是否允许数据为空(文件无内容)
+     * @throws IOException
+     */
+    public static void write(String filePath, byte[] data, boolean allowNoData) throws IOException {
+        if (StringUtils.isEmpty(filePath)) {
+            throw new IllegalArgumentException("参数不能为空:filePath");
+        }
+        if (!allowNoData && StringUtils.isEmpty(data)) {
+            throw new IllegalArgumentException("参数不能为空:data");
+        }
+
+        File file = new File(filePath);
+        if (file.getParentFile() != null && !file.getParentFile().exists()) {
+            file.getParentFile().mkdirs();
+        }
+        FileOutputStream fos = new FileOutputStream(file);
+        fos.write(data);
+        fos.flush();
+        logger.info("Writed... " + file.getPath());
+        fos.close();
+    }
+
+   /* *//**
+     * 复制文件(夹)
+     *
+     * @param src
+     *            源文件(夹)
+     * @param dest
+     *            目的文件(夹)
+     * @throws IOException
+     *//*
+    public static void copy(File src, File dest) throws IOException {
+        if (src.equals(dest)) {
+            throw new IOException("不可置于相同路径下");
+        }
+        if (!src.isFile() && !dest.isFile() && isSub(src, dest)) {
+            throw new IOException("不可置于子路径下");
+        }
+        if (src.isFile()) {
+            if (dest.exists() && dest.isDirectory()) {
+                dest = new File(dest, src.getName());
+                copy(src, dest);
+                return;
+            }
+            ReadableByteChannel in = Channels.newChannel(new FileInputStream(src));
+            WritableByteChannel out = Channels.newChannel(new FileOutputStream(dest));
+            copyChannel(in, out);
+            in.close();
+            out.close();
+        } else {
+            if (dest.exists() && dest.isFile()) {
+                throw new IOException("不可将文件夹置于文件下");
+            }
+            if (!dest.exists()) {
+                dest.mkdirs();
+            }
+            File[] files = src.listFiles();
+            for (File file : files) {
+                copy(file, new File(dest, file.getName()));
+            }
+        }
+    }*/
+
 }