From 70974247d7567d306e28a57f0e3286c6ab24071a Mon Sep 17 00:00:00 2001 From: igor Date: Mon, 13 Jan 2025 02:35:54 +0500 Subject: [PATCH] =?UTF-8?q?=D0=92=D1=8B=D0=B1=D0=BE=D1=80=D0=BA=D1=83=20?= =?UTF-8?q?=D0=BC=D0=B5=D1=82=D0=B0=D0=B4=D0=B0=D0=BD=D0=BD=D1=8B=D1=85=20?= =?UTF-8?q?=D0=B2=D1=8B=D0=BD=D0=B5=D1=81=20=D0=B2=20=D0=BE=D1=82=D0=B4?= =?UTF-8?q?=D0=B5=D0=BB=D1=8C=D0=BD=D1=83=D1=8E=20=D1=84=D1=83=D0=BD=D0=BA?= =?UTF-8?q?=D1=86=D0=B8=D1=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- org_ccalm_dbms.yml | 25 +- src/main/java/dbms/DBMSRecords.java | 566 +++++++++++++------- src/main/java/models/MetadataNameModel.java | 15 + src/main/resources/logback-spring.xml | 3 +- 4 files changed, 415 insertions(+), 194 deletions(-) create mode 100644 src/main/java/models/MetadataNameModel.java diff --git a/org_ccalm_dbms.yml b/org_ccalm_dbms.yml index 0028f83..ea83e88 100644 --- a/org_ccalm_dbms.yml +++ b/org_ccalm_dbms.yml @@ -11,20 +11,21 @@ issuer: spring: application: - name: dbms + name: org_ccalm_dbms datasource: - url: jdbc:postgresql://91.201.214.156:5432/CCALM + url: jdbc:postgresql://91.201.214.156:5432/CCALM?ApplicationName=org_ccalm_dbms&ssl=true&sslmode=require&connectTimeout=10000&socketTimeout=10000 username: postgres - password: PasSecrKey1 + password: 309A86FF65A78FB428F4E38DFE35F730 driver-class-name: org.postgresql.Driver hikari: maximum-pool-size: 10 minimum-idle: 5 - max-lifetime: 1700000 - idle-timeout: 600000 + max-lifetime: 600000 + idle-timeout: 300000 connection-timeout: 30000 - connection-test-query: SELECT now() - validation-timeout: 60000 + connection-test-query: SELECT 1 + validation-timeout: 5000 + validation-interval: 60000 redis: host: 127.0.0.1 port: 6379 @@ -51,8 +52,8 @@ url: reset: http://127.0.0.1:8088/reset main: http://127.0.0.1:8088/ -logging: - level: - com: - zaxxer: - hikari: DEBUG +#logging: +# level: +# com: +# zaxxer: +# hikari: DEBUG diff --git a/src/main/java/dbms/DBMSRecords.java b/src/main/java/dbms/DBMSRecords.java index 7b890ca..17b36b2 100644 --- a/src/main/java/dbms/DBMSRecords.java +++ b/src/main/java/dbms/DBMSRecords.java @@ -19,14 +19,11 @@ 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; -import java.sql.SQLException; -import java.sql.Statement; +import java.sql.*; import java.text.SimpleDateFormat; import java.util.*; //import java.util.Iterator; +import java.util.Date; import java.util.zip.CRC32; import java.util.zip.Checksum; @@ -55,6 +52,7 @@ import javax.xml.xpath.XPathFactory; //import org.apache.commons.fileupload.FileItem; //import org.apache.commons.fileupload.disk.DiskFileItemFactory; //import org.apache.commons.fileupload.servlet.ServletFileUpload; +import models.MetadataNameModel; import org.apache.commons.io.FileUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.MarkerManager; @@ -68,6 +66,7 @@ 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.dao.DataAccessException; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; @@ -142,11 +141,137 @@ public class DBMSRecords implements ServletContextAware { return null; } + //Вместо fn="0" + @RequestMapping(value = "/metadata",method = {RequestMethod.POST,RequestMethod.GET}) //,produces = "text/plain; charset=utf-8" + @ResponseBody + public ResponseEntity getMetadata( + @RequestBody(required = false) byte[] reqData, + @CookieValue(value = "jwt_a", defaultValue = "") String jwt_a, + @CookieValue(value = "lng", defaultValue = "1") String language_id + ) { + final HttpHeaders httpHeaders= new HttpHeaders(); + httpHeaders.setContentType(MediaType.APPLICATION_JSON); + String result=sendError(10000,"Request_not_processed",null); + + if (jwt_a.equals("") || Tools.countOccurrences(jwt_a, '.') != 2) { + result = sendError(10000, "You_are_not_logged_in",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 user = new User(); + user.id = claims.getBody().get("user_id").toString(); + user.language_id = language_id; + + result=sendError(10000,"Request not processed!",null); + if(reqData==null) + return new ResponseEntity(result, httpHeaders, HttpStatus.OK); + InputStream body = new ByteArrayInputStream(reqData); + + Document doc = null; + Element reqNode = null; + try { + DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); + doc = dBuilder.parse(body); + } catch (Exception ex) { + logger.info(ex.getMessage()); + return new ResponseEntity(sendError(10000,"Parsing request error!",null), httpHeaders, HttpStatus.OK); + } + + if (doc != null) { + reqNode = doc.getDocumentElement(); + //fn = reqNode.getAttribute("fn"); //Номер функции + } + + //Get XML node from database and parse to DOM + javax.xml.xpath.XPathFactory xPathfactory = javax.xml.xpath.XPathFactory.newInstance(); + XPath xpath = xPathfactory.newXPath(); + XPathExpression expr=null; + + String name = ""; + //if (fn != null && fn.equals("0")) //Send metadata to client + if (doc != null) { + xPathfactory = XPathFactory.newInstance(); + xpath = xPathfactory.newXPath(); + try { + expr = xpath.compile("//metadata/type/@n"); + name = "" + expr.evaluate(doc, XPathConstants.STRING); + } catch (XPathExpressionException ex) { + logger.info(ex.getMessage()); + } + } + + String xml = ""; + + //Get XML node from database and parse to DOM + doc = parseString(getTypeStrNode2(name)); + + if (doc != null) { + doc.getDocumentElement().normalize(); //Del or concat text node + + xml += ""; + + //Delete all child "sql-query" nodes. + XPathExpression exp=null; + NodeList nl=null; + try { + exp = xpath.compile("//sql-query"); + nl = (NodeList) exp.evaluate(doc, XPathConstants.NODESET); + } catch (XPathExpressionException ex) { + logger.info(ex.getMessage()); + } + + for (int j = 0; j < nl.getLength(); j++) { + nl.item(j).getParentNode().removeChild(nl.item(j)); + } + // XML Node Serialisation + DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation(); + LSSerializer lsSerializer = domImplementation.createLSSerializer(); + lsSerializer.getDomConfig().setParameter("xml-declaration", false); + + //Set attributes to define access level (insert,update,selete,select). + String allow; + + allow = getAccess(user.id,"Select_" + name); + doc.getDocumentElement().setAttribute("sel", allow); + + allow = getAccess(user.id,"Insert_" + name); + doc.getDocumentElement().setAttribute("ins", allow); + + allow = getAccess(user.id,"Update_" + name); + doc.getDocumentElement().setAttribute("upd", allow); + + allow = getAccess(user.id,"Delete_" + name); + doc.getDocumentElement().setAttribute("del", allow); + + xml += lsSerializer.writeToString(doc.getDocumentElement()); + xml += ""; + } else { + xml += ""; + } + + result=trts2(xml,user); + httpHeaders.setContentType(MediaType.APPLICATION_XML); + + return new ResponseEntity(result, httpHeaders, HttpStatus.OK); + } + //Документация по @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( + @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, @@ -154,7 +279,6 @@ public class DBMSRecords implements ServletContextAware { ) { 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")) { // @@ -177,12 +301,12 @@ public class DBMSRecords implements ServletContextAware { } - 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); + 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; - result=sendError(10000,"Request not processed!",null); + boolean error=false; + result=sendError(10000,"Request not processed!",null); if(reqData==null) return new ResponseEntity(result, httpHeaders, HttpStatus.OK); @@ -216,7 +340,7 @@ public class DBMSRecords implements ServletContextAware { String fn = "";//request.getParameter("fn"); String name = "";//request.getParameter("n"); //type name - + InputStream body = new ByteArrayInputStream(reqData); //logger.info("Send \"Records\" for user = ."+user.name); @@ -252,13 +376,13 @@ public class DBMSRecords implements ServletContextAware { Marker marker = MarkerManager.getMarker(uuid); logger.info(marker,"Connect is OK!"); } else { - error=true; - result=sendError(10000,"An error occurred while connecting to the database!",null); + error=true; + result=sendError(10000,"An error occurred while connecting to the database!",null); } } catch (Exception ex) { logger.info(ex.getMessage()); - error=true; - result=sendError(10000,"An error occurred while connecting to the database!",null); + error=true; + result=sendError(10000,"An error occurred while connecting to the database!",null); } try { @@ -325,7 +449,7 @@ public class DBMSRecords implements ServletContextAware { } catch (XPathExpressionException ex) { logger.info(ex.getMessage()); } - + for (int j = 0; j < nl.getLength(); j++) { nl.item(j).getParentNode().removeChild(nl.item(j)); } @@ -409,7 +533,7 @@ public class DBMSRecords implements ServletContextAware { rs.close(); } catch (SQLException ex) { logger.info(ex.getMessage()); - } + } } } catch (SQLException ex) { logger.info(ex.getMessage()); @@ -499,7 +623,7 @@ public class DBMSRecords implements ServletContextAware { sql_query = (String) expr.evaluate(nTypeS, XPathConstants.STRING); } catch (XPathExpressionException ex) { logger.info(ex.getMessage()); - } + } logger.info("sql_query11 = " + sql_query); @@ -519,21 +643,21 @@ public class DBMSRecords implements ServletContextAware { if (nodeList!=null && nodeList.getLength() > 0) { vt = nodeList.item(0).getAttributes().getNamedItem("vt").getNodeValue(); //If this "file" is then copy it from the temporary folder to the specified path - if(vt.equals("file")) + if(vt.equals("file")) { String srcPath = data_dir;//context.getInitParameter("file-upload"); String destPath = nodeList.item(0).getAttributes().getNamedItem("path").getNodeValue(); - File srcFile = new File(srcPath+val); //Upload folder - if(srcFile.isFile()) - { - File destFile = new File(destPath+val); //Foldef from metadata.xml - try { + File srcFile = new File(srcPath+val); //Upload folder + if(srcFile.isFile()) + { + File destFile = new File(destPath+val); //Foldef from metadata.xml + try { FileUtils.copyFile(srcFile, destFile); - FileUtils.forceDelete(srcFile); + FileUtils.forceDelete(srcFile); } catch (IOException ex) { logger.info(ex.getMessage()); } - } + } } } @@ -571,7 +695,7 @@ public class DBMSRecords implements ServletContextAware { } } - } else if (fn != null && fn.equals("2")) //Update record by ID from XML data + } else if (fn != null && fn.equals("2")) //Update record by ID from XML data { String typename = ""; String obj_id = ""; @@ -633,22 +757,22 @@ public class DBMSRecords implements ServletContextAware { if (nodeList!=null && nodeList.getLength() > 0) { vt = nodeList.item(0).getAttributes().getNamedItem("vt").getNodeValue(); //If this "file" is then copy it from the temporary folder to the specified path - if(vt.equals("file")) + if(vt.equals("file")) { String srcPath = data_dir;//context.getInitParameter("file-upload"); String destPath = nodeList.item(0).getAttributes().getNamedItem("path").getNodeValue(); - File srcFile = new File(srcPath+val); //Upload folder - if(srcFile.isFile()) - { - File destFile = new File(destPath+val); //Foldef from metadata.xml - try { + File srcFile = new File(srcPath+val); //Upload folder + if(srcFile.isFile()) + { + File destFile = new File(destPath+val); //Foldef from metadata.xml + try { FileUtils.copyFile(srcFile, destFile); - FileUtils.forceDelete(srcFile); + FileUtils.forceDelete(srcFile); } catch (IOException ex) { logger.info(ex.getMessage()); } - } + } } } sql_query=Tools.replaceAll(sql_query,"${" + vn + "}", DBTools.getSQLValue(vt, val)); @@ -729,7 +853,7 @@ public class DBMSRecords implements ServletContextAware { { String vn=node_properties.item(i).getAttributes().getNamedItem("n").getNodeValue(); String val=node_properties.item(i).getTextContent(); - + //Так как тип узла не передётся в запросе выбираем его отдельно String vt=""; expr = xpath.compile("properties/prop[@n='"+vn+"']"); @@ -739,7 +863,7 @@ public class DBMSRecords implements ServletContextAware { { vt=nodeList.item(0).getAttributes().getNamedItem("vt").getNodeValue(); } - + sql_query=Tools.replaceAll(sql_query,"${"+vn+"}",DBTools.getSQLValue(vt,val)); } */ @@ -814,7 +938,7 @@ public class DBMSRecords implements ServletContextAware { f1 = nodeList.item(0); nodeList = (NodeList) xpath.compile("objects-list/filter").evaluate(nTypeR, XPathConstants.NODESET); if (nodeList.getLength() > 0) - f2 = nodeList.item(0); + f2 = nodeList.item(0); } catch (XPathExpressionException ex) { logger.info(ex.getMessage()); } @@ -979,8 +1103,8 @@ public class DBMSRecords implements ServletContextAware { JSONObject data = new JSONObject(); datas.put(data); - - + + String access = ""; //u = enable update field, d = enable delete field try { if (rs.getBoolean("_u") == true) @@ -1003,7 +1127,7 @@ public class DBMSRecords implements ServletContextAware { data.put("id", id); data.put("a", access); - + JSONArray row = new JSONArray(); data.put("row",row); for (int i = 0; i < columns.size(); i++) { @@ -1024,7 +1148,7 @@ public class DBMSRecords implements ServletContextAware { stmt.close(); rs=null; stmt=null; - + } catch (SQLException ex) { String uuid = UUID.randomUUID().toString(); Marker marker = MarkerManager.getMarker(uuid); @@ -1083,7 +1207,7 @@ public class DBMSRecords implements ServletContextAware { //st = conn.createStatement(); - + try { Statement stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = stt.executeQuery(sql_query); @@ -1305,8 +1429,8 @@ public class DBMSRecords implements ServletContextAware { email = (String) xpath.compile("//metadata/email/text()").evaluate(reqNode, XPathConstants.STRING); } catch (XPathExpressionException ex) { logger.info(ex.getMessage()); - } - + } + String xmlstring = ""; if (cmd.equals("0")) //Restore password by email { @@ -1322,8 +1446,8 @@ public class DBMSRecords implements ServletContextAware { find = true; rs.close(); } catch (SQLException ex) { - logger.info(ex.getMessage()); - } + logger.info(ex.getMessage()); + } } rs.close(); stt.close(); @@ -1382,7 +1506,7 @@ public class DBMSRecords implements ServletContextAware { } else if (cmd.equals("1")) //Logout { String sql_query="select main.p__logout("+user.id+");"; - + //Отмечаем в базе что пользователь вышел (для электронной очереди если пользователь обрабатывается) try { Statement stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); @@ -1471,8 +1595,8 @@ public class DBMSRecords implements ServletContextAware { String expiration = rs.getString("expiration"); //Дата до которой действует пароль String renewal = rs.getString("renewal"); //На сколько дней продлевать действие пароля - xmlstring = ""; }else @@ -1499,11 +1623,11 @@ public class DBMSRecords implements ServletContextAware { xmlstring = ""; //if error String sql_query = ""; String val; - + //Check exists user by email email - sql_query = "select id from main._users where email=LOWER(TRIM(${email}))"; + sql_query = "select id from main._users where email=LOWER(TRIM(${email}))"; val = DBTools.getSQLValue("string", email); - sql_query = Tools.replaceAll(sql_query,"${email}", val); + sql_query = Tools.replaceAll(sql_query,"${email}", val); try { Statement stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = stt.executeQuery(sql_query); @@ -1517,83 +1641,83 @@ public class DBMSRecords implements ServletContextAware { } catch (SQLException ex) { logger.info(ex.getMessage()); } - } + } rs.close(); - stt.close(); + stt.close(); } catch (SQLException ex) { logger.info(ex.getMessage()); //xmlstring = ""; xmlstring=sendError(10000,"Error: " + ex.getMessage(),null); error=true; - } - + } + if(!error) { - String newPass = getRandomString(8); + String newPass = getRandomString(8); sql_query = "select * from main.p__Users_1(4,${country_id},${surname},${name},${company},${position},${phone},${email},${password});"; - - val = DBTools.getSQLValue("i4", country_id); - sql_query = Tools.replaceAll(sql_query,"${country_id}", val); - val = DBTools.getSQLValue("string", lastname); - sql_query = Tools.replaceAll(sql_query,"${surname}", val); - val = DBTools.getSQLValue("string", firstname); - sql_query = Tools.replaceAll(sql_query,"${name}", val); - val = DBTools.getSQLValue("string", company); - sql_query = Tools.replaceAll(sql_query,"${company}", val); - val = DBTools.getSQLValue("string", position); - sql_query = Tools.replaceAll(sql_query,"${position}", val); - val = DBTools.getSQLValue("string", phone); - sql_query = Tools.replaceAll(sql_query,"${phone}", val); - val = DBTools.getSQLValue("string", email); - sql_query = Tools.replaceAll(sql_query,"${email}", val); - val = DBTools.getSQLValue("string", newPass); - sql_query = Tools.replaceAll(sql_query,"${password}", val); - - //logger.info("sql_query = " + sql_query); - - - try { - Statement stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); - ResultSet rs = stt.executeQuery(sql_query); - if (rs != null) { - try { - if (rs.next()) { - xmlstring = ""; - - //Отправляем пароль на Email - String recipient = email; - String subject = "Password for new user on http://www.ccalm.org"; - String content = "Login is: "+ email.toLowerCase()+"\n
Password: " + newPass+""; - content += "

