From ddcb146952922eaa8a5202ea9f3d022ca0d726be Mon Sep 17 00:00:00 2001 From: igor Date: Sun, 8 Dec 2024 15:24:40 +0600 Subject: [PATCH] add postData to get data --- metadata/dbms/DBMSRecords.java | 309 +++++++++++++++++---------------- metadata/dbms/DBMSTree.java | 33 ++-- metadata/dbms/dbms.xyz | 4 +- metadata/dbms/editrecord.js | 294 ++++++++++++++++++++----------- metadata/dbms/records.xyz | 9 +- metadata/dbms/showrecord.js | 218 ++++++++++++----------- metadata/dbms/tools.js | 87 ++++++++-- metadata/dbms/window.js | 14 +- metadata/include/tools.xyz | 10 +- 9 files changed, 585 insertions(+), 393 deletions(-) diff --git a/metadata/dbms/DBMSRecords.java b/metadata/dbms/DBMSRecords.java index 8c58c6c..c2c4016 100644 --- a/metadata/dbms/DBMSRecords.java +++ b/metadata/dbms/DBMSRecords.java @@ -1,4 +1,4 @@ -package dbms; //package com.geovizor.monitoring; //Главная 2 +package dbms; //package org.ccalm.monitoring; //Главная 2 import java.io.BufferedOutputStream; import java.io.BufferedWriter; @@ -12,6 +12,13 @@ import java.io.OutputStreamWriter; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.security.KeyFactory; +import java.security.NoSuchAlgorithmException; +import java.security.PublicKey; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.X509EncodedKeySpec; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; @@ -49,23 +56,26 @@ import javax.xml.xpath.XPathFactory; //import org.apache.commons.fileupload.disk.DiskFileItemFactory; //import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FileUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.MarkerManager; import org.json.JSONArray; import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.Marker; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.FileSystemResource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; +import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; +import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.SessionAttributes; +import org.springframework.web.bind.annotation.*; import org.springframework.web.context.ServletContextAware; import org.springframework.web.multipart.MultipartFile; import org.w3c.dom.CharacterData; @@ -79,25 +89,31 @@ import org.w3c.dom.ls.LSSerializer; import org.xml.sax.InputSource; import tctable.Tools; +import tools.DBTools; import tools.EmailUtility; import tools.Translation; import tools.User; @Controller -@SessionAttributes( { "user" }) //Сесионный объект public class DBMSRecords implements ServletContextAware { - //private static final Logger logger = LoggerFactory.getLogger(Translation.class); - private static final Logger logger = LoggerFactory.getLogger(DBMSRecords.class); + private static final Logger logger = LogManager.getLogger(DBMSRecords.class); + + private final NamedParameterJdbcTemplate jdbcTemplate; private ServletContext context; private Properties m_props=null; private String m_props_loc=""; - - //If not created object "user", create him. - @ModelAttribute("user") - public User populatePerson() { - return new User("none"); + + @Value("${public.key}") + String key_a_txt=""; + + @Autowired + private Environment env; + + @Autowired + public DBMSRecords(NamedParameterJdbcTemplate jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; } @Override @@ -105,27 +121,68 @@ public class DBMSRecords implements ServletContextAware { this.context=servletContext; } - public String sendError(int code, String message) { + public String sendError(int code, String message,String marker) { JSONObject json = new JSONObject(); json.put("error_code",code); json.put("error_message",message); + json.put("error_marker",marker); return json.toString(); } - //Документация по @RequestBody http://javastudy.ru/spring-mvc/json-xml/ application/xml - @RequestMapping(value = "/api/dbms/v09/records.xyz",method = {RequestMethod.POST,RequestMethod.GET}) //,produces = "text/plain; charset=utf-8" - @ResponseBody - public ResponseEntity ajaxRecords(@ModelAttribute User user, @RequestBody(required = false) byte[] reqData, @RequestParam(required=false,name="lng") String language_id) { + private PublicKey getPublicKey(){ + try { + byte[] keyBytes = Base64.getDecoder().decode(key_a_txt); + X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); + KeyFactory keyFactory = KeyFactory.getInstance("RSA"); + PublicKey key = keyFactory.generatePublic(spec); + return key; + } catch (Exception e) { + logger.error(e); + } + return null; + } + //Документация по @RequestBody http://javastudy.ru/spring-mvc/json-xml/ application/xml + //Обычно мантирую в: /api/dbms/v09/ + @RequestMapping(value = "/dbms",method = {RequestMethod.POST,RequestMethod.GET}) //,produces = "text/plain; charset=utf-8" + @ResponseBody + public ResponseEntity ajaxRecords( + @ModelAttribute User user, + @RequestBody(required = false) byte[] reqData, + @CookieValue(value = "jwt_a", defaultValue = "") String jwt_a, + @RequestParam(required=false,name="lng") String language_id + ) { final HttpHeaders httpHeaders= new HttpHeaders(); httpHeaders.setContentType(MediaType.APPLICATION_JSON); + String result=sendError(10000,"Request_not_processed",null); + + if(user.id==null || user.id.equals("null")) { // + if (jwt_a.equals("") || Tools.countOccurrences(jwt_a, '.') != 2) { + result = sendError(10000, "Please_send_a_valid_JWT_token",null); + return new ResponseEntity(result, httpHeaders, HttpStatus.OK); + } + //Проверяю подпись токена + Jws claims = null; + PublicKey key_a = getPublicKey(); //SecretKey key_a = new SecretKeySpec(Base64.getDecoder().decode(env.getProperty("access.key")), "HmacSHA256"); + try { + claims = Jwts.parserBuilder() + .setSigningKey(key_a) + .build() + .parseClaimsJws(jwt_a); + } catch (Exception e) { + return new ResponseEntity("JWT_token_verification_error", httpHeaders, HttpStatus.OK); + } + user.id = claims.getBody().get("user_id").toString(); + } + + if(language_id!=null && !language_id.equals("")) user.language_id=language_id; logger.info("user.id="+user.id+" user.name="+user.name+" user.language_id="+user.language_id+" user.country_id="+user.country_id); boolean error=false; - String result=sendError(1,"Request not processed!"); + result=sendError(10000,"Request not processed!",null); if(reqData==null) return new ResponseEntity(result, httpHeaders, HttpStatus.OK); @@ -141,20 +198,18 @@ public class DBMSRecords implements ServletContextAware { String mail_port = ""; String mail_login = ""; String mail_password = ""; - Properties prop = new Properties(); try { - prop.load(new FileInputStream("application.properties")); // load a properties file - db_url = prop.getProperty("spring.datasource.url"); - db_login = prop.getProperty("spring.datasource.username"); - db_password = prop.getProperty("spring.datasource.password"); - data_dir = prop.getProperty("data.dir"); - mail_host = prop.getProperty("mail.host"); - mail_port = prop.getProperty("mail.port"); - mail_login = prop.getProperty("mail.login"); - mail_password = prop.getProperty("mail.password"); + db_url = env.getProperty("spring.datasource.url"); + db_login = env.getProperty("spring.datasource.username"); + db_password = env.getProperty("spring.datasource.password"); + data_dir = env.getProperty("data.dir"); + mail_host = env.getProperty("mail.host"); + mail_port = env.getProperty("mail.port"); + mail_login = env.getProperty("mail.login"); + mail_password = env.getProperty("mail.password"); } catch (Exception e) { e.printStackTrace(); - logger.error("Error load application.properties",e); + logger.error("Error load org_ccalm_main.properties",e); } String jspPath = context.getRealPath("/"); @@ -176,7 +231,7 @@ public class DBMSRecords implements ServletContextAware { } catch (Exception ex) { logger.info(ex.getMessage()); //return ""; - return new ResponseEntity(sendError(1,"Parsing request error!"), httpHeaders, HttpStatus.OK); + return new ResponseEntity(sendError(10000,"Parsing request error!",null), httpHeaders, HttpStatus.OK); } if (doc != null) { @@ -193,15 +248,17 @@ public class DBMSRecords implements ServletContextAware { Class.forName("org.postgresql.Driver"); conn = DriverManager.getConnection(db_url, db_login, db_password); if (conn != null) { - logger.info("Connect is OK!"); + String uuid = UUID.randomUUID().toString(); + Marker marker = MarkerManager.getMarker(uuid); + logger.info(marker,"Connect is OK!"); } else { error=true; - result=sendError(1,"An error occurred while connecting to the database!"); + result=sendError(10000,"An error occurred while connecting to the database!",null); } } catch (Exception ex) { logger.info(ex.getMessage()); error=true; - result=sendError(1,"An error occurred while connecting to the database!"); + result=sendError(10000,"An error occurred while connecting to the database!",null); } try { @@ -212,7 +269,7 @@ public class DBMSRecords implements ServletContextAware { } catch (SQLException ex) { logger.info(ex.getMessage()); error=true; - result=sendError(1,"An set TYPE_SCROLL_SENSITIVE!"); + result=sendError(10000,"An set TYPE_SCROLL_SENSITIVE!",null); } //response.getWriter().append("fn="+fn); @@ -286,7 +343,7 @@ public class DBMSRecords implements ServletContextAware { allow = "1"; try { stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); - sql_query = "select main.p_getAccess(" + user.id + ", 'Select_" + name + "') as acc;"; + sql_query = "select main.get_Access(" + user.id + ", 'Select_" + name + "') as acc;"; rs = stt.executeQuery(sql_query); if (rs != null) { try { @@ -302,7 +359,7 @@ public class DBMSRecords implements ServletContextAware { } } catch (SQLException ex) { logger.info(ex.getMessage() + " SQL=" + sql_query); - result=sendError(1,"Error: " + ex.getMessage()); + result=sendError(10000,"Error: " + ex.getMessage(),null); error=true; }finally { if(rs!=null) try{rs.close();}catch(SQLException ex){} @@ -314,7 +371,7 @@ public class DBMSRecords implements ServletContextAware { allow = "1"; try { stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); - rs = stt.executeQuery("select main.p_getAccess(" + user.id + ", 'Insert_" + name + "') as acc;"); + rs = stt.executeQuery("select main.get_Access(" + user.id + ", 'Insert_" + name + "') as acc;"); if (rs != null) { try { if (rs.next()) @@ -329,7 +386,7 @@ public class DBMSRecords implements ServletContextAware { } } catch (SQLException ex) { logger.info(ex.getMessage()); - result=sendError(1,"Error: " + ex.getMessage()); + result=sendError(10000,"Error: " + ex.getMessage(),null); error=true; }finally { if(rs!=null) try{rs.close();}catch(SQLException ex){} @@ -341,7 +398,7 @@ public class DBMSRecords implements ServletContextAware { allow = "1"; try { stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); - rs = stt.executeQuery("select main.p_getAccess(" + user.id + ", 'Update_" + name + "') as acc;"); + rs = stt.executeQuery("select main.get_Access(" + user.id + ", 'Update_" + name + "') as acc;"); if (rs != null) { try { if (rs.next()) @@ -356,7 +413,7 @@ public class DBMSRecords implements ServletContextAware { } } catch (SQLException ex) { logger.info(ex.getMessage()); - result=sendError(1,"Error: " + ex.getMessage()); + result=sendError(10000,"Error: " + ex.getMessage(),null); error=true; }finally { if(rs!=null) try{rs.close();}catch(SQLException ex){} @@ -368,7 +425,7 @@ public class DBMSRecords implements ServletContextAware { allow = "1"; try { stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); - rs = stt.executeQuery("select main.p_getAccess(" + user.id + ", 'Delete_" + name + "') as acc;"); + rs = stt.executeQuery("select main.get_Access(" + user.id + ", 'Delete_" + name + "') as acc;"); if (rs != null) { try { if (rs.next()) @@ -383,7 +440,7 @@ public class DBMSRecords implements ServletContextAware { } } catch (SQLException ex) { logger.info(ex.getMessage()); - result=sendError(1,"Error: " + ex.getMessage()); + result=sendError(10000,"Error: " + ex.getMessage(),null); error=true; }finally { if(rs!=null) try{rs.close();}catch(SQLException ex){} @@ -480,7 +537,7 @@ public class DBMSRecords implements ServletContextAware { } } - sql_query = Tools.replaceAll(sql_query,"${" + vn + "}", getSQLValue(vt, val)); + sql_query = Tools.replaceAll(sql_query,"${" + vn + "}", DBTools.getSQLValue(vt, val)); } if(user.id==null) sql_query = Tools.replaceAll(sql_query,"${_user_id}", "null"); @@ -509,7 +566,7 @@ public class DBMSRecords implements ServletContextAware { rs=null; } catch (SQLException ex) { logger.info(ex.getMessage()); - result=sendError(1,"Error: " + ex.getMessage()+"\n\nSQL query: " + sql_query); + result=sendError(10000,"Error: " + ex.getMessage()+"\n\nSQL query: " + sql_query,null); error=true; } } @@ -594,7 +651,7 @@ public class DBMSRecords implements ServletContextAware { } } } - sql_query=Tools.replaceAll(sql_query,"${" + vn + "}", getSQLValue(vt, val)); + sql_query=Tools.replaceAll(sql_query,"${" + vn + "}", DBTools.getSQLValue(vt, val)); } if(user.id==null) sql_query = Tools.replaceAll(sql_query,"${_user_id}", "null"); else sql_query = Tools.replaceAll(sql_query,"${_user_id}", (String) user.id); @@ -621,7 +678,7 @@ public class DBMSRecords implements ServletContextAware { stt.close(); } catch (SQLException ex) { logger.info(ex.getMessage()); - result=sendError(1,"Error: " + ex.getMessage()+"\n\nSQL query: " + sql_query); + result=sendError(10000,"Error: " + ex.getMessage()+"\n\nSQL query: " + sql_query,null); error=true; } } @@ -683,10 +740,10 @@ public class DBMSRecords implements ServletContextAware { vt=nodeList.item(0).getAttributes().getNamedItem("vt").getNodeValue(); } - sql_query=Tools.replaceAll(sql_query,"${"+vn+"}",getSQLValue(vt,val)); + sql_query=Tools.replaceAll(sql_query,"${"+vn+"}",DBTools.getSQLValue(vt,val)); } */ - sql_query = Tools.replaceAll(sql_query,"${id}", getSQLValue("string", obj_id)); //string а не i4 так как некоторые таблицы с uuid + sql_query = Tools.replaceAll(sql_query,"${id}", DBTools.getSQLValue("string", obj_id)); //string а не i4 так как некоторые таблицы с uuid if(user.id==null) sql_query = Tools.replaceAll(sql_query,"${_user_id}", "null"); else sql_query = Tools.replaceAll(sql_query,"${_user_id}", (String) user.id); @@ -711,7 +768,7 @@ public class DBMSRecords implements ServletContextAware { stt.close(); } catch (SQLException ex) { logger.info(ex.getMessage()); - result=sendError(1,"Error: " + ex.getMessage()+"\n\nSQL query: " + sql_query); + result=sendError(10000,"Error: " + ex.getMessage()+"\n\nSQL query: " + sql_query,null); error=true; } @@ -792,7 +849,7 @@ public class DBMSRecords implements ServletContextAware { String vt = nextnode.getAttributes().getNamedItem("vt").getNodeValue(); String val = getCharacterDataFromElement((Element) nextnode); - val = getSQLValue(vt, val); + val = DBTools.getSQLValue(vt, val); sql_query = Tools.replaceAll(sql_query,"${" + vn + "}", val); } catch (Exception ex) { @@ -818,7 +875,7 @@ public class DBMSRecords implements ServletContextAware { } } catch (Exception ex) { logger.info(ex.getMessage()); - result=sendError(1,"Error: " + ex.getMessage()+"\n\nSQL query: " + sql_query); + result=sendError(10000,"Error: " + ex.getMessage()+"\n\nSQL query: " + sql_query,null); error=true; } pagecount = (int) Math.ceil((double) pagecount / (double) rowspagecount); @@ -969,9 +1026,11 @@ public class DBMSRecords implements ServletContextAware { stmt=null; } catch (SQLException ex) { - logger.info(ex.getMessage()); + String uuid = UUID.randomUUID().toString(); + Marker marker = MarkerManager.getMarker(uuid); + logger.error(marker,ex.getMessage(),ex); ex.printStackTrace(); - result=sendError(1,"Error: " + ex.getMessage()+"\n\nSQL query: " + sql_query); + result=sendError(10000,trt(conn,"Error_executing_SQL_query",user),uuid); error=true; } } @@ -1016,7 +1075,7 @@ public class DBMSRecords implements ServletContextAware { logger.info(ex.getMessage()); } - sql_query = Tools.replaceAll(sql_query,"${"+idname+"}", getSQLValue("string", id)); + sql_query = Tools.replaceAll(sql_query,"${"+idname+"}", DBTools.getSQLValue("string", id)); if(user.id==null) sql_query = Tools.replaceAll(sql_query,"${_user_id}", "null"); else sql_query = Tools.replaceAll(sql_query,"${_user_id}", (String) user.id); @@ -1066,7 +1125,7 @@ public class DBMSRecords implements ServletContextAware { stt=null; } catch (SQLException ex) { logger.info(ex.getMessage()); - result=sendError(1,"Error: " + ex.getMessage()+"\n\nSQL query: " + sql_query); + result=sendError(10000,"Error: " + ex.getMessage()+"\n\nSQL query: " + sql_query,null); error=true; } } @@ -1154,7 +1213,7 @@ public class DBMSRecords implements ServletContextAware { String vt = nextnode.getAttributes().getNamedItem("vt").getNodeValue(); String val = getCharacterDataFromElement((Element) nextnode); - val = getSQLValue(vt, val); + val = DBTools.getSQLValue(vt, val); sql_query = Tools.replaceAll(sql_query,"${" + vn + "}", val); } catch (Exception ex) { @@ -1201,14 +1260,14 @@ public class DBMSRecords implements ServletContextAware { stt=null; } catch (SQLException ex) { logger.info(ex.getMessage()); - result=sendError(1,"Error: " + ex.getMessage()+"\n\nSQL query: " + sql_query); + result=sendError(10000,"Error: " + ex.getMessage()+"\n\nSQL query: " + sql_query,null); error=true; } } else { - result=sendError(1,"Could not find the requested node!"); + result=sendError(10000,"Could not find the requested node!",null); error=true; } } @@ -1273,7 +1332,7 @@ public class DBMSRecords implements ServletContextAware { } catch (SQLException ex) { logger.info(ex.getMessage()); //xmlstring = ""; - xmlstring=sendError(1,"Error: " + ex.getMessage()); + xmlstring=sendError(10000,"Error: " + ex.getMessage(),null); error=true; } @@ -1310,14 +1369,14 @@ public class DBMSRecords implements ServletContextAware { } catch (SQLException ex) { logger.info(ex.getMessage()); //xmlstring = ""; - xmlstring=sendError(1,"Error: " + ex.getMessage()); + xmlstring=sendError(10000,"Error: " + ex.getMessage(),null); } } xmlstring = ""; } else { //xmlstring = ""; - xmlstring=sendError(1,"This email address was not registered!"); + xmlstring=sendError(10000,"This email address was not registered!",null); } } else if (cmd.equals("1")) //Logout @@ -1335,7 +1394,7 @@ public class DBMSRecords implements ServletContextAware { } catch (SQLException ex) { logger.info(ex.getMessage()); //xmlstring = ""; - xmlstring=sendError(1,"Error: " + ex.getMessage() + "\n\nSQL query: " + sql_query); + xmlstring=sendError(10000,"Error: " + ex.getMessage() + "\n\nSQL query: " + sql_query,null); error=true; } @@ -1379,17 +1438,17 @@ public class DBMSRecords implements ServletContextAware { } String val; - val = getSQLValue("i4", user_id); + val = DBTools.getSQLValue("i4", user_id); sql_query = Tools.replaceAll(sql_query,"${user_id}", val); - val = getSQLValue("string", login); + val = DBTools.getSQLValue("string", login); sql_query = Tools.replaceAll(sql_query,"${login}", val); - val = getSQLValue("string", password); + val = DBTools.getSQLValue("string", password); sql_query = Tools.replaceAll(sql_query,"${password}", val); - val = getSQLValue("string", hash); + val = DBTools.getSQLValue("string", hash); sql_query = Tools.replaceAll(sql_query,"${hash}", val); - val = getSQLValue("string", ""/*request.getSession().getId()*/); + val = DBTools.getSQLValue("string", ""/*request.getSession().getId()*/); sql_query = Tools.replaceAll(sql_query,"${sessionid}", val); - val = getSQLValue("string", ""/*request.getRemoteAddr()*/); + val = DBTools.getSQLValue("string", ""/*request.getRemoteAddr()*/); sql_query = Tools.replaceAll(sql_query,"${ip}", val); //logger.info("sql_query = " + sql_query); @@ -1419,7 +1478,7 @@ public class DBMSRecords implements ServletContextAware { }else { //xmlstring = ""; - xmlstring=sendError(1,trt(conn,"Error_in_login_or_password",user)); + xmlstring=sendError(10000,trt(conn,"Error_in_login_or_password",user),null); } } rs.close(); @@ -1429,7 +1488,7 @@ public class DBMSRecords implements ServletContextAware { } catch (SQLException ex) { logger.info(ex.getMessage()); //xmlstring = ""; - xmlstring=sendError(1,"Error: " + ex.getMessage() + "\n\nSQL query: " + sql_query); + xmlstring=sendError(10000,"Error: " + ex.getMessage() + "\n\nSQL query: " + sql_query,null); error=true; } @@ -1443,7 +1502,7 @@ public class DBMSRecords implements ServletContextAware { //Check exists user by email email sql_query = "select id from main._users where email=LOWER(TRIM(${email}))"; - val = getSQLValue("string", email); + val = DBTools.getSQLValue("string", email); sql_query = Tools.replaceAll(sql_query,"${email}", val); try { Statement stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); @@ -1452,7 +1511,7 @@ public class DBMSRecords implements ServletContextAware { try { if (rs.next()) { //xmlstring = ""; - xmlstring=sendError(1,trt(conn,"E_mail_already_exists_in_the_database",user)); + xmlstring=sendError(10000,trt(conn,"E_mail_already_exists_in_the_database",user),null); error=true; } } catch (SQLException ex) { @@ -1464,7 +1523,7 @@ public class DBMSRecords implements ServletContextAware { } catch (SQLException ex) { logger.info(ex.getMessage()); //xmlstring = ""; - xmlstring=sendError(1,"Error: " + ex.getMessage()); + xmlstring=sendError(10000,"Error: " + ex.getMessage(),null); error=true; } @@ -1472,21 +1531,21 @@ public class DBMSRecords implements ServletContextAware { String newPass = getRandomString(8); sql_query = "select * from main.p__Users_1(4,${country_id},${surname},${name},${company},${position},${phone},${email},${password});"; - val = getSQLValue("i4", country_id); + val = DBTools.getSQLValue("i4", country_id); sql_query = Tools.replaceAll(sql_query,"${country_id}", val); - val = getSQLValue("string", lastname); + val = DBTools.getSQLValue("string", lastname); sql_query = Tools.replaceAll(sql_query,"${surname}", val); - val = getSQLValue("string", firstname); + val = DBTools.getSQLValue("string", firstname); sql_query = Tools.replaceAll(sql_query,"${name}", val); - val = getSQLValue("string", company); + val = DBTools.getSQLValue("string", company); sql_query = Tools.replaceAll(sql_query,"${company}", val); - val = getSQLValue("string", position); + val = DBTools.getSQLValue("string", position); sql_query = Tools.replaceAll(sql_query,"${position}", val); - val = getSQLValue("string", phone); + val = DBTools.getSQLValue("string", phone); sql_query = Tools.replaceAll(sql_query,"${phone}", val); - val = getSQLValue("string", email); + val = DBTools.getSQLValue("string", email); sql_query = Tools.replaceAll(sql_query,"${email}", val); - val = getSQLValue("string", newPass); + val = DBTools.getSQLValue("string", newPass); sql_query = Tools.replaceAll(sql_query,"${password}", val); //logger.info("sql_query = " + sql_query); @@ -1530,7 +1589,7 @@ public class DBMSRecords implements ServletContextAware { } catch (SQLException ex) { logger.info(ex.getMessage()); //xmlstring = ""; - xmlstring=sendError(1,"Error: " + ex.getMessage()); + xmlstring=sendError(10000,"Error: " + ex.getMessage(),null); error=true; } } @@ -1561,7 +1620,7 @@ public class DBMSRecords implements ServletContextAware { stt=null; } catch (SQLException ex) { logger.info(ex.getMessage()); - result=sendError(1,"Error: " + ex.getMessage()); + result=sendError(10000,"Error: " + ex.getMessage(),null); error=true; } @@ -1656,7 +1715,7 @@ public class DBMSRecords implements ServletContextAware { String vt = nextnode.getAttributes().getNamedItem("vt").getNodeValue(); String val = getCharacterDataFromElement((Element) nextnode); - val = getSQLValue(vt, val); + val = DBTools.getSQLValue(vt, val); sql_query = Tools.replaceAll(sql_query,"${" + vn + "}", val); } catch (Exception ex) { @@ -1742,7 +1801,7 @@ public class DBMSRecords implements ServletContextAware { } } catch (IOException ex) { logger.info(ex.getMessage()); - result=sendError(1,"Error: " + ex.getMessage()); + result=sendError(10000,"Error: " + ex.getMessage(),null); error=true; } finally { try { @@ -1760,7 +1819,7 @@ public class DBMSRecords implements ServletContextAware { stt=null; } catch (SQLException ex) { logger.info(ex.getMessage()); - result=sendError(1,"Error: " + ex.getMessage() + "\n\nSQL query: " + sql_query); + result=sendError(10000,"Error: " + ex.getMessage() + "\n\nSQL query: " + sql_query,null); error=true; } } @@ -1857,7 +1916,7 @@ public class DBMSRecords implements ServletContextAware { */ } else { - result=sendError(1,"Unknown function \"" + fn + "\" !"); + result=sendError(10000,"Unknown function \"" + fn + "\" !",null); error=true; } @@ -1878,15 +1937,13 @@ public class DBMSRecords implements ServletContextAware { String db_url=""; String db_login=""; String db_password=""; - Properties prop = new Properties(); try { - prop.load(new FileInputStream("application.properties")); // load a properties file - db_url = prop.getProperty("spring.datasource.url"); - db_login = prop.getProperty("spring.datasource.username"); - db_password = prop.getProperty("spring.datasource.password"); + db_url = env.getProperty("spring.datasource.url"); + db_login = env.getProperty("spring.datasource.username"); + db_password = env.getProperty("spring.datasource.password"); } catch (Exception e) { e.printStackTrace(); - logger.error("Error load application.properties",e); + logger.error("Error load org_ccalm_main.properties",e); } @@ -1895,7 +1952,9 @@ public class DBMSRecords implements ServletContextAware { Class.forName("org.postgresql.Driver"); conn = DriverManager.getConnection(db_url, db_login, db_password); if (conn != null) { - logger.info("Connect is OK!"); + String uuid = UUID.randomUUID().toString(); + Marker marker = MarkerManager.getMarker(uuid); + logger.info(marker,"Connect is OK!"); } else { logger.info("An error occurred while connecting to the database!"); } @@ -1994,7 +2053,6 @@ public class DBMSRecords implements ServletContextAware { } } - @RequestMapping(value = "/upload", method = { RequestMethod.GET, RequestMethod.POST }) @ResponseBody public String uploadFile(HttpServletResponse response,@RequestParam(required=false,name="file") MultipartFile file) { @@ -2002,13 +2060,11 @@ public class DBMSRecords implements ServletContextAware { String result=""; String data_dir = ""; - Properties prop = new Properties(); try { - prop.load(new FileInputStream("application.properties")); // load a properties file - data_dir = prop.getProperty("data.dir"); + data_dir = env.getProperty("data.dir"); } catch (Exception e) { e.printStackTrace(); - logger.error("Error load application.properties",e); + logger.error("Error load org_ccalm_main.properties",e); } @@ -2081,13 +2137,11 @@ public class DBMSRecords implements ServletContextAware { public FileSystemResource sendReport(HttpServletResponse response,@RequestParam(required=true,name="file") String fileName) { String data_dir = ""; - Properties prop = new Properties(); try { - prop.load(new FileInputStream("application.properties")); // load a properties file - data_dir = prop.getProperty("data.dir"); + data_dir = env.getProperty("data.dir"); } catch (Exception e) { e.printStackTrace(); - logger.error("Error load application.properties",e); + logger.error("Error load org_ccalm_main.properties",e); } File file = new File(data_dir + "temp" + File.separator + fileName); @@ -2106,43 +2160,6 @@ public class DBMSRecords implements ServletContextAware { } } - String getSQLValue(String t, String v) { - //if($t=='object' && (strtoupper($v)!='NULL' && gettype($v)=='string')) $t='string'; //Если id шники uuid - - if (t.equals("object") || t.equals("uid")) { - if (v.equals("")) - v = "NULL"; - } else if (t.equals("i4") || t.equals("integer")) { - if (v.equals("")) - v = "NULL"; - } else if (t.equals("f8")) { - if (v.equals("")) - v = "NULL"; - v = Tools.replaceAll(v,",", "."); //The decimal part: point. - } else if (t.equals("f4")) { - if (v.equals("")) - v = "NULL"; - v = Tools.replaceAll(v,",", "."); //The decimal part: point. - } else if (t.equals("b")) { - if (v.equals("")) - v = "NULL"; - else if (v.equals("1")) - v = "true"; - else if (v.equals("0")) - v = "false"; - } else if (t.equals("string") || t.equals("text") || t.equals("dateTime") || t.equals("date")) { - if (v.equals("")) { - v = "NULL"; - } else { - v = Tools.replaceAll(v,"'", "''"); - v = "'" + v + "'"; - } - } else { - v = "'" + v + "'"; - } - return v; - } - private String nodeToString(Node node) { StringWriter sw = new StringWriter(); try { diff --git a/metadata/dbms/DBMSTree.java b/metadata/dbms/DBMSTree.java index 7b5b143..590a302 100644 --- a/metadata/dbms/DBMSTree.java +++ b/metadata/dbms/DBMSTree.java @@ -11,7 +11,7 @@ import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; -import javax.servlet.ServletContext; +//import javax.servlet.ServletContext; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; @@ -20,6 +20,7 @@ import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; +import jakarta.servlet.ServletContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.ClassPathResource; @@ -39,22 +40,17 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; import tctable.Tools; +import tools.DBTools; +import tools.XMLTools; import tools.User; -import tools.xml.XMLTools; + @Controller -@SessionAttributes( { "user" }) //Сесионный объект! public class DBMSTree implements ServletContextAware { private static final Logger logger = LoggerFactory.getLogger(DBMSTree.class); private ServletContext context; - //If not created object "user", create him. - @ModelAttribute("user") - public User populatePerson() { - return new User("none"); - } - @RequestMapping(value = "/tree",method = RequestMethod.POST,produces = "application/xml; charset=utf-8") @ResponseBody public Object ajaxTamer(@ModelAttribute User user,@RequestBody byte[] reqData,@RequestParam(required=false,name="lng") String language_id) { @@ -73,13 +69,13 @@ public class DBMSTree implements ServletContextAware { String db_password=""; Properties prop = new Properties(); try { - prop.load(new FileInputStream("application.properties")); // load a properties file + prop.load(new FileInputStream("org_ccalm_main.properties")); // load a properties file db_url = prop.getProperty("spring.datasource.url"); db_login = prop.getProperty("spring.datasource.username"); db_password = prop.getProperty("spring.datasource.password"); } catch (Exception e) { e.printStackTrace(); - logger.error("Error load application.properties",e); + logger.error("Error load org_ccalm_main.properties",e); } Connection conn = null; @@ -188,7 +184,7 @@ public class DBMSTree implements ServletContextAware { { String vt = nF.getAttributes().getNamedItem("vt").getNodeValue(); String val= XMLTools.getCDATAValue(nF); - sql = sql.replace("${" + nF.getAttributes().getNamedItem("n").getNodeValue() + "}", Tools.getSQLValue(vt, val)); + sql = sql.replace("${" + nF.getAttributes().getNamedItem("n").getNodeValue() + "}", DBTools.getSQLValue(vt, val)); } nF=nF.getNextSibling(); } @@ -218,9 +214,9 @@ public class DBMSTree implements ServletContextAware { String iid=""; String val=""; - if(Tools.hasColumn(rs,"id")) fid=rs.getString("id"); else fid=""; //Уникальный id записи - if(Tools.hasColumn(rs,"icon_id")) iid=rs.getString("icon_id"); else iid=""; //id значка - if(Tools.hasColumn(rs,caption)) val=rs.getString(caption); else val=""; //Заголовок + if(DBTools.hasColumn(rs,"id")) fid=rs.getString("id"); else fid=""; //Уникальный id записи + if(DBTools.hasColumn(rs,"icon_id")) iid=rs.getString("icon_id"); else iid=""; //id значка + if(DBTools.hasColumn(rs,caption)) val=rs.getString(caption); else val=""; //Заголовок String visible = ""; if(tmpNode.getAttributes().getNamedItem("visible").getNodeValue().equals("0")) visible=" visible=\"0\" "; @@ -248,7 +244,7 @@ public class DBMSTree implements ServletContextAware { String fval=""; try { - if(Tools.hasColumn(rs,fname)) + if(DBTools.hasColumn(rs,fname)) { fval=rs.getString(fname); }else @@ -432,17 +428,16 @@ public class DBMSTree implements ServletContextAware { { if(nF.getNodeName().equals("column")) { - sql = sql.replace("{"+nF.getAttributes().getNamedItem("n").getNodeValue()+"}", Tools.getSQLValue(nF.getAttributes().getNamedItem("vt").getNodeValue(),XMLTools.getCDATAValue(nF))); + sql = sql.replace("{"+nF.getAttributes().getNamedItem("n").getNodeValue()+"}", DBTools.getSQLValue(nF.getAttributes().getNamedItem("vt").getNodeValue(),XMLTools.getCDATAValue(nF))); } nF=nF.getNextSibling(); } } return sql; } - + @Override public void setServletContext(ServletContext servletContext) { this.context=servletContext; } - } diff --git a/metadata/dbms/dbms.xyz b/metadata/dbms/dbms.xyz index 23bf963..d63d43e 100644 --- a/metadata/dbms/dbms.xyz +++ b/metadata/dbms/dbms.xyz @@ -272,7 +272,7 @@ $allow_ins=false; $allow_upd=false; $allow_del=false; - $sql_query='select '.$Schema.'p_getaccess(:user_id1,:action_insert) as ins,'.$Schema.'p_getaccess(:user_id2,:action_update) as upd,'.$Schema.'p_getaccess(:user_id3,:action_delete) as del;'; + $sql_query='select '.$Schema.'get_access(:user_id1,:action_insert) as ins,'.$Schema.'get_access(:user_id2,:action_update) as upd,'.$Schema.'get_access(:user_id3,:action_delete) as del;'; $stmt = $db->prepare($sql_query); $stmt->bindValue(':user_id1', $_SESSION['USER_ID'], PDO::PARAM_INT); //getSQLValue(gettype($_SESSION['USER_ID']),$_SESSION['USER_ID']) $stmt->bindValue(':user_id2', $_SESSION['USER_ID'], PDO::PARAM_INT); //getSQLValue(gettype($_SESSION['USER_ID']),$_SESSION['USER_ID']) @@ -1343,7 +1343,7 @@ print ' '; print ' '; print ' '; - print '
'; + print ' '; print ' '; print '
'; print ' '; diff --git a/metadata/dbms/editrecord.js b/metadata/dbms/editrecord.js index ecdcc92..b5a267d 100644 --- a/metadata/dbms/editrecord.js +++ b/metadata/dbms/editrecord.js @@ -36,8 +36,6 @@ class EdtRec this.pBarCnt=0; //Progress Bar this.pBarDiv=null; //Progress Bar - this.request = new TRequest(this); - //this.fields = new Array(); ERec_mas[this.uid]=this; @@ -82,10 +80,24 @@ class EdtRec this.f_TypeName=typeName; this.f_Settings=settings; this.record_id=id; - if(this.request.callServer(ScriptName,'')) - { - this.showProgressBar(); - } + + postXMLData(ScriptName,'', + (ok,data)=>{ + if(ok){ + if(data.error_code=='0') + { + this.eRecNo(data,this.record_id); + }else + { + alert2(trt('Alert'),data.error_message); + } + }else{ + alert2(trt('Error'),data); + } + this.hideProgressBar(); + } + ); + this.showProgressBar(); }; //Задать CDATA значение для узла "type->properties->prop" по "n" @@ -140,17 +152,17 @@ class EdtRec //Записываю record_id в соответствующее XML поле this.setPropCdata(nodeType.getAttribute("ObjectID"),record_id); - let str=''; - str+=' '; - str+=' '; - str+=' '; - str+=' '; - str+=' '; - str+=' '; - str+=' '; - str+=' '; - str+=' '; - str+='
'+trt('Name')+''+trt('Value')+'
'; + let str=` + + + + + + + + + +
`+trt('Name')+``+trt('Value')+`
`; document.getElementById('eDiv'+this.uid).innerHTML=str; //this.win.setContent(str); @@ -236,14 +248,9 @@ class EdtRec } nP=nP.nextSibling; } - subSRec.f_Settings=nodeProp; - subSRec.f_State='0'; - if(subSRec.request.callServer(ScriptName,'')) - { - //obj.showProgressBar(); - } - + subSRec.callData(nodeProp.getAttribute("n"),nodeProp); + }else if (nodeProp.nodeName=="divide") //Grouping fields. { @@ -673,7 +680,7 @@ class EdtRec }else if(vt==="blob" || vt==="file") { - let ifr=createIFrame("prop_"+this.uid+"_"+nodeProp.getAttribute("n")+'_frm', ScriptUName+"?fn=9", td2, false); //IFrame to send the file to the server. + let ifr=createIFrame("prop_"+this.uid+"_"+nodeProp.getAttribute("n")+'_frm', ScriptUName, td2, false); //IFrame to send the file to the server. document.body.appendChild(ifr); let tbl_b=document.createElement('table'); @@ -865,10 +872,21 @@ class EdtRec this.fillGUIFromXML(); }else { - if(this.request.callServer(ScriptName,'',true)) - { - this.showProgressBar(); - } + postXMLData(ScriptName,'',(ok,data)=>{ + if(ok){ + if(data.error_code=='0') + { + this.setData(data); + }else + { + alert2(trt('Alert'),data.error_message); + } + }else{ + alert2(trt('Error'),data); + } + this.hideProgressBar(); + }); + this.showProgressBar(); } }; @@ -914,11 +932,26 @@ class EdtRec let option=document.getElementById("prop_"+this.uid+"_"+node.getAttribute("n")); setCdataValue(node,0,option.value); - strXMLF=''+strXMLF+''; - if(this.request.callServer(ScriptName,strXMLF,true)) - { - this.showProgressBar(); - } + postXMLData(ScriptName,''+strXMLF+'',(ok,data)=>{ + if(ok){ + if(data.error_code=='0') + { + this.setDataSelect(data); + }else + { + alert2(trt('Alert'),data.error_message); + } + }else{ + alert2(trt('Error'),data); + } + this.hideProgressBar(); + }); + this.showProgressBar(); + + //if(this.request.callServer(ScriptName,strXMLF,true)) + //{ + // this.showProgressBar(); + //} } } @@ -988,14 +1021,9 @@ class EdtRec rec.create(null); rec.f_State=1; rec.f_PropName=nodeProp.getAttribute("n"); - rec.f_Settings=settings; - rec.f_TypeName=TypeName; rec.win.setLeftTop(pageX-250,pageY-10); rec.win.setParent(this.win); - if(rec.request.callServer(ScriptName,'')) - { - rec.showProgressBar(); - } + rec.callData(TypeName,settings) }; //Запросить данные для выпадающих списков и других объектов (только после загрузки данных полей) @@ -1029,18 +1057,46 @@ class EdtRec } nColF = nColF.nextSibling; } - strXMLF=''+strXMLF+''; - if(this.request.callServer(ScriptName,strXMLF,true)) - { - this.showProgressBar(); - } + postXMLData(ScriptName,''+strXMLF+'',(ok,data)=>{ + if(ok){ + if(data.error_code=='0') + { + this.setDataSelect(data); + }else + { + alert2(trt('Alert'),data.error_message); + } + }else{ + alert2(trt('Error'),data); + } + this.hideProgressBar(); + }); + this.showProgressBar(); + //if(this.request.callServer(ScriptName,strXMLF,true)) + //{ + // this.showProgressBar(); + //} }else { - let xml=''; - if(this.request.callServer(ScriptName,xml,true)) - { - this.showProgressBar(); - } + postXMLData(ScriptName,'',(ok,data)=>{ + if(ok){ + if(data.error_code=='0') + { + this.setDataSelect(data); + }else + { + alert2(trt('Alert'),data.error_message); + } + }else{ + alert2(trt('Error'),data); + } + this.hideProgressBar(); + }); + this.showProgressBar(); + //if(this.request.callServer(ScriptName,xml,true)) + //{ + // this.showProgressBar(); + //} } }else { @@ -1199,39 +1255,6 @@ class EdtRec } }; - applyReq(req,fn,node,xmldoc,win) - { - this.hideProgressBar(); - - if(node.error_code>0) { - alert2(trt('Alert'), node.error_message); - return; - } - - if (fn==0) { - this.eRecNo(node,this.record_id); - } else - if (fn==1) { //returned id - this.insertRows(node); - } else - if (fn==2) { //Returned id and type of updated record - this.updateRows(node); - } else - if (fn==3) { //Returned id of deleted record - this.deleteRows(node); - } else - if (fn==5) { - this.setData(node); - } else - if (fn==6) { //Fill in the drop-down lists. - this.setDataSelect(node); - } else - if (fn==7) { - this.setData(node); - } else { - alert2(trt('Alert'),"Unknown function! fn=\""+fn+"\"" ); - } - }; /** * Request data to fill in the field with the button * @@ -1267,10 +1290,25 @@ class EdtRec ''; } - if(this.request.callServer(ScriptName,xml,true)) - { - this.showProgressBar(); - } + postXMLData(ScriptName,xml,(ok,data)=>{ + if(ok){ + if(data.error_code=='0') + { + this.setDataSelect(data); + }else + { + alert2(trt('Alert'),data.error_message); + } + }else{ + alert2(trt('Error'),data); + } + this.hideProgressBar(); + }); + this.showProgressBar(); + //if(this.request.callServer(ScriptName,xml,true)) + //{ + // this.showProgressBar(); + //} }else { alert2(trt('Alert'),'Field "'+prop_id+'" not find!'); @@ -1291,10 +1329,25 @@ class EdtRec let xml=''; xml+=''; xml+=''; - if(this.request.callServer(ScriptName,xml,true)) - { - this.showProgressBar(); - } + postXMLData(ScriptName,xml,(ok,data)=>{ + if(ok){ + if(data.error_code=='0') + { + this.setDataSelect(data); + }else + { + alert2(trt('Alert'),data.error_message); + } + }else{ + alert2(trt('Error'),data); + } + this.hideProgressBar(); + }); + this.showProgressBar(); + //if(this.request.callServer(ScriptName,xml,true)) + //{ + // this.showProgressBar(); + //} } }; @@ -1377,10 +1430,25 @@ class EdtRec let xml=''; xml+=''; xml+=''; - if(this.request.callServer(ScriptName,xml,true)) - { - this.showProgressBar(); - } + postXMLData(ScriptName,xml,(ok,data)=>{ + if(ok){ + if(data.error_code=='0') + { + this.setDataSelect(data); + }else + { + alert2(trt('Alert'),data.error_message); + } + }else{ + alert2(trt('Error'),data); + } + this.hideProgressBar(); + }); + this.showProgressBar(); + //if(this.request.callServer(ScriptName,xml,true)) + //{ + // this.showProgressBar(); + //} } } } @@ -1459,11 +1527,41 @@ class EdtRec s+=' \n'; s+='\n'; s+=''; - //alert2(trt('Alert'),s); - if(this.request.callServer(ScriptName,s,true)) - { + + if (this.record_id!=-1) { + postXMLData(ScriptName, s, (ok, data) => { + if (ok) { + if (data.error_code == '0') { + this.updateRows(data); + } else { + alert2(trt('Alert'), data.error_message); + } + } else { + alert2(trt('Error'), data); + } + this.hideProgressBar(); + }); + this.showProgressBar(); + }else{ + postXMLData(ScriptName, s, (ok, data) => { + if (ok) { + if (data.error_code == '0') { + this.insertRows(data); + } else { + alert2(trt('Alert'), data.error_message); + } + } else { + alert2(trt('Error'), data); + } + this.hideProgressBar(); + }); this.showProgressBar(); } + + //if(this.request.callServer(ScriptName,s,true)) + //{ + // this.showProgressBar(); + //} }; //Check the field according to its type checkData(value,type,maybenull) diff --git a/metadata/dbms/records.xyz b/metadata/dbms/records.xyz index 2c59a6e..0a406f4 100644 --- a/metadata/dbms/records.xyz +++ b/metadata/dbms/records.xyz @@ -223,7 +223,8 @@ } }*/ - $fn=filter_input(INPUT_GET, 'fn', FILTER_VALIDATE_INT, array('options'=>array('default'=>-1))); + if(!isset($fn)) + $fn=filter_input(INPUT_GET, 'fn', FILTER_VALIDATE_INT, array('options'=>array('default'=>-1))); $HTTP_INPUT=file_get_contents("php://input"); if($HTTP_INPUT) @@ -240,7 +241,7 @@ if ($reqNode) { - $fn = $reqNode->getAttribute("fn"); //Номер функции + $fn = $reqNode->getAttribute("fn"); //Номер функции из XML } } @@ -272,7 +273,7 @@ $allow_ins=false; $allow_upd=false; $allow_del=false; - $sql_query='select '.$Schema.'p_getaccess(:user_id1,:action_insert) as ins,'.$Schema.'p_getaccess(:user_id2,:action_update) as upd,'.$Schema.'p_getaccess(:user_id3,:action_delete) as del;'; + $sql_query='select '.$Schema.'get_access(:user_id1,:action_insert) as ins,'.$Schema.'get_access(:user_id2,:action_update) as upd,'.$Schema.'get_access(:user_id3,:action_delete) as del;'; $stmt = $db->prepare($sql_query); $stmt->bindValue(':user_id1', $_SESSION['USER_ID'], PDO::PARAM_INT); //getSQLValue(gettype($_SESSION['USER_ID']),$_SESSION['USER_ID']) $stmt->bindValue(':user_id2', $_SESSION['USER_ID'], PDO::PARAM_INT); //getSQLValue(gettype($_SESSION['USER_ID']),$_SESSION['USER_ID']) @@ -1343,7 +1344,7 @@ print ' '; print ' '; print ' '; - print ' '; + print ' '; print ' '; print '
'; print ' '; diff --git a/metadata/dbms/showrecord.js b/metadata/dbms/showrecord.js index 5aeb2f4..91781a7 100644 --- a/metadata/dbms/showrecord.js +++ b/metadata/dbms/showrecord.js @@ -31,7 +31,6 @@ class SRec this.masCL=new Array();//node table column this.masVis=new Array(); //Whether to display a column this.masChBox=new Array(); //Checkboxes - this.xmldoc=null; //accepted XML document (for CDATA creation) this.pagepos=0; //current data page this.pBarCnt=0; //Progress bar @@ -40,57 +39,12 @@ class SRec this.name=""; this.uid=getUID(); - this.request = new TRequest(this); SRec_mas[this.uid]=this; this.onUpdate=null; //For call set function this.onInsert=null; //For call set function } - applyReq(req,fn,node,xmldoc) - { - this.hideProgressBar(); - - if(node.error_code>0) { - alert2(trt('Alert'), node.error_message); - return; - } - - this.xmldoc=node.ownerDocument; //xmldoc; - - if (fn==0) - { - //alert2(trt('Alert'),getXMLNodeSerialisation(node)); - this.setMetadata(node); - this.updateSize(); - }else - if (fn==11) //Update record after editing, 1 entry has come. - { - this.updateRows(node); - }else - if (fn==3) //Information which record or records were deleted. - { - this.ApplyDelRec(node); - }else - if (fn==4) //Data after the selection of records, replacement of existing ones. - { - this.insertRows(node,true); - }else - if (fn==6) //Fill in the drop-down lists. - { - this.setDataSelect(node); - }else - if (fn==8) //There was a link to the report. - { - if(this.rwin!=null) - { - this.rwin.hideProgressBar(); - this.rwin.setContent('
'+trt('Download_report')+': "'+this.win.getCaption().innerHTML+'".
'); - } - }else - alert2(trt('Alert'),"Unknown function! fn=\""+fn+"\"" ); - } - //Edit the GUI filter from the xml string. setGUISettings(xmlStr) { @@ -166,7 +120,7 @@ class SRec `+trt('Refresh')+` -
+
@@ -430,11 +384,7 @@ class SRec '' + ''; } - - if(this.request.callServer(ScriptName,xml,true)) - { - this.showProgressBar(); - } + this.callDataSelect(xml); }else { alert2(trt('Alert'),'Filter "'+column_n+'" not find!'); @@ -512,12 +462,34 @@ class SRec xs+='\n'; xs+=''; - //alert2(trt('Alert'),xs); - - if(this.request.callServer(ScriptName,xs)) - { - this.showProgressBar(); + if(id!=-1) { + postXMLData(ScriptName, xs, (ok, data) => { + if (ok) { + if (data.error_code == '0') { + this.updateRows(data); + } else { + alert2(trt('Alert'), data.error_message); + } + } else { + alert2(trt('Error'), data); + } + this.hideProgressBar(); + }); + }else{ + postXMLData(ScriptName, xs, (ok, data) => { + if (ok) { + if (data.error_code == '0') { + this.insertRows(data, true); + } else { + alert2(trt('Alert'), data.error_message); + } + } else { + alert2(trt('Error'), data); + } + this.hideProgressBar(); + }); } + this.showProgressBar(); } //Get metadata records and break them into global variables. @@ -532,6 +504,7 @@ class SRec let tablefilter=document.getElementById('idfilter'+this.uid); if (tablefilter==null || tablefilter.tBodies==null) alert2(trt('Alert'),'tablefilter=null'); let nodeType=findFirstNode(node, "type"); + if (nodeType==null) alert2(trt('Alert'),'Not_find_data'); this.f_pI=nodeType.getAttribute("ins");//access rights this.f_pU=nodeType.getAttribute("upd"); this.f_pD=nodeType.getAttribute("del"); @@ -890,17 +863,10 @@ class SRec nColF = nColF.nextSibling; } strXMLF=''+strXMLF+''; - - if(this.request.callServer(ScriptName,strXMLF,true)) - { - this.showProgressBar(); - } + this.callDataSelect(strXMLF); }else { - if(this.request.callServer(ScriptName,'',true)) - { - this.showProgressBar(); - } + this.callDataSelect(''); } }else { @@ -945,10 +911,7 @@ class SRec if ((value!="")&&(value!=-1)) { let xmlString=''; - if(this.request.callServer(ScriptName,xmlString,true)) - { - this.showProgressBar(); - } + this.callDataSelect(xmlString); } } td2.appendChild( table ); @@ -1054,10 +1017,7 @@ class SRec } strXMLF=''+strXMLF+''; - if(this.request.callServer(ScriptName,strXMLF,true)) - { - this.showProgressBar(); - } + this.callDataSelect(strXMLF); } } } @@ -1066,6 +1026,26 @@ class SRec } } + callDataSelect(data) { + postXMLData(ScriptName,data, + (ok,data)=>{ + if(ok){ + if(data.error_code=='0') + { + this.setDataSelect(data); + }else + { + alert2(trt('Alert'),data.error_message); + } + }else{ + alert2(trt('Error'),data); + } + this.hideProgressBar(); + } + ); + this.showProgressBar(); + } + //We ask the server for a list of values almost like a drop-down list. //typeName - The name of the object (TODO if the current is the variable f TypeName) //name - the name of the column for selecting the values (must match the name of any filter in typeName) @@ -1079,10 +1059,7 @@ class SRec let xml=''; xml+=''; xml+=''; - if(this.request.callServer(ScriptName,xml,true)) - { - this.showProgressBar(); - } + this.callDataSelect(xml); }else { document.getElementById("filter_"+this.uid+"_"+htmlid).value=''; @@ -1401,14 +1378,9 @@ class SRec rec.create(null); rec.f_State=1; //Зачем коментил? rec.f_PropName=nodeColu.getAttribute("n"); //Зачем коментил? - rec.f_Settings=settings; - rec.f_TypeName=TypeName; rec.win.setLeftTop(pageX-250,pageY-10); rec.win.setParent(this.win); - if(rec.request.callServer(ScriptName,'')) - { - rec.showProgressBar(); - } + rec.callData(TypeName,settings); }; //Call the ShowRecord window with the parameters for the filter (not just the object name) //id - id records from the database @@ -1432,16 +1404,9 @@ class SRec //wishWin = window.open("showrecord.html?name="+typeName,typeName,"width=800,height=600,menubar=no,location=no,resizable=yes,scrollbars=yes"); let rec=new SRec(); rec.create(null); - //rec.f_State=1; not used - //rec.f_PropName=propname; not used - rec.f_Settings=xmlString; - rec.f_TypeName=typeName; rec.win.setLeftTop(pageX-250,pageY-10); rec.win.setParent(this.win); - if(rec.request.callServer(ScriptName,'')) - { - rec.showProgressBar(); - } + rec.callData(typeName,xmlString); } //Get column number by name @@ -1566,10 +1531,28 @@ class SRec xs+=' \n'; xs+=' \n'; xs+=''; - if(this.request.callServer(ScriptName,xs)) - { - this.rwin.showProgressBar(); - } + + postXMLData(ScriptName,xs, + (ok,data)=>{ + if(ok){ + if(data.error_code=='0') + { + if(this.rwin!=null) + { + this.rwin.hideProgressBar(); + this.rwin.setContent('
'+trt('Download_report')+': "'+this.win.getCaption().innerHTML+'".
'); + } + }else + { + alert2(trt('Alert'),data.error_message); + } + }else{ + alert2(trt('Error'),data); + } + this.hideProgressBar(); + } + ); + this.showProgressBar(); } chp(page) @@ -1639,10 +1622,23 @@ class SRec { if(this.masChBox[i].checked) { - if(this.request.callServer(ScriptName,'',true)) - { - this.showProgressBar(); - } + postXMLData(ScriptName,'', + (ok,data)=>{ + if(ok){ + if(data.error_code=='0') + { + this.ApplyDelRec(data); + }else + { + alert2(trt('Alert'),data.error_message); + } + }else{ + alert2(trt('Error'),data); + } + this.hideProgressBar(); + } + ); + this.showProgressBar(); } } } @@ -1672,13 +1668,23 @@ class SRec { this.f_TypeName=typeName; this.f_Settings=settings; - - if(this.request.callServer(ScriptName,'')) - { - this.showProgressBar(); - } + postXMLData(ScriptName,'',(ok,data)=>{ + if(ok){ + if(data.error_code=='0') + { + this.setMetadata(data); + this.updateSize(); + }else + { + alert2(trt('Alert'),data.error_message); + } + }else{ + alert2(trt('Error'),data); + } + this.hideProgressBar(); + }); + this.showProgressBar(); } - } //Convert XML to array diff --git a/metadata/dbms/tools.js b/metadata/dbms/tools.js index 8ccf84b..f32cb2e 100644 --- a/metadata/dbms/tools.js +++ b/metadata/dbms/tools.js @@ -1,7 +1,22 @@ /*jshint esversion: 6 */ "use strict"; -//var g_translations = {'':''}; +function strToInt(str){ + if(str==null) return null; + const match = str.trim().match(/[-+]?\d+(\.\d+)?/); + if (match) { + const number = Number(match[0]); + return isNaN(number) ? null : number; + } + return null; +} + +function removeChild(parent){ + if(parent==null) return; + while (parent.firstChild) { + parent.removeChild(parent.firstChild); + } +} //Массив g_translations подгружается отдельно function trt(key) @@ -237,7 +252,7 @@ function loadContent(url,obj) req.send( null ); } -//POST Json Data to server and Json in result +//POST Json Data to server function postJsonData(url,data,fun){ if(typeof data !== 'string') { data = JSON.stringify(data); @@ -248,15 +263,21 @@ function postJsonData(url,data,fun){ return function(){ if(req.readyState == 4 || typeof(req.readyState)=='undefined'){ if(req.status == 200) { - let json = null; - try { - json = JSON.parse(req.responseText); - } catch (e) { + if(req.responseXML!=null) { + let node = req.responseXML.documentElement; + node.error_code='0'; + fun(true, node); + }else { + let json = null; + try { + json = JSON.parse(req.responseText); + } catch (e) { + } + if (json != null) + fun(true, json); + else + fun(false, req.responseText); } - if (json != null) - fun(true, json); - else - fun(false, req.responseText); }else{ fun(false,trt('Failed_to_receive_data')); } @@ -267,6 +288,45 @@ function postJsonData(url,data,fun){ req.setRequestHeader("Content-type", "application/json"); req.send(data); } +//POST Json Data to server +function postXMLData(url,data,fun){ + if(typeof data !== 'string') { + let serializer = new XMLSerializer(); + data = serializer.serializeToString(data); + } + let req=createRequestObject(); + req.onreadystatechange = function(req) + { + return function(){ + if(req.readyState == 4 || typeof(req.readyState)=='undefined'){ + if(req.status == 200) { + if(req.responseXML!=null) { + let node = req.responseXML.documentElement; + node.error_code='0'; + fun(true, node); + }else { + let json = null; + try { + json = JSON.parse(req.responseText); + } catch (e) { + } + if (json != null) + fun(true, json); + else + fun(false, req.responseText); + } + }else{ + fun(false,trt('Failed_to_receive_data')); + } + } + }; + }(req); + req.open( "POST", url, true ); + req.setRequestHeader("Content-type", "application/xml"); + req.send(data); + + +} //Вывести текст поверх окон с кнопочкой OK function alert2(title,smallText,fullText,okFunc=null) @@ -278,7 +338,10 @@ function alert2(title,smallText,fullText,okFunc=null) } let pos1=smallText.indexOf('[['); let pos2=smallText.indexOf(']]'); - if(pos1>=0 && pos2>=0 && pos1=0 && pos2>=0 && pos1'; + this.pBarDiv.innerHTML='
'; + //var eDiv=document.getElementById('eDiv'+this.uid); this.div.appendChild(this.pBarDiv); diff --git a/metadata/include/tools.xyz b/metadata/include/tools.xyz index fe5a33c..4c7d084 100644 --- a/metadata/include/tools.xyz +++ b/metadata/include/tools.xyz @@ -107,7 +107,7 @@ function getAccess($key) global $db; $result=false; - $sql="select main.p_getaccess(:user_id,:key) as acc;"; + $sql="select main.get_access(:user_id,:key) as acc;"; $stmt = $db->prepare($sql); if(isset($_SESSION['USER_ID'])) $stmt->bindValue(':user_id', $_SESSION['USER_ID'], PDO::PARAM_INT); @@ -517,3 +517,11 @@ function cutBeforeFirst(&$sstr,$fstr) return $sub; } } + +function getUID() +{ + $data = openssl_random_pseudo_bytes(16); + $data[6] = chr(ord($data[6]) & 0x0f | 0x40); + $data[8] = chr(ord($data[8]) & 0x3f | 0x80); + return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4)); +} \ No newline at end of file