package com.yc.action.panval;
|
|
import com.alibaba.fastjson.JSON;
|
import com.google.gson.JsonObject;
|
import com.jspsmart.upload.Files;
|
import com.jspsmart.upload.Request;
|
import com.jspsmart.upload.SmartUpload;
|
import com.yc.action.BaseAction;
|
import com.yc.entity.DataSourceActionEntity;
|
import com.yc.entity.DataSourceActionEntity.ActionEnum;
|
import com.yc.entity.DataSourceEntity;
|
import com.yc.entity.DemoConstant;
|
import com.yc.exception.ApplicationException;
|
import com.yc.exception.CallBackMessage;
|
import com.yc.factory.FactoryBean;
|
import com.yc.multiData.JdbcPoolConfig;
|
import com.yc.multiData.MultiDataSource;
|
import com.yc.multiData.SpObserver;
|
import com.yc.sdk.WebSocketMessage.action.WebSocketMessageServer;
|
import com.yc.sdk.WebSocketMessage.entity.MessageInfo;
|
import com.yc.sdk.WebSocketMessage.entity.MessageType;
|
import com.yc.sdk.password.action.ChangePassword;
|
import com.yc.sdk.shopping.util.SettingKey;
|
import com.yc.sdk.weixincp.util.AsynchronousExecution;
|
import com.yc.service.BaseService;
|
import com.yc.service.demo.DemoIfc;
|
import com.yc.service.grid.GridServiceIfc;
|
import com.yc.service.impl.DBHelper;
|
import com.yc.service.impl.EnvHelper;
|
import com.yc.service.oapanel.WebMenuAccessIfc;
|
import com.yc.service.panel.*;
|
import com.yc.service.panel.v2.PanelBean;
|
import com.yc.service.panel.v2.TypeControl;
|
import com.yc.service.panel.v2.TypeControlDao;
|
import com.yc.utils.EncodeUtil;
|
import com.yc.utils.SessionKey;
|
import com.yc.utils.fileAndFolder.FileAndFolderOper;
|
import org.apache.catalina.LifecycleException;
|
import org.apache.catalina.startup.Catalina;
|
import org.apache.commons.lang3.StringUtils;
|
import org.slf4j.Logger;
|
import org.slf4j.LoggerFactory;
|
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.dao.DataAccessException;
|
import org.springframework.stereotype.Controller;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.multipart.MultipartFile;
|
|
import javax.imageio.IIOException;
|
import javax.imageio.ImageIO;
|
import javax.imageio.ImageReader;
|
import javax.imageio.stream.ImageInputStream;
|
import javax.servlet.http.Cookie;
|
import javax.servlet.http.HttpServletRequest;
|
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpSession;
|
import java.awt.color.ColorSpace;
|
import java.awt.image.BufferedImage;
|
import java.awt.image.ColorConvertOp;
|
import java.awt.image.Raster;
|
import java.io.*;
|
import java.net.InetAddress;
|
import java.net.URLDecoder;
|
import java.sql.SQLException;
|
import java.text.ParseException;
|
import java.text.SimpleDateFormat;
|
import java.util.*;
|
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.regex.Matcher;
|
import java.util.regex.Pattern;
|
|
//import peng.pb.io.FileDo;
|
|
@Controller
|
public class InvGet extends BaseAction {
|
@Autowired
|
PanelValueDao pDao;
|
@Autowired
|
SystemSettingsDao sysDao;
|
@Autowired
|
WebMenuAccessIfc wIfc;
|
@Autowired
|
TypeControlDao tControlDao;
|
@Autowired
|
SqlDBHelperIfc sqlDBHelperIfc;
|
@Autowired
|
DemoIfc demoIfc;
|
@Autowired
|
DemoIfc dIfc;
|
@Autowired
|
DiBangIfc diBangIfc;
|
@Autowired
|
GridServiceIfc gridServiceIfc;
|
//@Autowired
|
//private DefaultLobHandler defaultLobHandler;
|
private final Catalina EMBEDDED = new Catalina();
|
private final Logger log = LoggerFactory.getLogger(this.getClass());
|
public FileAndFolderOper FAFO = new FileAndFolderOper();
|
public static String driverClass = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
|
public static Integer initialPoolSize = Integer.parseInt(JdbcPoolConfig.get("cop3.initialPoolSize")); //5 ;
|
public static Integer minPoolSize = Integer.parseInt(JdbcPoolConfig.get("cop3.minPoolSize"));//5 ;
|
public static Integer maxPoolSize = Integer.parseInt(JdbcPoolConfig.get("cop3.maxPoolSize"));//50 ;
|
public static Integer acquireIncrement =Integer.parseInt(JdbcPoolConfig.get("cop3.acquireIncrement"));// 5 ;
|
public static Integer maxIdleTime = Integer.parseInt(JdbcPoolConfig.get("cop3.maxIdleTime"));//1800 ;
|
public static Integer idleConnectionTestPeriod = Integer.parseInt(JdbcPoolConfig.get("cop3.idleConnectionTestPeriod"));//1800 ;
|
public static Integer maxStatements = Integer.parseInt(JdbcPoolConfig.get("cop3.maxStatements"));//0 ;
|
|
|
@RequestMapping("/inv.do")
|
public void login(int id, String where, String sel, String get, HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {
|
try {
|
where = URLDecoder.decode(where, "utf-8");
|
SpObserver.setDBtoInstance("_"+request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
|
if (!sel.equals("") && id > -1) {// 这为2类型下拉,控制下吧,
|
this.print(response, pDao.getStr(id, where, sel, get));
|
} else {
|
this.print(response, "");
|
}
|
} catch (Exception e) {
|
this.print(response, e.getCause()!=null?e.getCause().getMessage():e.getMessage());
|
}finally {
|
SpObserver.setDBtoInstance();
|
}
|
|
}
|
|
@RequestMapping("/invAll.do")
|
public void login(int id, String where, HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {
|
try {
|
where = URLDecoder.decode(where, "utf-8");
|
SpObserver.setDBtoInstance("_"+request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
|
if (id < 0) {
|
this.print(response, "");
|
} else {
|
this.print(response,pDao.getStrAll(id, where));
|
}
|
} catch (Exception e) {
|
this.print(response, e.getCause()!=null?e.getCause().getMessage():e.getMessage());
|
}finally {
|
SpObserver.setDBtoInstance();
|
}
|
}
|
|
@RequestMapping("/invAlldiv.do")
|
public void login(int id, String where, String sugg, HttpServletRequest request, HttpServletResponse response) throws IOException {
|
try {
|
where = URLDecoder.decode(where, "utf-8");
|
SpObserver.setDBtoInstance("_"+request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
|
if (id < 0) {
|
this.print(response, "");
|
} else {
|
where = getwherezdy(where, request);
|
this.print(response,pDao.getStrAll42(id, where, "42", sugg));
|
}
|
} catch (Exception e) {
|
this.print(response, e.getCause()!=null?e.getCause().getMessage():e.getMessage());
|
}finally {
|
SpObserver.setDBtoInstance();
|
}
|
}
|
|
/**
|
* 针对面板的42控件取值的方法 xin 2021-3-18 14:01:33
|
* 这个方法是新的,且是面板42控件调用,旧方法是上面的/invAlldiv.do
|
* @param request
|
* @param response
|
*/
|
@RequestMapping("/panelControlData42.do")
|
public void getPanelControlData42(int page,int limit,int ft,String where,String sugg,int formType,String parameter,
|
HttpServletRequest request,HttpServletResponse response) {
|
try {
|
SpObserver.setDBtoInstance("_" + request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
|
if (ft <= 0) {//表号为空
|
super.printJson(response, "");
|
return;
|
}
|
where = URLDecoder.decode(where, "utf-8");
|
where = getwherezdy(where, request);
|
String value = pDao.getStrAll42(page, limit, ft, where, sugg,formType,parameter);
|
super.printJson(response, value);
|
} catch (Exception e) {
|
super.printJson(response,new CallBackMessage().sendErrorMessage(e.getCause()!=null?e.getCause().getMessage():e.getMessage()));
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
}
|
|
/**
|
* 处理@符号替换
|
* @param where处理的条件
|
* @param request
|
* @return
|
*/
|
public String getwherezdy(String where, HttpServletRequest request) {
|
try {
|
HttpSession session = request.getSession();
|
if ((where.indexOf("@~")) != -1) {
|
where = where.replaceAll("@~", "%");
|
}
|
// if(where.indexOf("'@'"))
|
if ((where.indexOf("@")) != -1) {
|
while ((where.indexOf("@")) != -1) {
|
String tes = "";
|
Pattern ps = Pattern.compile("@.*?\\w+");// 匹配以@开头的单词
|
Matcher propsMatchers = ps.matcher(where);
|
while (propsMatchers.find()) {
|
tes = propsMatchers.group();
|
}
|
String se = session.getAttribute(tes.toLowerCase()) == null ? tes : session.getAttribute(tes.toLowerCase()).toString();//
|
|
where = where.replaceAll(tes, se);
|
|
}
|
}
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
return where;
|
}
|
|
@RequestMapping("/NeedWork.do")
|
public void NeedWork(String UNID, String actionType,int formId, String doccode, int formType, HttpServletRequest request, HttpServletResponse response) throws IOException {
|
try {
|
SpObserver.setDBtoInstance("_"+request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
|
wIfc.setIsRead(UNID);
|
HttpSession session = request.getSession();
|
String url = SettingKey.getHostUrl(request) +
|
"/app/" + session.getAttribute(SessionKey.DATA_BASE_ID) + "/" + session.getAttribute(SessionKey.VERSION_ID) + "/" + session.getAttribute(SessionKey.SYSTEM_LANGUAGE)
|
|
+ "/" + formId + "/" + formType + "/index.jsp?" + EncodeUtil.base64Encode("isNew=ie&doccode=\'" + doccode + "\'");
|
response.sendRedirect(url);
|
}catch (Exception e) {
|
this.print(response, e.getCause()!=null?e.getCause().getMessage():e.getMessage());
|
}finally {
|
SpObserver.setDBtoInstance();
|
}
|
}
|
@RequestMapping("/NeedWorkOK.do")
|
public void NeedWorkOk(String UNID,String actionType, HttpServletRequest request, HttpServletResponse response) throws IOException {
|
try {
|
SpObserver.setDBtoInstance("_"+request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
|
this.print(response, wIfc.setIsRead(UNID)+"");
|
}catch (Exception e) {
|
this.print(response, e.getCause()!=null?e.getCause().getMessage():e.getMessage());
|
}finally {
|
SpObserver.setDBtoInstance();
|
}
|
}
|
|
@RequestMapping("/getDiBang.do")
|
public void getDiBang(String ip, HttpServletRequest request, HttpServletResponse response) throws IOException {
|
response.setContentType("text/html;charset=utf-8");
|
PrintWriter out = response.getWriter();
|
HttpSession session = request.getSession();
|
// Map<String, Object> oMap = diBangIfc.getDiBangInfo(ip);
|
String hostname = request.getParameter("hostname");
|
try {
|
SpObserver.setDBtoInstance("_"+request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
|
Map<String, Object> oMap = diBangIfc.getDiBangInfo(ip, hostname);
|
session.setAttribute(SessionKey.IP_ADDRESS, ip);// 赋地磅信息session值
|
session.setAttribute(SessionKey.HOSTNAME, hostname);
|
session.setAttribute(SessionKey.MAC_ADDRESS, request.getParameter("MacAddress"));
|
String loadername = "";
|
if (oMap != null && !oMap.isEmpty()) {
|
out.print("hasParm:1,");
|
out.print("isrndstart:" + DBHelper.getValue(oMap, "isRndStart") + ",");
|
out.print("decimals:" + DBHelper.getValueInt(oMap, "Decimals") + ","); // 小数位数: 1 表示1个小数位,2,表示2个小数位
|
out.print("eloadprebits:" + DBHelper.getValueInt(oMap, "EloadPrebits") + ","); // 从第1个字符开始丢弃的字符个数
|
out.print("eloadbits:" + DBHelper.getValueInt(oMap, "Eloadbits") + ","); // 连续取字符串长度
|
out.print("bufferlength:" + DBHelper.getValueInt(oMap, "BufferLength") + ","); // 缓冲区长度
|
out.print("newlinesepchar:" + DBHelper.getValueInt(oMap, "NewLineSepChar") + ","); // 换行分隔符
|
out.print("enterkeysepchar:" + DBHelper.getValueInt(oMap, "EnterkeySepChar") + ","); // 回车分隔符
|
out.print("othersepchar:" + DBHelper.getValue(oMap, "OtherSepChar") + ","); // 其它分隔符
|
out.print("isreservchar:" + DBHelper.getValueInt(oMap, "IsReservChar") + ","); // 是否反转显示字符串
|
out.print("portnum:" + DBHelper.getValueInt(oMap, "LoadPort") + ","); // 端口号 , 1 表示 com1 , 2 表示 com1 以此类推
|
out.print("bandrate:" + DBHelper.getValueInt(oMap, "BandRate") + ","); // 设置波特率 , 缺省 2400
|
out.print("databit:" + DBHelper.getValueInt(oMap, "DataBit") + ","); // 数据位 , 缺省 8
|
out.print("parity:" + DBHelper.getValue(oMap, "CRCbit") + ","); // 奇偶校验 , n 表示NONE 无
|
out.print("stopbit:" + DBHelper.getValueInt(oMap, "StopBit") + ","); // 停止位 ,缺省 1
|
out.print("isdebug:" + DBHelper.getValueInt(oMap, "isDebug") + ""); // 是否为调试
|
loadername = DBHelper.getValue(oMap, "LoaderName");
|
} else {
|
out.print("hasParm:0");
|
}
|
session.setAttribute(SessionKey.LOADER_NAME, loadername);
|
out.flush();
|
out.close();
|
}catch (Exception e) {
|
this.print(response, e.getCause()!=null?e.getCause().getMessage():e.getMessage());
|
}finally {
|
SpObserver.setDBtoInstance();
|
}
|
}
|
|
@RequestMapping("/getDoc.do")
|
public void getDoc(HttpServletRequest request, HttpServletResponse response) throws IOException {
|
String doccode = request.getParameter("doccode");
|
String t_doc = request.getParameter("t_doc");
|
String tUrl = request.getParameter("tUrl");
|
String[] tStrings = tUrl.split("\\?");
|
tStrings[1] = EncodeUtil.base64Encode(EncodeUtil.base64Decode(tStrings[1]).replace(doccode, t_doc));
|
this.print(response,tStrings[0] + "?" + tStrings[1]);
|
}
|
|
@RequestMapping("/getDateDemo.do")
|
public void getData(HttpServletRequest request, HttpServletResponse response) throws IOException {
|
String path = request.getServletContext().getRealPath("/");
|
EnvHelper.setPath(path);// 得到项目的地址,方便后面使用
|
String text = request.getParameter("dataBaseDis");
|
String str_version = request.getParameter("version");
|
String id = request.getParameter("id");
|
HttpSession session = request.getSession();
|
if (id != null) {
|
Cookie cookie = new Cookie("selectDatabase", id);
|
cookie.setMaxAge(604800);// 保存一周60×60×20×7
|
response.addCookie(cookie);
|
// System.out.println("选择配置文件为_" + id + ".xml");
|
session.setAttribute(SessionKey.DATA_BASE_ID, id);
|
session.setAttribute("databaseDis", text == null ? "" : text);
|
session.setAttribute("indexSelected", id);
|
}
|
int version = 0;
|
try {
|
version = Integer.parseInt(str_version);
|
} catch (Exception e) {
|
}
|
session.setAttribute(SessionKey.VERSION_ID, version);
|
// SpObserver.setDBtoInstance("_" + id);// 确立选择的配置文件
|
}
|
|
@RequestMapping("/SyncDataSource.do")
|
public void syncDataSource(HttpServletRequest request, HttpServletResponse response) throws Exception {
|
try {
|
String dbId = request.getParameter(SessionKey.DATA_BASE_ID) ; //从URL读取 dbid 参数
|
//String isDeleted = request.getParameter(SessionKey.isDeleted) ; //是否正在删除
|
refreshDataSource(dbId,DataSourceActionEntity.ActionEnum.REFRESH);
|
this.print(response, "同步更新集群主机的数据源成功!");
|
System.out.println("同步更新集群主机的数据源成功!");
|
}catch (Exception e) {
|
this.print(response, e.getMessage());
|
}
|
}
|
|
public static boolean refreshDataSource(String dbId,ActionEnum action) throws Exception{
|
DataSourceEntity oldDataSource=null;
|
DataSourceEntity newDataSource=null;
|
if (dbId!=null) {
|
MultiDataSource multiDataSource = (MultiDataSource) FactoryBean.getBean("multiDataSource");
|
oldDataSource = MultiDataSource.getDataSourceMap(dbId);//取内存数据
|
List<DataSourceEntity> newSourceList = multiDataSource.refreshDataSource(dbId);// 是为了增加一个数据源实现不重启就可以访问新增的数据源。也就是对原有保存在内存的数据源集合进行更新 2014-11-26
|
if(newSourceList!=null&&newSourceList.size()>0) {
|
MultiDataSource.getDataSourceMaps().put(dbId, newSourceList.get(0));
|
newDataSource = MultiDataSource.getDataSourceMap(dbId);
|
}else {
|
throw new ApplicationException("获取新数据源出错:"+dbId);
|
}
|
|
}
|
MessageInfo messageInfo = new MessageInfo();
|
//---刷新本地tomcat内存的数据源
|
messageInfo.setMsgType(MessageType.CHECK_SYSTEM_DISABLED);
|
messageInfo.setDbId(dbId==null?null:Integer.parseInt(dbId));
|
DataSourceActionEntity dataSourceActionEntity = new DataSourceActionEntity() ;
|
dataSourceActionEntity.setDbId(dbId);
|
dataSourceActionEntity.setAction(action.getName());
|
messageInfo.setMsg(JSON.toJSONString(dataSourceActionEntity));
|
WebSocketMessageServer.publishMessageToRedis(messageInfo);
|
//---webscoket通知web端和APP端
|
if(oldDataSource!=null&&newDataSource!=null) {
|
|
String actionType=null;
|
if(oldDataSource.isExpiredDate()&&!newDataSource.isExpiredDate())
|
{
|
actionType="start";
|
}
|
if(!oldDataSource.isExpiredDate()&&newDataSource.isExpiredDate())
|
{
|
actionType="stop";
|
}
|
if(actionType!=null&&!"".equals(actionType)) {
|
MessageInfo info = new MessageInfo();
|
info.setDbId(Integer.parseInt(dbId));
|
if ("stop".equalsIgnoreCase(actionType)) {
|
info.setMsgType(MessageType.NOTICE_SYSTEM_STOP);
|
} else {
|
info.setMsgType(MessageType.NOTICE_SYSTEM_START);
|
//info.setUserFromType("1");//作为key的一部分,识别是用来刷新登录页面
|
}
|
WebSocketMessageServer.publishMessageToRedis(info);
|
}
|
}
|
return true ;
|
}
|
|
/**
|
* 判断当前 dbid 是否存在于 cookies 中
|
* @param request
|
* @param dbId
|
* @return
|
*/
|
public static boolean isExistsDatabaseIdByCookie(HttpServletRequest request,String dbId) {
|
Cookie[] cookies = request.getCookies();
|
if(cookies!=null){
|
for(int i=0;i<cookies.length;i++){
|
if(cookies[i].getName().equals("selectDatabase") && !"".equals(dbId) && dbId.equals(cookies[i].getValue())){
|
return true ;
|
}
|
}
|
}
|
return false ;
|
}
|
|
@RequestMapping("/getInvitationCode.do")
|
public void getInvitationCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
|
try {
|
SpObserver.setDBtoDemo();
|
String invitationCode =dIfc.getInvitationCode() ;
|
this.print(response, invitationCode);
|
}catch (DataAccessException e) {
|
e.printStackTrace();
|
this.print(response,"修改出错!错误原因:" + (e.getCause()!=null? e.getCause().getMessage():e.getMessage()));
|
return ;
|
} catch (Exception e) {
|
e.printStackTrace();
|
this.print(response,"修改出错!错误原因:" + (e.getCause()!=null? e.getCause().getMessage():e.getMessage()));
|
return ;
|
}finally {
|
SpObserver.setDBtoInstance();
|
}
|
}
|
|
// @RequestMapping("/saveSystemConfig.do") //修改人 xin 2021-1-18 11:02:47
|
private void saveSystemConfig(MultipartFile logoFile,DataSourceEntity dataSourceEntity,HttpServletRequest request, HttpServletResponse response) throws Exception {
|
JsonObject json = new JsonObject();
|
JsonObject errJson = new JsonObject();
|
// String logodel = request.getParameter("logodel");//logo删除 ,1表示删除 0不处理 xin 2019-11-9 16:45:38
|
//String hostUrl = SettingKey.getHostUrl(request) ;
|
try {
|
SpObserver.setDBtoDemo();
|
// DataSourceEntity dataSourceEntity = getConnMap(request,response, "");
|
// byte[] logo = dataSourceEntity.getLogoIcon();
|
// //处理logoicon字段,删除和上传logo时候进入 xin 2019-11-9 16:45:38
|
// if(logodel!=null && logodel.equals("1") || logo!=null){
|
// //给false值是为了在sql组装的时候处理logoicon字段 xin 2019-11-9 16:45:38
|
// dataSourceEntity.setHasLogoIcon(false);
|
// }else{
|
// dataSourceEntity.setHasLogoIcon(true);
|
// }
|
if(logoFile!=null && !logoFile.isEmpty()) {//上传文件不为空
|
dataSourceEntity.setLogoIcon(logoFile.getBytes());
|
dataSourceEntity.setHasLogoIcon(false);
|
}
|
Integer ret = dIfc.saveDemo(dataSourceEntity);
|
if (ret != null && ret.equals(1)) {
|
json.addProperty("success", "更新成功!");
|
}else {
|
json.addProperty("success", "更新失败!");
|
}
|
//AsynchronousExecution.doRefreshUri(hostUrl,"/SyncDataSource.do?"+SessionKey.DATA_BASE_ID + "=" + dataSourceEntity.getDbId(), ""); //doRefreshDataSource();
|
|
refreshDataSource(dataSourceEntity.getDbId()+"",DataSourceActionEntity.ActionEnum.REFRESH); //直接刷新本机
|
|
this.printJson(response, json.toString());
|
return;
|
}catch (DataAccessException e) {
|
e.printStackTrace();
|
errJson.addProperty("warning", e.getCause().getMessage());
|
json.add("error", errJson);
|
this.printJson(response, json.toString());
|
return;
|
} catch (Exception e) {
|
e.printStackTrace();
|
errJson.addProperty("warning", e.getMessage());
|
json.add("error", errJson);
|
this.printJson(response, json.toString());
|
return;
|
}finally {
|
SpObserver.setDBtoInstance();
|
}
|
}
|
|
@RequestMapping("/setXml.do")//(旧方法,下面的/newsetXml.do为最新调用方法) xin 2020-12-28 16:12:39
|
public void setXml(HttpServletRequest request, HttpServletResponse response) throws Exception {
|
String testConn = request.getParameter("testConn");
|
String chqi = request.getParameter("chqi");
|
String logodel = request.getParameter("logodel");//logo删除 ,1表示删除 0不处理 xin 2019-11-9 16:45:38
|
if (chqi != null) {
|
reStartTomcat(request, response);
|
return;
|
}
|
DataSourceEntity dataSourceEntity = null;
|
try {
|
SpObserver.setDBtoDemo();
|
dataSourceEntity = getConnMap(request,response, "");
|
String pwd = dataSourceEntity.getPassword();
|
if (pwd == null || pwd.equals("")) {
|
List<DataSourceEntity> dataSourceMap = demoIfc.getDataSource(
|
DemoConstant.getInstance().setActived(null).setDbId(dataSourceEntity.getDbId() + ""));
|
if (dataSourceMap != null && dataSourceMap.size() > 0) {
|
pwd = dataSourceMap.get(0).getPassword();
|
dataSourceEntity.setPassword(pwd);
|
}
|
}
|
byte[] logo = dataSourceEntity.getLogoIcon();
|
//处理logoicon字段,删除和上传logo时候进入 xin 2019-11-9 16:45:38
|
if(logodel!=null && logodel.equals("1") || logo!=null){
|
//给false值是为了在sql组装的时候处理logoicon字段 xin 2019-11-9 16:45:38
|
dataSourceEntity.setHasLogoIcon(false);
|
}else{
|
dataSourceEntity.setHasLogoIcon(true);
|
}
|
if (dataSourceEntity.getActived()) {
|
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
|
String driverUrl = "jdbc:sqlserver://" + dataSourceEntity.getHost() + ":" + dataSourceEntity.getPort()
|
+ ";encrypt=true;trustServerCertificate=true;databaseName=" + dataSourceEntity.getDb();
|
try {
|
boolean isTestSuccess = DBHelper.getConnTest(driver, driverUrl, dataSourceEntity.getUserid(), pwd);
|
if (!isTestSuccess) {
|
this.print(response,"{\"state\":2,\"info\":\"数据库连接失败!\"}");
|
return;
|
}
|
if (testConn != null && testConn.equals("1")) {
|
this.print(response,"{\"state\":1,\"info\":\"连接成功\"}");
|
return;
|
}
|
}catch (Exception e) {
|
this.print(response,"{\"state\":2,\"info\":\""+ (e.getCause() != null?e.getCause().getMessage():e.getMessage()) + "\"}");
|
return;
|
}
|
}
|
} catch (DataAccessException e) {
|
this.print(response,"{\"state\":0,\"info\":\"修改出错!错误原因:"+ (e.getCause()!=null?e.getCause().getMessage():e.getMessage())+"\"}");
|
return;
|
} catch (Exception e) {
|
this.print(response,"{\"state\":0,\"info\":\"修改出错!错误原因:"+ (e.getCause()!=null?e.getCause().getMessage():e.getMessage())+"\"}");
|
return;
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
|
try {
|
if (dataSourceEntity.getDemoDataSource() != null
|
&& (dataSourceEntity.getDemoDataSource()).equals(SpObserver.DEMOXML)) {// demo
|
xmlDoWrite(request, dataSourceEntity); // 写入 _demo.xml 文件
|
MultiDataSource multiDataSource = (MultiDataSource) FactoryBean.getBean("multiDataSource");
|
DemoConstant demoConstant=new DemoConstant();
|
demoConstant.setDbId(dataSourceEntity.getDbId()+"");
|
multiDataSource.setDataSourceByMap(dataSourceEntity,demoConstant);
|
this.print(response,"{\"state\":1,\"info\":\"操作已经处理,请手动重启服务器才能生效!\"}");
|
} else {
|
// 配置不保存
|
String result=null;
|
try {
|
SpObserver.setDBtoDemo();
|
String invitationCode = (dataSourceEntity.getInvitationCode() == null ? null
|
: dataSourceEntity.getInvitationCode());
|
if (invitationCode == null || invitationCode.equals("")) {
|
invitationCode = dIfc.getInvitationCode();
|
dataSourceEntity.setInvitationCode(invitationCode);
|
}
|
result = dIfc.updateDemo(dataSourceEntity);
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
if(StringUtils.isNotBlank(result)) {
|
refreshDataSource(result.split(",")[0] , DataSourceActionEntity.ActionEnum.REFRESH); // 直接刷新本机
|
if (dataSourceEntity.getActived()) {
|
this.print(response, "{\"state\":1,\"info\":\"修改成功,可立即使用该数据源登录系统!\"}");
|
} else {
|
this.print(response, "{\"state\":1,\"info\":\"修改成功,由于该数据源未【启用】,因此不可立即使用该数据源登录系统!\"}");
|
}
|
}
|
}
|
return;
|
} catch (DataAccessException e) {
|
this.print(response,"{\"state\":0,\"info\":\"修改出错!错误原因:" + (e.getCause()!=null?e.getCause().getMessage():e.getMessage())+"\"}");
|
return;
|
} catch (Exception e) {
|
this.print(response,"{\"state\":0,\"info\":\"修改出错!错误原因:" + (e.getCause()!=null?e.getCause().getMessage():e.getMessage())+"\"}");
|
return;
|
}
|
}
|
|
/**
|
* 解析数据源定义的所有域名对应的IP
|
* @param dataSourceEntity
|
* @return
|
*/
|
private void processDomainToIP(DataSourceEntity dataSourceEntity){
|
StringBuilder sb=new StringBuilder();
|
if(StringUtils.isNotBlank(dataSourceEntity.getDomain())) {
|
Object[] domainList= Arrays.stream(dataSourceEntity.getDomain().replaceAll(":.*?\\d+", "").split(";")).distinct().toArray();
|
for(Object domain:domainList){
|
try {
|
InetAddress addresses = InetAddress.getByName(String.valueOf(domain));
|
//本机IP跳过
|
if("127.0.0.1".equals(addresses.getHostAddress())) continue;
|
sb.append(addresses.getHostAddress());
|
sb.append(";");
|
}catch (Exception ex){
|
ex.printStackTrace();
|
continue;
|
}
|
}
|
}
|
if(sb.length()>0) {
|
String str=sb.toString();
|
int index=str.lastIndexOf(";");
|
dataSourceEntity.setDomainIpList(str.substring(0,index));
|
}
|
}
|
@RequestMapping("/demo/refreshIp.do")
|
public void freshDomainTOIP(HttpServletRequest request,HttpServletResponse response){
|
//通过域名查出ip
|
try {
|
StringBuilder sql=new StringBuilder();
|
final Map<String, DataSourceEntity> dataSourceMaps = MultiDataSource.getDataSourceMaps();
|
Map<String, DataSourceEntity> concurrentHashMap =new ConcurrentHashMap<>();
|
concurrentHashMap.putAll(dataSourceMaps);
|
for (Map.Entry<String, DataSourceEntity> entry : concurrentHashMap.entrySet()) {
|
DataSourceEntity dataSourceEntity = entry.getValue();
|
processDomainToIP(dataSourceEntity);
|
sql.append(String.format(" update a set a.domainIpList='%s' from gsystem a where a.id=%d \n ", dataSourceEntity.getDomainIpList(), dataSourceEntity.getDbId()));
|
}
|
//更新到数据库
|
SpObserver.setDBtoDemo();
|
if(StringUtils.isNotBlank(sql)) {
|
BaseService baseService = (BaseService) FactoryBean.getBean("BaseService");
|
baseService.getSimpleJdbcTemplate().execute(sql.toString());
|
//刷新数据源
|
refreshDataSource("", ActionEnum.REFRESH);
|
this.print(response, "所有数据源域名重新绑定IP成功!");
|
}
|
} catch (Exception e) {
|
e.printStackTrace();
|
this.print(response, new CallBackMessage().sendErrorMessage(e.getMessage()));
|
}finally {
|
SpObserver.setDBtoInstance();
|
}
|
}
|
//新的保存,修改,测试 xin 2020-12-28 10:25:12
|
@RequestMapping("/newsetXml.do")
|
public void newsetXml(MultipartFile logoFile, DataSourceEntity datasoure, HttpServletRequest request,
|
HttpServletResponse response) throws Exception {
|
try {
|
int restart = (request.getParameter("restart")!=null?Integer.parseInt(request.getParameter("restart")):-1);//是否重启
|
if (restart!=-1) {
|
//重启
|
reStartTomcat(request, response);
|
return;
|
}
|
int saveSystemConfig=(request.getParameter("saveSystemConfig")!=null?Integer.parseInt(request.getParameter("saveSystemConfig")):-1);//
|
if(saveSystemConfig!=-1) {
|
//维护系统配置界面调用
|
saveSystemConfig(logoFile,datasoure,request,response);
|
return;
|
}
|
SpObserver.setDBtoDemo();
|
String pwd = datasoure.getPassword();
|
if (pwd == null || pwd.equals("")) {// 密码为空时,查询数据库获取密码
|
List<DataSourceEntity> dataSourceMap = demoIfc
|
.getDataSource(DemoConstant.getInstance().setActived(null).setDbId(datasoure.getDbId() + ""));
|
if (dataSourceMap != null && dataSourceMap.size() > 0) {
|
pwd = dataSourceMap.get(0).getPassword();
|
datasoure.setPassword(pwd);
|
}
|
}else {
|
datasoure.setPassword(ChangePassword.getEncryptPassword(pwd));//密码加密
|
}
|
if (datasoure.getActived()) {
|
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
|
String driverUrl = "jdbc:sqlserver://" + datasoure.getHost() + ":" + datasoure.getPort()
|
+ ";encrypt=true;trustServerCertificate=true;databaseName=" + datasoure.getDb();
|
try {
|
boolean isTestSuccess = DBHelper.getConnTest(driver, driverUrl, datasoure.getUserid(), datasoure.getPassword());
|
if (!isTestSuccess) {
|
super.print(response, new CallBackMessage().sendErrorMessage("数据库连接失败!"));
|
return;
|
}
|
String testConn = request.getParameter("testConn");//测试连接
|
if (testConn != null && testConn.equals("1")) {
|
super.print(response, new CallBackMessage().sendSuccessMessage("连接成功"));
|
return;
|
}
|
} catch (Exception e) {
|
super.print(response, new CallBackMessage()
|
.sendErrorMessage((e.getCause() != null ? e.getCause().getMessage() : e.getMessage())));
|
return;
|
}
|
}
|
if(logoFile!=null && !logoFile.isEmpty()) {//上传文件不为空
|
datasoure.setLogoIcon(logoFile.getBytes());
|
datasoure.setHasLogoIcon(false);
|
}
|
|
if (datasoure.getDemoDataSource() != null && (datasoure.getDemoDataSource()).equals(SpObserver.DEMOXML)) {// demo
|
xmlDoWrite(request, datasoure); // 写入 _demo.xml 文件
|
MultiDataSource multiDataSource = (MultiDataSource) FactoryBean.getBean("multiDataSource");
|
DemoConstant demoConstant=new DemoConstant();
|
demoConstant.setDbId(datasoure.getDbId()+"");
|
multiDataSource.setDataSourceByMap(datasoure,demoConstant);
|
this.print(response, new CallBackMessage().sendSuccessMessage("操作已经处理,请手动重启服务器才能生效!"));
|
return;
|
} else {
|
// 配置不保存
|
String invitationCode = (datasoure.getInvitationCode() == null ? null : datasoure.getInvitationCode());
|
if (invitationCode == null || invitationCode.equals("")) {
|
invitationCode = dIfc.getInvitationCode();
|
datasoure.setInvitationCode(invitationCode);
|
}
|
//解析域名对应的IP
|
processDomainToIP(datasoure);
|
String result = dIfc.updateDemo(datasoure);
|
if(StringUtils.isNotBlank(result)) {
|
String[] arrayResult=result.split(",");
|
String dbid=arrayResult[0];
|
String expiredMinute=arrayResult[1];
|
refreshDataSource(dbid , DataSourceActionEntity.ActionEnum.REFRESH); // 直接刷新本机
|
if (Integer.parseInt(expiredMinute)>=0) {
|
//过期则发通知退出系统返回登录页面 by danaus 2022/8/2 16:57
|
MessageInfo messageInfo = new MessageInfo();
|
messageInfo.setDbId(datasoure.getDbId());
|
messageInfo.setMsgType(MessageType.NOTICE_SYSTEM_STOP);
|
WebSocketMessageServer.publishMessageToRedis(messageInfo);
|
}
|
String datav = "{\"dbid\":" + dbid + ",\"invitationCode\":\"" + datasoure.getInvitationCode() + "\"}";
|
File file = new File(request.getSession().getServletContext().getRealPath(File.separator + "images" + File.separator + "login" + File.separator + dbid + File.separator + "logo.png"));
|
if (!logoFile.isEmpty()) {//修改成功后,再次把logo图片写入磁盘里 xin 2021-4-14 14:15:11
|
if (!file.getParentFile().exists() || !file.exists()) {//表示文件或目录是否存在
|
file.getParentFile().mkdirs();
|
file.createNewFile();
|
}
|
ImageIO.write(ImageIO.read(logoFile.getInputStream()), "png", file);
|
} else {
|
if (!datasoure.isHasLogoIcon() && file.exists()) {//默认图片情况下把上传过的图片删除
|
file.delete();//删除
|
}
|
}
|
if (datasoure.getActived()) {
|
this.print(response, new CallBackMessage().setData(datav).sendSuccessMessage("修改成功,可立即使用该数据源登录系统!"));
|
} else {
|
this.print(response,
|
new CallBackMessage().setData(datav).sendSuccessMessage("修改成功,由于该数据源未【启用】,因此不可立即使用该数据源登录系统!"));
|
}
|
return;
|
}
|
}
|
} catch (Exception e) {
|
super.print(response, new CallBackMessage()
|
.sendErrorMessage((e.getCause() != null ? e.getCause().getMessage() : e.getMessage())));
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
}
|
|
//Logo图片加载--- xin 2019-10-31 17:59:44
|
@RequestMapping("/getLogoIcon.do")
|
@SuppressWarnings("all")
|
private void getLogoIcon(HttpServletRequest request, HttpServletResponse response) throws IOException {
|
int dbid = Integer.parseInt(request.getParameter("dbid"));
|
BufferedImage bufImg = null;
|
File file = new File(request.getSession().getServletContext().getRealPath(File.separator + "images" + File.separator + "login" + File.separator + dbid + File.separator + "logo.png"));
|
// if (!file.getParentFile().exists() || !file.exists()) {//表示文件或目录是否存在
|
file.getParentFile().mkdirs();
|
file.createNewFile();
|
String mrPath = request.getSession().getServletContext().getRealPath(File.separator + "images" + File.separator + "login" + File.separator + "logo.png");
|
try {
|
SpObserver.setDBtoDemo();
|
String sql = " set nocount on \n" + " declare @dbid int = ? \n";
|
sql += "select LogoIcon from gsystem where id = @dbid ";
|
BaseService baseServer = (BaseService) FactoryBean.getBean("BaseService");
|
Map<String, Object> logo = baseServer.getJdbcTemplate().queryForMap(sql, new Object[]{dbid});
|
if (logo != null && logo.get("LogoIcon") != null && !"".equals(logo.get("LogoIcon"))) {
|
ByteArrayInputStream input=new ByteArrayInputStream((byte[]) logo.get("LogoIcon"));
|
try {
|
bufImg = ImageIO.read(input);
|
} catch (IIOException iioException) {
|
bufImg = makeGrey(input, mrPath);
|
}
|
} else {
|
bufImg = ImageIO.read(new File(mrPath));
|
}
|
ImageIO.write(bufImg, "png", response.getOutputStream());
|
} catch (Exception e) {
|
bufImg = ImageIO.read(new File(mrPath));
|
ImageIO.write(bufImg, "png", response.getOutputStream());
|
} finally {
|
SpObserver.setDBtoInstance();
|
ImageIO.write(bufImg, "png", file);
|
}
|
// } else {
|
// ImageIO.write(ImageIO.read(file), "png", response.getOutputStream());
|
// }
|
}
|
|
//对图片做灰化处理
|
public static BufferedImage makeGrey(ByteArrayInputStream in,String mrPath) throws IOException {
|
ImageInputStream input = ImageIO.createImageInputStream(in);
|
Iterator<?> readers = ImageIO.getImageReaders(input);
|
if (readers == null || !readers.hasNext()) {
|
return ImageIO.read(new File(mrPath));
|
}
|
ImageReader reader = (ImageReader) readers.next();
|
reader.setInput(input);
|
// 读取Raster (没有颜色的转换).
|
Raster raster = reader.readRaster(0, null);
|
BufferedImage img = new BufferedImage(raster.getWidth(), raster.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
|
img.getRaster().setRect(raster);
|
BufferedImage bufferedImage = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
|
bufferedImage.getGraphics().drawImage(img, 0, 0, img.getWidth(), img.getHeight(), null);
|
bufferedImage = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_sRGB), null).filter(img, bufferedImage);
|
return bufferedImage;
|
}
|
|
/**
|
* 重启服务器
|
*
|
* @param request
|
* @param out
|
* @throws LifecycleException
|
*/
|
private void reStartTomcat(HttpServletRequest request, HttpServletResponse response) throws LifecycleException {
|
EMBEDDED.stop();
|
try {
|
EMBEDDED.start();
|
} catch (Exception e) {
|
// e.printStackTrace();
|
DBHelper.log.debug("脚本启动服务时");
|
} finally {
|
// out.print("已经生成配置文件!必须重启服务,否则还是用原配置!");
|
request.getSession().setAttribute(SessionKey.DEMO_REF, null);// 处理之后无权限控制配置文件
|
this.print(response,"可以再操作了!");
|
}
|
}
|
|
public static boolean isNumberic(String str) {
|
if (str == null || "".equals(str)) return false ;
|
//检查字符串是否数字
|
for (int k = str.length();--k>=0;){
|
if (!Character.isDigit(str.charAt(k))){
|
return false ;
|
}
|
}
|
return true ;
|
}
|
|
/**
|
* 获得连接设置参数
|
*
|
* @param request
|
* @return Map<String, Object>
|
* @throws Exception
|
*/
|
private DataSourceEntity getConnMap(HttpServletRequest request1, HttpServletResponse response, String i)
|
throws Exception {
|
DataSourceEntity dataSourceEntity = new DataSourceEntity();
|
// 创建SmartUpload对象
|
SmartUpload Upload = new SmartUpload();
|
try {
|
// ------------获取logo图片值
|
// 初始化SmartUpload对象
|
Upload.initialize(request1.getServletContext(), request1, response);
|
// 设置允许上传文件类型
|
Upload.setAllowedFilesList("jpg,gif,jpeg,png");
|
//设置上传文件的最大值
|
Upload.setMaxFileSize(1024*1024);
|
//设置上传文件的总最大值
|
Upload.setTotalMaxFileSize(1024*1024);
|
// 上传
|
Upload.upload();
|
Files files = Upload.getFiles();
|
com.jspsmart.upload.File file = null;
|
for (int f = 0; f < files.getCount(); f++) { // 遍历上传的所有文件
|
file = files.getFile(f);
|
}
|
if (file!=null && !file.getFileName().equals("")) {
|
String path = EnvHelper.getPath() + EnvHelper.getJrxml();
|
Upload.save(path);
|
File file2 = new File(path + file.getFileName());
|
dataSourceEntity.setLogoIcon(input2byte(new FileInputStream(file2)));
|
if(file2!=null&&file2.exists()&& file2.isFile()) {
|
log.info("del>>userCode:"+request1.getSession().getAttribute(SessionKey.USERCODE)+"|dbid:"+request1.getSession().getAttribute(SessionKey.DATA_BASE_ID)+"|"+file2.getAbsolutePath());
|
file2.delete();
|
}
|
}
|
Request request = Upload.getRequest();
|
// -----end
|
|
String password = request.getParameter(DemoKey._PASSWORD + i);
|
if (password != null && !"".equals(password)) {
|
password = ChangePassword.getEncryptPassword(password);
|
} else {
|
password = "";
|
}
|
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
String expiredDateStr = request.getParameter("expiredDate");
|
Date expiredDate = null;
|
try {
|
if (expiredDateStr != null && !"".equals(expiredDateStr)) {
|
expiredDate = sdf.parse(expiredDateStr);
|
}
|
} catch (ParseException px) {
|
throw px;
|
}
|
String dbId = request.getParameter(DemoKey._ID + i);
|
|
if (isNumberic(dbId)) {
|
dataSourceEntity.setDbId(Integer.parseInt(dbId));
|
} else {
|
dataSourceEntity.setDemoDataSource(SpObserver.DEMOXML);
|
}
|
|
dataSourceEntity.setDb(request.getParameter(DemoKey._DB + i))
|
.setHost(request.getParameter(DemoKey._HOST + i)).setPassword(password)
|
.setPort(request.getParameter(DemoKey._PORT + i))
|
.setUserid(request.getParameter(DemoKey._USER_ID + i))
|
.setActived(request.getParameter(DemoKey._ACTIVED + i) != null
|
&& "1".equals(request.getParameter(DemoKey._ACTIVED + i)) ? true : false)
|
.setSystemID(request.getParameter(DemoKey._SYSTEM_ID + i))
|
.setSystemDescribe(request.getParameter(DemoKey._SYSTEM_DESCRIBE + i))
|
.setDomain(request.getParameter(DemoKey._DOMAIN)).setSmsUid(request.getParameter("smsUid"))
|
.setSmsKey(request.getParameter("smsKey"))
|
.setLimitUserNumber(request.getParameter("LimitUserNumber") != null
|
&& !request.getParameter("LimitUserNumber").equals("")
|
? Integer.parseInt(request.getParameter("LimitUserNumber")) : 0)
|
.setLimitDepartmentNumber(request.getParameter("LimitDepartmentNumber") != null
|
&& !request.getParameter("LimitDepartmentNumber").equals("")
|
? Integer.parseInt(request.getParameter("LimitDepartmentNumber")) : 0)
|
.setSystemType(request.getParameter("systemtype")).setExpiredDate(expiredDate)
|
.setShowAttendanceButton(request.getParameter("isShowAttendanceButton") != null
|
&& "1".equals(request.getParameter("isShowAttendanceButton")) ? true : false)
|
.setRemarks(request.getParameter("Remarks"))
|
.setDataCheckPageNum(request.getParameter("DataCheckPageNum") != null
|
&& !"".equals(request.getParameter("DataCheckPageNum"))
|
? Integer.parseInt(request.getParameter("DataCheckPageNum")) : 0)
|
.setCorpURL(request.getParameter("CorpURL")).setCorpId(request.getParameter("CorpId"))
|
.setMpAppId(request.getParameter("MpAppId")).setMpSecret(request.getParameter("MpSecret"))
|
.setMpToken(request.getParameter("MpToken")).setMpAesKey(request.getParameter("MpAesKey"))
|
.setMpOrgId(request.getParameter("MpOrgId")).setMiniAppId(request.getParameter("MiniAppId"))
|
.setMiniAppSecret(request.getParameter("MiniAppSecret"))
|
.setMiniAppToken(request.getParameter("MiniAppToken"))
|
.setMiniAppAesKey(request.getParameter("MiniAppAesKey"))
|
.setMiniAppOrgId(request.getParameter("MiniAppOrgId")).setMpMchId(request.getParameter("MpMchId"))
|
.setMpMchName(request.getParameter("MpMchName")).setMpMchKey(request.getParameter("MpMchKey"))
|
.setGeoWebApiKey(request.getParameter("GeoWebApiKey"))
|
.setInvitationCode(request.getParameter("InvitationCode"))
|
.setDisabledOpenNextPeriodId(request.getParameter("isDisabledOpenNextPeriodId") != null
|
&& "1".equals(request.getParameter("isDisabledOpenNextPeriodId")) ? true : false)
|
.setSystemSecretKey(request.getParameter("SystemSecretKey"))
|
.setSystemAccessKey(request.getParameter("SystemAccessKey"))
|
.setDockingSystem(request.getParameter("DockingSystem"))
|
.setUseAPP(request.getParameter("isUseAPP") != null && "1".equals(request.getParameter("isUseAPP"))
|
? true : false)
|
.setShowInLoginPage(request.getParameter("isShowInLoginPage") != null
|
&& "1".equals(request.getParameter("isShowInLoginPage")) ? true : false)
|
.setProtocol(request.getParameter("Protocol"))
|
.setAutoGenerateFormId(request.getParameter("isAutoGenerateFormId")!=null && "1".equals(request.getParameter("isAutoGenerateFormId"))?true:false)
|
.setTengXunMapLocationServiceKey(request.getParameter("TengXunMapLocationServiceKey"));
|
|
return dataSourceEntity;
|
} catch (Exception e) {
|
String error=(e.getCause()!=null?e.getCause().getMessage():e.getMessage());
|
if(error!=null && error.indexOf("1010")!=-1){
|
error="只能上传JPG,GIF,JPEG,PNG格式,并且图片大小在1M以内。";
|
}
|
throw new Exception(error);
|
} finally {
|
}
|
}
|
|
|
/**
|
* 生成一个连接文件
|
*
|
* @param map 所需集合信息
|
*/
|
private void xmlDoWrite(HttpServletRequest request,DataSourceEntity dataSourceEntity) throws Exception{
|
|
|
//String jdbcUrl = DBHelper.encryptHelper.encrypt("jdbc:jtds:sqlserver://" + DBHelper.getValue(map, DemoKey._HOST) + ":" + DBHelper.getValue(map, DemoKey._PORT) + ";DatabaseName=" + DBHelper.getValue(map, DemoKey._DB)) ;
|
String user = DBHelper.encryptHelper.encrypt(dataSourceEntity.getUserid()) ;
|
String password = dataSourceEntity.getPassword(); // DBHelper.encryptHelper.encrypt(DBHelper.encryptHelper.encrypt(DBHelper.getValue(map, DemoKey._PASSWORD))) ;
|
|
StringBuffer sBuffer = new StringBuffer();
|
sBuffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
|
sBuffer.append("\n<!DOCTYPE beans PUBLIC \"-//SPRING//DTD BEAN//EN\" \"http://www.springframework.org/dtd/spring-beans.dtd\">");
|
sBuffer.append("\n<beans>");
|
sBuffer.append("\n <bean id=\"" + dataSourceEntity.getDemoDataSource() + "\" class=\"com.yc.dataAccess.ComboPooledDataSource\" destroy-method=\"close\"> ");
|
|
//sBuffer.append("\n <property name=\"driverClass\" value=\"" + DBHelper.encryptHelper.encrypt("net.sourceforge.jtds.jdbc.Driver") + "\"/>");
|
//sBuffer.append("\n <property name=\"jdbcUrl\" value=\"" + jdbcUrl + "\"/>");
|
sBuffer.append("\n <property name=\"driverClass\" value=\"" + DBHelper.encryptHelper.encrypt(driverClass) + "\"/>");
|
sBuffer.append("\n <property name=\"jdbcUrl\" value=\"" + DBHelper.encryptHelper.encrypt("jdbc:sqlserver://" +dataSourceEntity.getHost() + ":" +dataSourceEntity.getPort() + ";encrypt=true;trustServerCertificate=true;databaseName=" +dataSourceEntity.getDb()) + "\"/>");
|
|
|
sBuffer.append("\n <property name=\"user\" value=\"" + user + "\"/>");
|
sBuffer.append("\n <property name=\"password\" value=\"" + password + "\"/>");
|
sBuffer.append("\n <property name=\"initialPoolSize\" value=\""+ initialPoolSize +"\"/>");
|
sBuffer.append("\n <property name=\"minPoolSize\" value=\""+ minPoolSize +"\"/>");
|
sBuffer.append("\n <property name=\"maxPoolSize\" value=\"" + maxPoolSize+"\"/>");
|
sBuffer.append("\n <property name=\"acquireIncrement\" value=\"" + acquireIncrement+ "\"/>");
|
sBuffer.append("\n <property name=\"maxIdleTime\" value=\"" + maxIdleTime + "\"/>");
|
sBuffer.append("\n <property name=\"idleConnectionTestPeriod\" value=\"" + idleConnectionTestPeriod + "\"/>");
|
sBuffer.append("\n <property name=\"maxStatements\" value=\"" + maxStatements + "\"/>");
|
sBuffer.append("\n </bean>");
|
sBuffer.append("\n</beans>");
|
try {
|
FAFO.writeFile(EnvHelper.getPath() + File.separator+"WEB-INF"+File.separator+"classes"+File.separator+"dataSource"+File.separator+ dataSourceEntity.getDemoDataSource() + ".xml", sBuffer.toString());
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
}
|
|
@RequestMapping("/doDelDemo.do")
|
public void doDelete(HttpServletRequest request, HttpServletResponse response) throws IOException {
|
int dbid = Integer.parseInt(request.getParameter("op").toString());
|
//String hostUrl = SettingKey.getHostUrl(request) ;
|
JsonObject json = new JsonObject();
|
try {
|
SpObserver.setDBtoDemo();
|
dIfc.deleteDemo(dbid);
|
DBHelper.cDao.delete(EnvHelper.getPath() + File.separator+"WEB-INF"+File.separator+"classes"+File.separator+"dataSource"+File.separator+"_" + dbid + ".xml");
|
//AsynchronousExecution.doRefreshUri(hostUrl,"/SyncDataSource.do?"+SessionKey.DATA_BASE_ID + "=" + dbid , "");
|
|
refreshDataSource(dbid+"",DataSourceActionEntity.ActionEnum.DELETE); //直接刷新本机
|
json.addProperty("hint", "删除成功!");
|
this.printJson(response, json.toString());
|
} catch (Exception e) {
|
e.printStackTrace();
|
json.addProperty("error", e.getCause()!= null?e.getCause().getMessage(): e.getMessage());
|
this.printJson(response, json.toString());
|
return ;
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
|
}
|
|
@RequestMapping("/getDyfied.do")
|
public void getDyfield(String headflag, String funcname, String fs, HttpServletRequest request, HttpServletResponse response) throws IOException, Exception {
|
|
String string = "select *,controltype=3 from " + funcname + fs + " where headflag=" + headflag;
|
try {
|
SpObserver.setDBtoInstance("_"+request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
|
List<Map<String, Object>> list = sqlDBHelperIfc.getHashMapObj(string);
|
String listmax = gridServiceIfc.getTypeLengthInfo(funcname + fs);
|
Map<String, Integer> maxMap = new HashMap<String, Integer>();
|
// 返回char nchar,varchar nvarchar类型的字段和长度。操作时间:2014-7-2 16:39:42
|
if (listmax != null) {
|
String[] max = listmax.split(",");
|
for (int m = 0; m < max.length; m++) {
|
String[] maindex = max[m].split("-");
|
maxMap.put(maindex[0], Integer.parseInt(maindex[1]));// 组装字段和长度 操作时间:2014-7-2 16:39:29
|
}
|
}
|
String writeHtml = "";
|
PanelParmHelper parmHelper = null;
|
PanelBean panelBean=null;
|
for (Map<String, Object> map : list) {
|
if (DBHelper.getValueInt(map, "visible") == 1) {
|
String yeId = DBHelper.getValue(map, "fieldid");
|
//----start by danaus 2020/2/20 12:12
|
parmHelper = new PanelParmHelper();
|
parmHelper.id = yeId;
|
panelBean=new PanelBean();
|
panelBean.setPHelper(parmHelper);
|
map.put(TypeControl.PANEL_INFO,panelBean);//把panelBean加到map,进行下一步处理
|
//----end
|
writeHtml = yeId + ";pb#1;pb#" + tControlDao.getComponentForPanel(map, false, maxMap) + ";fen#";// 创建控件
|
} else {
|
writeHtml = DBHelper.getValue(map, "fieldid") + ";pb#0;fen#";
|
}
|
this.print(response,writeHtml);
|
}
|
|
}catch (Exception e) {
|
this.print(response, e.getCause()!=null?e.getCause().getMessage():e.getMessage());
|
}finally {
|
SpObserver.setDBtoInstance();
|
}
|
}
|
|
@RequestMapping("/doCompany.do")
|
public void doCompany(HttpServletRequest request, HttpServletResponse response) throws IOException, Exception {
|
try {
|
int cltId = Integer.parseInt(request.getParameter("cltId"));
|
int statuid = Integer.parseInt(request.getParameter("statuid"));
|
HttpSession session = request.getSession();
|
String hostUrl = SettingKey.getHostUrl(request) ;
|
Integer dbid = null;
|
//FileDo fDo = new FileDo();
|
|
DataSourceEntity dataSourceEntity = MultiDataSource.getDataSourceMapByCltId( cltId) ;
|
|
if (statuid == 0) {// 未开通时执行的步骤
|
String exeSql = "exec pCreateDB " + cltId + ",'" + session.getAttribute(SessionKey.USERCODE) + "','" + session.getAttribute(SessionKey.USERNAME) + "'";
|
|
try {
|
SpObserver.setDBtoDemo();// 更改到demo数据库
|
sqlDBHelperIfc.dataSql(exeSql);// 第一部 还原数据库
|
//map = dIfc.getOneByCltId(cltId);
|
} catch (Exception e) {
|
throw new ApplicationException(e.getMessage());
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
if (dataSourceEntity != null) {
|
|
dataSourceEntity.setActived(true);
|
|
try {
|
SpObserver.setDBtoDemo();// 更改到demo数据库
|
dbid = dIfc.updateDemoSaaS(dataSourceEntity);// 第二步 重新更改
|
} catch (Exception e) {
|
throw new ApplicationException(e.getMessage());
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
|
// AsynchronousExecution.doRefreshUri(hostUrl,"/SyncDataSource.do?"+SessionKey.DATA_BASE_ID + "=" + dbid , "");
|
|
refreshDataSource(dbid+"",DataSourceActionEntity.ActionEnum.REFRESH); //直接刷新本机
|
|
|
//fDo.copy(EnvHelper.getPath() + "app"+File.separator + map.get(DemoKey._TEMP_CONNID), EnvHelper.getPath() + "app"+File.separator + map.get(DemoKey._ID));// 第三步 生成开通的源文件
|
|
//MultiDataSource multiDataSource = (MultiDataSource) FactoryBean.getBean("multiDataSource");
|
//multiDataSource.refreshDataSource(dbid+"");
|
}
|
} else if (statuid == 5) {// 删除时执行
|
try {
|
SpObserver.setDBtoDemo();
|
//map = dIfc.getOneByCltId(cltId);
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
if (dataSourceEntity != null) {
|
|
dataSourceEntity.setActived(false);
|
|
|
String exeSql = "exec pDropDB " + cltId + ",'" + session.getAttribute(SessionKey.USERCODE) + "','" + session.getAttribute(SessionKey.USERNAME) + "'";
|
try {
|
SpObserver.setDBtoDemo();// 更改到demo数据库
|
dbid = dIfc.updateDemoSaaS(dataSourceEntity);// 第一步 重新更改
|
sqlDBHelperIfc.dataSql(exeSql);// 第二步 删除数据库
|
} catch (Exception e) {
|
throw new ApplicationException(e.getMessage());
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
|
AsynchronousExecution.doRefreshUri(hostUrl,"/SyncDataSource.do?"+SessionKey.DATA_BASE_ID + "=" + dbid , "");
|
|
refreshDataSource(dbid+"",DataSourceActionEntity.ActionEnum.REFRESH); //直接刷新本机
|
|
//fDo.delete(EnvHelper.getPath() + "app" +File.separator + map.get(DemoKey._ID));// 第三步删除原文件
|
//multiDataSource.reflshDB(dbid+"", "0");
|
}
|
} else {// 2,3,4
|
|
if (dataSourceEntity != null) {
|
|
try {
|
SpObserver.setDBtoDemo();// 更改到demo数据库
|
sqlDBHelperIfc.doSql("update a set a.actived=0 from gsystem a where a.CltID =" + dataSourceEntity.getCltId());
|
} catch (Exception e) {
|
throw new ApplicationException(e.getMessage());
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
AsynchronousExecution.doRefreshUri(hostUrl,"/SyncDataSource.do?"+SessionKey.DATA_BASE_ID + "=" + dbid , "");
|
|
refreshDataSource(dbid+"",DataSourceActionEntity.ActionEnum.REFRESH); //直接刷新本机
|
|
//multiDataSource.reflshDB(dataSourceEntity.getId()+"", "0");
|
}
|
}
|
|
statuid = (statuid == 0 ? 1 : statuid);
|
try {
|
SpObserver.setDBtoDemo();// 更改到demo数据库
|
sqlDBHelperIfc.doSql("update a set status =" + statuid + " from _sysCustomer a where CltID =" + cltId);
|
this.print(response,"1");
|
} catch (Exception e) {
|
throw new ApplicationException(e.getMessage());
|
} finally {
|
SpObserver.setDBtoInstance();
|
}
|
|
} catch (Exception e) {
|
String mesString = (e.getCause() != null) ? e.getCause().getMessage() : e.getMessage();
|
this.print(response,mesString);
|
}
|
|
}
|
}
|