Sincerely, the administration of ccalm.org."; - - //String answer = ""; - try { - EmailUtility.sendEmail(mail_host, mail_port, mail_login, mail_password, recipient, subject, content); - //answer = "New password was sent successfully on \"" + recipient + "\".\nIf there is no email then check the spam folder."; - } catch (Exception ex) { - logger.info(ex.getMessage()); - //answer = "There were an error: " + ex.getMessage(); - } finally { - //request.setAttribute("Message", resultMessage); - //context.getRequestDispatcher("/Result.jsp").forward(request, response); + + val = DBTools.getSQLValue("i4", country_id); + sql_query = Tools.replaceAll(sql_query,"${country_id}", val); + val = DBTools.getSQLValue("string", lastname); + sql_query = Tools.replaceAll(sql_query,"${surname}", val); + val = DBTools.getSQLValue("string", firstname); + sql_query = Tools.replaceAll(sql_query,"${name}", val); + val = DBTools.getSQLValue("string", company); + sql_query = Tools.replaceAll(sql_query,"${company}", val); + val = DBTools.getSQLValue("string", position); + sql_query = Tools.replaceAll(sql_query,"${position}", val); + val = DBTools.getSQLValue("string", phone); + sql_query = Tools.replaceAll(sql_query,"${phone}", val); + val = DBTools.getSQLValue("string", email); + sql_query = Tools.replaceAll(sql_query,"${email}", val); + val = DBTools.getSQLValue("string", newPass); + sql_query = Tools.replaceAll(sql_query,"${password}", val); + + //logger.info("sql_query = " + sql_query); + + + try { + Statement stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); + ResultSet rs = stt.executeQuery(sql_query); + if (rs != null) { + try { + if (rs.next()) { + xmlstring = ""; + + //Отправляем пароль на Email + String recipient = email; + String subject = "Password for new user on http://www.ccalm.org"; + String content = "Login is: "+ email.toLowerCase()+"\n
Password: " + newPass+""; + content += "

Sincerely, the administration of ccalm.org."; + + //String answer = ""; + try { + EmailUtility.sendEmail(mail_host, mail_port, mail_login, mail_password, recipient, subject, content); + //answer = "New password was sent successfully on \"" + recipient + "\".\nIf there is no email then check the spam folder."; + } catch (Exception ex) { + logger.info(ex.getMessage()); + //answer = "There were an error: " + ex.getMessage(); + } finally { + //request.setAttribute("Message", resultMessage); + //context.getRequestDispatcher("/Result.jsp").forward(request, response); + } + } - + } catch (SQLException ex) { + logger.info(ex.getMessage()); } - } catch (SQLException ex) { - logger.info(ex.getMessage()); } - } - rs.close(); - stt.close(); - rs=null; - stt=null; - } catch (SQLException ex) { - logger.info(ex.getMessage()); + rs.close(); + stt.close(); + rs=null; + stt=null; + } catch (SQLException ex) { + logger.info(ex.getMessage()); //xmlstring = ""; xmlstring=sendError(10000,"Error: " + ex.getMessage(),null); - error=true; + error=true; + } } } - } result=xmlstring; httpHeaders.setContentType(MediaType.APPLICATION_XML); @@ -1628,7 +1752,7 @@ public class DBMSRecords implements ServletContextAware { //String pagepos=""; Node nTypeR = null; - if (doc != null) { + if (doc != null) { Object exprResult=null; try { expr = xpath.compile("//metadata/type"); @@ -1678,7 +1802,7 @@ public class DBMSRecords implements ServletContextAware { //Filter options for display in the header Excel(XLS) document. /* String filter=""+trt("Filter_options",user)+":
"; - expr = xpath.compile("objects-list/filter/column"); + expr = xpath.compile("objects-list/filter/column"); exprResult = expr.evaluate(nTypeR, XPathConstants.NODESET); nodeList = (NodeList) exprResult; for(int i=0;i\n"); writer.write(" " + trts(conn,"" + expr.evaluate(nTypeS, XPathConstants.STRING),user) + "\n"); writer.write(" \n"); writer.write(" "); - + expr = xpath.compile("objects-list/column"); Object exprResult = expr.evaluate(nTypeS, XPathConstants.NODESET); nodeList = (NodeList) exprResult; @@ -1781,7 +1905,7 @@ public class DBMSRecords implements ServletContextAware { writer.write(" \n"); writer.write(" \n"); writer.write(" \n"); - + while (rs.next()) { writer.write(" "); for (int i = 0; i < nodeList.getLength(); i++) { @@ -1876,7 +2000,7 @@ public class DBMSRecords implements ServletContextAware { } crc32 = sum_control.getValue(); fin.close(); - + //To be rename file, add CRC32 in begin. File srcFile = new File(filePath + fileName); File destFile = new File(filePath + Long.toHexString(crc32) +"_"+ fileName); @@ -1923,8 +2047,8 @@ public class DBMSRecords implements ServletContextAware { try { if(conn!=null) conn.close(); } catch (SQLException e) { throw new RuntimeException(e); } //return body content return new ResponseEntity(result, httpHeaders, HttpStatus.OK); - } - + } + /** * Example request: http://localhost:8080/CCALM/download?t=FrmLocust&f=image_name1&i=1298 */ @@ -1942,11 +2066,11 @@ public class DBMSRecords implements ServletContextAware { db_login = env.getProperty("spring.datasource.username"); db_password = env.getProperty("spring.datasource.password"); } catch (Exception e) { - e.printStackTrace(); + e.printStackTrace(); logger.error("Error load application.properties",e); } - + Connection conn = null; try { Class.forName("org.postgresql.Driver"); @@ -1994,7 +2118,7 @@ public class DBMSRecords implements ServletContextAware { javax.xml.xpath.XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr=null; - + Object exprResult=null; try { expr = xpath.compile("//metadata/type[@n='" + typename + "']"); @@ -2013,7 +2137,7 @@ public class DBMSRecords implements ServletContextAware { path = (String) expr.evaluate(nTypeS, XPathConstants.STRING); } catch (XPathExpressionException ex) { logger.info(ex.getMessage()); - } + } } if(path!=null && !path.equals("")) @@ -2043,12 +2167,12 @@ public class DBMSRecords implements ServletContextAware { try { if(conn!=null) conn.close(); } catch (SQLException e) { throw new RuntimeException(e); } if(file!=null) { - response.setContentType("application/octet-stream"); - response.setHeader("Content-Disposition", "attachment; filename="+afterFirst(filename,"_")); - response.setHeader("Cache-Control", "no-cache"); + response.setContentType("application/octet-stream"); + response.setHeader("Content-Disposition", "attachment; filename="+afterFirst(filename,"_")); + response.setHeader("Cache-Control", "no-cache"); return new FileSystemResource(file); }else { - response.setContentType("text/html"); + response.setContentType("text/html"); return null; } } @@ -2056,7 +2180,7 @@ 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) { - + String result=""; String data_dir = ""; @@ -2067,45 +2191,45 @@ public class DBMSRecords implements ServletContextAware { logger.error("Error load application.properties",e); } - + String fileName = ""; - + if (file!=null && !file.isEmpty()) { try { - + byte[] bytes = file.getBytes(); fileName = file.getOriginalFilename(); - + File dir = new File(data_dir); if (!dir.exists()) dir.mkdirs(); BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(data_dir + fileName))); stream.write(bytes); stream.flush(); - stream.close(); + stream.close(); //Calc CRC32 long crc32=0; FileInputStream fin = new FileInputStream(data_dir + fileName); - Checksum sum_control = new CRC32(); - for (int b = fin.read(); b != -1; b = fin.read()) { + Checksum sum_control = new CRC32(); + for (int b = fin.read(); b != -1; b = fin.read()) { sum_control.update(b); - } - crc32 = sum_control.getValue(); - fin.close(); - + } + crc32 = sum_control.getValue(); + fin.close(); + //To be rename file, add CRC32 in begin. File srcFile = new File(data_dir + fileName); - File destFile = new File(data_dir + Long.toHexString(crc32) +"_"+ fileName); + File destFile = new File(data_dir + Long.toHexString(crc32) +"_"+ fileName); FileUtils.copyFile(srcFile, destFile); FileUtils.forceDelete(srcFile); //logger.info("Uploaded Filename: " + Long.toHexString(crc32) +"_"+ fileName); result+="ok=" + Long.toHexString(crc32) +"_"+ fileName + "\n"; - } catch (Exception ex) { - logger.info(ex.getMessage()); - } + } catch (Exception ex) { + logger.info(ex.getMessage()); + } } //This code put into iframe @@ -2132,9 +2256,9 @@ public class DBMSRecords implements ServletContextAware { } //Send generated report to the client for downloading - @RequestMapping(value = "/reports",method = RequestMethod.GET, produces = "application/octet-stream") - @ResponseBody - public FileSystemResource sendReport(HttpServletResponse response,@RequestParam(required=true,name="file") String fileName) { + @RequestMapping(value = "/reports",method = RequestMethod.GET, produces = "application/octet-stream") + @ResponseBody + public FileSystemResource sendReport(HttpServletResponse response,@RequestParam(required=true,name="file") String fileName) { String data_dir = ""; try { @@ -2144,21 +2268,21 @@ public class DBMSRecords implements ServletContextAware { logger.error("Error load application.properties",e); } - File file = new File(data_dir + "temp" + File.separator + fileName); - if(file.exists()) - { - //logger.info("Send report: " + fileName); + File file = new File(data_dir + "temp" + File.separator + fileName); + if(file.exists()) + { + //logger.info("Send report: " + fileName); //response.setContentType("application/octet-stream"); //Commented because it is specified in the function declaration. response.setHeader("Content-Disposition","attachment; filename="+fileName); response.setContentLength((int) file.length()); - return new FileSystemResource(file); - }else - { - logger.info("File not found: " + fileName); - return null; - } - } + return new FileSystemResource(file); + }else + { + logger.info("File not found: " + fileName); + return null; + } + } private String nodeToString(Node node) { StringWriter sw = new StringWriter(); @@ -2193,7 +2317,7 @@ public class DBMSRecords implements ServletContextAware { setCharacterDataToElement((Element) nc1, getCharacterDataFromElement((Element) nc2)); - //getCdata($nc1)->nodeValue=getCdata($nc2)->nodeValue; + //getCdata($nc1)->nodeValue=getCdata($nc2)->nodeValue; } } catch (Exception ex) { @@ -2226,7 +2350,7 @@ public class DBMSRecords implements ServletContextAware { e.appendChild(doc.createCDATASection(data)); } } - + public static String getRandomString(int length) { final String characters = "abcdefghijklmnopqrstuvwxyz1234567890"; StringBuilder result = new StringBuilder(); @@ -2266,8 +2390,32 @@ public class DBMSRecords implements ServletContextAware { } return result; } + public String trt2(String key,User user) + { + String result=""; + JSONObject json = null; + try { + String sql="select translation from main._translations where identifier=:identifier and language_id=:language_id"; + MapSqlParameterSource parameters = new MapSqlParameterSource(); + parameters.addValue("identifier", key); + parameters.addValue("language_id", Integer.valueOf(user.language_id), Types.INTEGER); + List ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper()); + for (int i = 0; i < ret.size(); i++) { + json = new JSONObject(ret.get(i)); + break; + } + }catch (DataAccessException ex){ + String uuid = UUID.randomUUID().toString(); + logger.error(uuid,ex); + } + if(json!=null) { + result=json.getString("translation"); + } + return result; + } - //Translate text by patterns + //Translate text by patterns (новая функция ниже) + //TODO потом удалить public String trts(Connection conn,String text,User user) { int pos1 = 0; while (true) { @@ -2282,7 +2430,21 @@ public class DBMSRecords implements ServletContextAware { } return text; } - + public String trts2(String text,User user) { + int pos1 = 0; + while (true) { + pos1 = text.indexOf("trt('", pos1); + if (pos1 == -1) + break; + int pos2 = text.indexOf("')", pos1); + if (pos2 == -1) + break; + + text = text.substring(0, pos1) + trt2(text.substring(pos1 + 5, pos2),user) + text.substring(pos2 + 2); + } + return text; + } + public static String afterFirst(String str, String ch) { int i=str.indexOf(ch); @@ -2291,30 +2453,31 @@ public class DBMSRecords implements ServletContextAware { return str.substring(i+ch.length()); } return ""; - } + } - //Получить узел метаданных из базы данных + //Получить узел метаданных из базы данных (новая функция ниже) + //TODO потом удалить public String getTypeStrNode(Connection conn,String typeName) { String result=""; String sql="select xml from main._metadata where name='"+typeName+"';"; try { - Statement st = conn.createStatement(); + Statement st = conn.createStatement(); ResultSet rs=null; - try { + try { rs = st.executeQuery(sql); } catch( SQLException ex ) { ex.printStackTrace(); } try { - if(rs!=null) - { - if(rs.next()) - { - result=rs.getString(1); - } + if(rs!=null) + { + if(rs.next()) + { + result=rs.getString(1); + } rs.close(); - } + } st.close(); } catch (SQLException ex) { ex.printStackTrace(); @@ -2324,6 +2487,47 @@ public class DBMSRecords implements ServletContextAware { } return result; } + //Получить узел метаданных из базы данных (новая функция ниже) + public String getTypeStrNode2(String typeName) + { + String result=""; + try { + String sql="select xml from main._metadata where name=:name"; + MapSqlParameterSource parameters = new MapSqlParameterSource(); + parameters.addValue("name", typeName); + List ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper()); + for (int i = 0; i < ret.size(); i++) { + JSONObject json = new JSONObject(ret.get(i)); + result = json.getString("xml"); + } + }catch (DataAccessException ex){ + String uuid = UUID.randomUUID().toString(); + logger.error(uuid,ex); + } + return result; + } + + public String getAccess(String user_id,String name) + { + String allow="1"; + try { + String sql = "select main.get_Access(:user_id,:name) as acc;"; + MapSqlParameterSource parameters = new MapSqlParameterSource(); + parameters.addValue("user_id", Integer.parseInt(user_id), Types.INTEGER); + parameters.addValue("name", name); + List ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper()); + for (int i = 0; i < ret.size(); i++) { + if ((new JSONObject(ret.get(i))).getBoolean("acc")) + allow = "1"; + else + allow = "0"; + } + }catch (DataAccessException ex){ + String uuid = UUID.randomUUID().toString(); + logger.error(uuid,ex); + } + return allow; + } //Пропарсить сткоку в DOM public Document parseString(String xml) diff --git a/src/main/java/models/MetadataNameModel.java b/src/main/java/models/MetadataNameModel.java new file mode 100644 index 0000000..4e785eb --- /dev/null +++ b/src/main/java/models/MetadataNameModel.java @@ -0,0 +1,15 @@ +package models; + +//import jakarta.persistence.Column; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class MetadataNameModel { + @JsonProperty("metadata_name") + private String metadata_name; + public String getMetadataName() { + return metadata_name; + } + public void setMetadataName(String metadata_name) { + this.metadata_name = metadata_name; + } +} \ No newline at end of file diff --git a/src/main/resources/logback-spring.xml b/src/main/resources/logback-spring.xml index 02a6985..411713f 100644 --- a/src/main/resources/logback-spring.xml +++ b/src/main/resources/logback-spring.xml @@ -25,7 +25,8 @@ - + +