Первый

This commit is contained in:
2024-11-18 22:17:38 +05:00
commit 6cd3bb5e65
12 changed files with 4118 additions and 0 deletions

89
DBTools.java Normal file
View File

@ -0,0 +1,89 @@
package tools;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.jdbc.core.RowMapper;
import tctable.Tools;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
public class DBTools {
public static class JsonRowMapper implements RowMapper<String> {
@Override
public String mapRow(ResultSet rs, int rowNum) throws SQLException {
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> resultMap = new HashMap<>();
// Получаем метаданные ResultSet для получения названий столбцов
int columnCount = rs.getMetaData().getColumnCount();
for (int i = 1; i <= columnCount; i++) {
String columnName = rs.getMetaData().getColumnName(i);
Object columnValue = rs.getObject(i);
resultMap.put(columnName, columnValue);
}
// Преобразовываем Map в JSON строку
try {
return objectMapper.writeValueAsString(resultMap);
} catch (Exception e) {
throw new RuntimeException("Failed to convert Map to JSON", e);
}
}
}
public static boolean hasColumn(ResultSet rs, String columnName) throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
if (columnName.equalsIgnoreCase(metaData.getColumnName(i))) {
return true;
}
}
return false;
}
public static 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;
}
}

65
EmailUtility.java Normal file
View File

@ -0,0 +1,65 @@
//From: http://www.codejava.net/java-ee/jsp/sending-e-mail-with-jsp-servlet-and-javamail
package tools;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
* A utility class for sending e-mail messages
* @author www.codejava.net
*
*/
public class EmailUtility {
public static void sendEmail(String host, String port,
final String userName, final String password, String toAddress,
String subject, String message) throws AddressException,
MessagingException
{
// sets SMTP server properties
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
//properties.put("mail.smtp.starttls.enable","true"); STARTTLS requested but already using SSL
properties.put("mail.smtp.EnableSSL.enable","true");
properties.put("mail.smtp.socketFactory.port", port);
properties.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
//properties.put("mail.debug", "true");
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
//creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
//msg.setText(message);
msg.setContent(message, "text/html; charset=utf-8");
// sends the e-mail
Transport.send(msg);
}
}

218
PreparedStatementNamed.java Normal file
View File

@ -0,0 +1,218 @@
package tools;
//import org.ccalm.main.AcceptASDCController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PreparedStatementNamed {
private static final Logger logger = LoggerFactory.getLogger(PreparedStatementNamed.class);
private class HMap{
public String name = "";
public int pos = -1;
public HMap(String name,int pos) {
this.name = name;
this.pos = pos;
}
}
private List< HMap > fields = new ArrayList< HMap >();
private PreparedStatement m_prepStmt;
public PreparedStatementNamed(Connection conn, String sql) throws SQLException {
int cnt=0;
int pos = 0;
while((pos = sql.indexOf("${")) != -1) {
int end = sql.substring(pos).indexOf("}");
if (end == -1)
end = sql.length();
else
end += pos+1;
cnt++;
fields.add(new HMap(sql.substring(pos+2,end-1),cnt));
sql = sql.substring(0, pos) + "?" + sql.substring(end); //Removing a parameter from a string
}
m_prepStmt = conn.prepareStatement(sql);
}
public void setString(String name, String value) throws SQLException {
for(int i=0;i<fields.size();i++) {
if(fields.get(i).name.equals(name)) {
m_prepStmt.setString(fields.get(i).pos, value);
}
}
}
public void setNULLString(String name) throws SQLException {
for(int i=0;i<fields.size();i++) {
if(fields.get(i).name.equals(name)) {
m_prepStmt.setNull(fields.get(i).pos,Types.NULL);
}
}
}
public void setInt(String name, String value) throws SQLException {
if(value==null){
setNULLInt(name);
}else {
for (int i = 0; i < fields.size(); i++) {
if (fields.get(i).name.equals(name)) {
m_prepStmt.setInt(fields.get(i).pos, Integer.parseInt(value));
}
}
}
}
public void setInt(String name, int value) throws SQLException {
for(int i=0;i<fields.size();i++) {
if(fields.get(i).name.equals(name)) {
m_prepStmt.setInt(fields.get(i).pos, value);
}
}
}
public void setNULLInt(String name) throws SQLException {
for(int i=0;i<fields.size();i++) {
if(fields.get(i).name.equals(name)) {
m_prepStmt.setNull(fields.get(i).pos,Types.INTEGER);
}
}
}
public void setBoolean(String name, String value) throws SQLException {
if(value==null){
setNULLBoolean(name);
}else {
for (int i = 0; i < fields.size(); i++) {
if (fields.get(i).name.equals(name)) {
if (value.equals("0") || value.equals("false") || value.equals(""))
m_prepStmt.setBoolean(fields.get(i).pos, false);
else
m_prepStmt.setBoolean(fields.get(i).pos, true);
}
}
}
}
public void setBoolean(String name, int value) throws SQLException {
for(int i=0;i<fields.size();i++) {
if(fields.get(i).name.equals(name)) {
if(value==0)
m_prepStmt.setBoolean(fields.get(i).pos, false);
else
m_prepStmt.setBoolean(fields.get(i).pos, true);
}
}
}
public void setNULLBoolean(String name) throws SQLException {
for(int i=0;i<fields.size();i++) {
if(fields.get(i).name.equals(name)) {
m_prepStmt.setNull(fields.get(i).pos,Types.BOOLEAN);
}
}
}
/*private int getIndex(String name) {
size()
} */
public void setDouble(String name, String value) throws SQLException {
if(value==null){
setNULLDouble(name);
}else {
for (int i = 0; i < fields.size(); i++) {
if (fields.get(i).name.equals(name)) {
m_prepStmt.setDouble(fields.get(i).pos, Double.parseDouble(value));
}
}
}
}
public void setDouble(String name, double value) throws SQLException {
for(int i=0;i<fields.size();i++) {
if(fields.get(i).name.equals(name)) {
m_prepStmt.setDouble(fields.get(i).pos, value);
}
}
}
public void setNULLDouble(String name) throws SQLException {
for(int i=0;i<fields.size();i++) {
if(fields.get(i).name.equals(name)) {
m_prepStmt.setNull(fields.get(i).pos,Types.DOUBLE);
}
}
}
public void setFloat(String name, String value) throws SQLException {
if(value==null){
setNULLFloat(name);
}else {
for (int i = 0; i < fields.size(); i++) {
if (fields.get(i).name.equals(name)) {
m_prepStmt.setDouble(fields.get(i).pos, Float.parseFloat(value));
}
}
}
}
public void setFloat(String name, float value) throws SQLException {
for(int i=0;i<fields.size();i++) {
if(fields.get(i).name.equals(name)) {
m_prepStmt.setFloat(fields.get(i).pos, value);
}
}
}
public void setNULLFloat(String name) throws SQLException {
for(int i=0;i<fields.size();i++) {
if(fields.get(i).name.equals(name)) {
m_prepStmt.setNull(fields.get(i).pos,Types.FLOAT);
}
}
}
public void setTimestamp(String name, String value) throws SQLException {
if(value==null){
for(int i=0;i<fields.size();i++) {
if(fields.get(i).name.equals(name)) {
m_prepStmt.setNull(fields.get(i).pos,Types.DATE, null);
}
}
}else {
if(value.matches("\\d+")) //If old date format in UNIX time
{
long uDate=Long.parseLong(value)+1;
java.sql.Timestamp tm=new java.sql.Timestamp(uDate*1000);
for (int i = 0; i < fields.size(); i++) {
if (fields.get(i).name.equals(name)) {
m_prepStmt.setTimestamp(fields.get(i).pos, tm);
}
}
}else
{
java.sql.Timestamp tm=null;
DateFormat dfm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //2016-05-29 18:00:01 in "GMT"
try{
tm = new java.sql.Timestamp(dfm.parse(value).getTime());
} catch (Exception ex) {
logger.error("Error",ex.getMessage());
}
for (int i = 0; i < fields.size(); i++) {
if (fields.get(i).name.equals(name)) {
m_prepStmt.setTimestamp(fields.get(i).pos, tm);
}
}
}
}
}
public PreparedStatement getPreparedStatement() {
return m_prepStmt;
}
/*public ResultSet executeQuery() throws SQLException {
return m_prepStmt.executeQuery();
}
public void close() throws SQLException {
m_prepStmt.close();
}*/
}

39
STools.java Normal file
View File

@ -0,0 +1,39 @@
package tools;
import java.util.Iterator;
import java.util.Map;
public class STools {
public static String CutBeforeFirst(StringBuffer str,String ch)
{
int pos=str.indexOf(ch);
String result="";
if(pos==-1)
{
result.concat(str.toString());
str.delete(0,str.length());
}else
{
result=str.substring(0,pos);
str.delete(0,pos+1);
}
return result;
}
/**
* Удалить из списка по значению
* @param map
* @param value
*/
public static void delFromMapByValue(Map<String, String> map, String value) {
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
if (entry.getValue().equalsIgnoreCase(value)) {
iterator.remove();
}
}
}
}

82
Translation.java Normal file
View File

@ -0,0 +1,82 @@
package tools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.*;
public class Translation {
private static final Logger logger = LoggerFactory.getLogger(Translation.class);
public int language_id;
//public NamedParameterJdbcTemplate jdbcTemplate;
public Connection conn;
public Translation(String lng, Connection conn){
language_id=1;
switch (lng) {
case "kz":
case "kk":
language_id = 2;
break;
case "en":
language_id = 3;
break;
case "uz":
language_id = 4;
break;
case "ru":
default:
language_id = 1;
break;
}
this.conn = conn;
}
public String trt(String text){
boolean find = false;
String sql = """
select
translation
from
main._translations
where
del=false
and language_id=${language_id}
and identifier=${identifier};
""";
PreparedStatementNamed stmtn=null;
try {
stmtn = new PreparedStatementNamed(conn, sql);
stmtn.setInt("language_id", language_id);
stmtn.setString("identifier", text);
} catch (SQLException e) {
logger.error("Error",e);
e.printStackTrace();
}
if(stmtn!=null){
PreparedStatement stmt=stmtn.getPreparedStatement();
ResultSet rs = null;
try {
rs = stmt.executeQuery();
while (rs.next()) {
text = rs.getString(1);
find = true;
}
} catch (SQLException e) {
logger.error("Error",e);
e.printStackTrace();
}finally{
try { if (rs != null) rs.close(); } catch (Exception e) {};
try { if (stmt != null) stmt.close(); } catch (Exception e) {};
}
}
if(!find){
text = text.replace("_", " ");
}
return text;
}
}

45
User.java Normal file
View File

@ -0,0 +1,45 @@
package tools;
public class User {
public String id; //User id from database
public String name; //Name Surname Patronymic
public String language_id; //User language
public String role; //User role
public String country_id; //User role
public User()
{
id="null"; //null так как заменяю в SQL строке строку вида ${_user_id} на цифровое значение
name="___";
language_id="1";
role="___";
country_id="";
}
public User(String name)
{
super();
id="null";
this.name=name;
language_id="1";
role="___";
country_id="";
}
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
public void Logout()
{
id="null";
name="___";
language_id="1";
role="___";
country_id="";
}
}

189
XMLTools.java Normal file
View File

@ -0,0 +1,189 @@
package tools;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
public class XMLTools
{
/**
* Вернуть значение первой попавшийся CDATA
* @return строка
*/
public static String getCDATAValue(Node node)
{
if(node==null) return "";
NodeList items = node.getChildNodes();
for (int i=0;i<items.getLength();i++)
{
Node n=items.item(i);
if(n.getNodeName().equals("#cdata-section"))
return n.getNodeValue();
}
return "";
}
/** Найти узел по атрибуту
*/
public static Node findNodeOnAttribute(Node node, String nodename, String attribute, String val)
{
if(node==null) return null;
NodeList items = node.getChildNodes();
for (int i=0;i<items.getLength();i++)
{
Node n=items.item(i);
if(n.getNodeName().equals(nodename))
{
NamedNodeMap nnm=n.getAttributes();
if(nnm.getNamedItem(attribute).getNodeValue().equals(val)) return n;
}
}
return null;
}
public static Node findFirstNodeOnAttribute(Node node, String nodename,String attribute,String val)
{
Node result=null;
if(node==null) return result;
javax.xml.xpath.XPathFactory xPathfactory = javax.xml.xpath.XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr=null;
Object exprResult=null;
try {
expr = xpath.compile("//*/"+nodename+"[@"+attribute+"='" + val + "']");
exprResult = expr.evaluate(node, XPathConstants.NODESET);
} catch (XPathExpressionException ex) {
}
NodeList nodeList = (NodeList) exprResult;
if (nodeList.getLength() > 0)
result = nodeList.item(0);
return result;
}
/**
* Поиск среди текущего и дочерних узлов
* @param {Node} node Корневой узел
* @param {String} nodename Имя первого попавшегося узла
* @returns {undefined}
*/
public static Node findFirstNode(Node node, String nodename)
{
Node result=null;
if(node==null) return result;
javax.xml.xpath.XPathFactory xPathfactory = javax.xml.xpath.XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr=null;
Object exprResult=null;
try {
expr = xpath.compile("//*/"+nodename);
exprResult = expr.evaluate(node, XPathConstants.NODESET);
} catch (XPathExpressionException ex) {
}
NodeList nodeList = (NodeList) exprResult;
if (nodeList.getLength() > 0)
result = nodeList.item(0);
return result;
}
/**
* Присвоить дочерние узлы первого дерева второму если их нет, иначе дополнить либо заменить. (Работает через рекурсию нужно для передачи параметров между окнами)
* @param {XML} first Узел где ханятся настройки
* @param {XML} second Узел к которому применяются настройки
* @param {String} name Имя атрибута по которому будут находиться одинаковые XML узлы
* @returns {undefined}
*/
public static void applyNodeToNode(Node first, Node second,String name)
{
if(first==null || second==null || name==null) return;
//Если есть совпадающие узлы то передаём в рекурсию если нет то просто копируем
Node fn=first.getFirstChild();
while (fn != null)
{
Node sn=null;
if(!fn.getNodeName().equals("#text") && !fn.getNodeName().equals("#cdata-section") && !fn.getNodeName().equals("#comment")) { //потому что для этих getAttribute вызывает ошибку
sn=findNodeOnAttribute(second,fn.getNodeName(),name,fn.getAttributes().getNamedItem(name).getNodeValue());
}
if(sn!=null) //Если по имени атрибуту совпали узлы
{
//Переписываем значения атрибутов из первого второму, если их нет то создаём.
for(int i=0;i<fn.getAttributes().getLength();i++)
{
Element el=(Element) sn;
el.setAttribute(fn.getAttributes().item(i).getNodeName(),fn.getAttributes().item(i).getNodeValue());
}
applyNodeToNode(fn,sn,name); //В рекурсию
}
else
{
//Значения CDADA или text node не должны накапливаться их мы пересоздаём (потом по момеру можно сделать 1й заменяется первым итд.)
if(fn.getNodeName().equals("#cdata-section"))
{
XMLTools.setCharacterDataToElement((Element)second, XMLTools.getCharacterDataFromElement((Element) fn)); //getCdata(second).nodeValue = fn.nodeValue;
}else
{
second.appendChild(fn.cloneNode(true));
}
}
fn=fn.getNextSibling();
}
}
/**
* Найти узел по имени
* @param node
* @param nodename
* @return
*/
public static Node findNode(Node node, String nodename)
{
if(node==null || nodename==null) return null;
NodeList items = node.getChildNodes();
for (int i=0;i<items.getLength();i++)
{
Node n=items.item(i);
if(n.getNodeName().equals(nodename))
{
return n;
}
}
return null;
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData().trim();
}
return "";
}
public static void setCharacterDataToElement(Node nF, String data) {
Node child = nF.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
cd.setData(data);
} else //Create new CDATA node
{
Document doc = nF.getOwnerDocument();
nF.appendChild(doc.createCDATASection(data));
}
}
}

14
tctable/Point.java Normal file
View File

@ -0,0 +1,14 @@
/**
* Created by IntelliJ IDEA.
* User: igor
* Date: 09.03.2007
* Time: 0:53:45
* To change this template use File | Settings | File Templates.
*/
package tctable;
public class Point
{
public double x=0;
public double y=0;
}

574
tctable/TCField.java Normal file
View File

@ -0,0 +1,574 @@
package tctable;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
public class TCField
{
//Типы данных
public static final int BD_NULL = 1000; //Столбец со значением всегда NULL
public static final int BD_UINT1 = 0; //1 байт без знаковый
public static final int BD_UINT2 = 1; //2 байта без знаковый
public static final int BD_UINT4 = 3; //4 байта без знаковый
public static final int BD_UINT8 = 23; //8 байта без знаковый
public static final int BD_SUINT8 = 24; //Почти тоже самое что и BD_UTF8_1 но с строке передаётся число
public static final int BD_INT1 = 10; //1 байт со знаковый
public static final int BD_INT2 = 11; //2 байта со знаковый
public static final int BD_INT4 = 13; //4 байта со знаковый
public static final int BD_INT8 = 17; //8 байт со знаковый
public static final int BD_SINT8 = 25; //Почти тоже самое что и BD_UTF8_1 но с строке передаётся число
public static final int BD_FLOAT4 = 20; //4 байта
public static final int BD_FLOAT8 = 22; //8 байт double
public static final int BD_SFLOAT8 = 26; //Почти тоже самое что и BD_UTF8_1 но с строке передаётся число
public static final int BD_UTF8_1 = 100; //100 - utf8_1 string 1й байт размер строки в байтах
public static final int BD_UTF8_2 = 101; //101 - utf8_2 string 1х 2 байта размер строки в байтах
public static final int BD_UTF8_4 = 102; //102 - utf8_4 string 1х 4 байта размер строки в байтах
public static final int BD_BLOB_2 = 141;
public static final int BD_BLOB_4 = 143; //Двоичные данные uint4 количество байт
public String name=""; //Название столбца
public int type=-1; //Тип данных
public byte[] value=null; //Запакованые данные
public TCField(String name, int type)
{
this.name=name;
this.type=type;
}
public TCField(String name, String type)
{
this.name=name;
//this.type=type;
this.type= TCField.BD_UTF8_2; //Defalt type
//From PostgreSQL and MySQL
if(type.equals("null")) { this.type= TCField.BD_NULL; } else
if(type.equals("bool") || type.equals("tinyint")) { this.type= TCField.BD_UINT1; } else
if(type.equals("int4") || type.equals("int") || type.equals("serial") || type.equals("bigint")) { this.type= TCField.BD_INT4; } else //bigint немного неправильно потому что это 64 бита но для андрод приложения не сделал
if(type.equals("int8")) { this.type= TCField.BD_INT8; } else
if(type.equals("float4") || type.equals("float")) { this.type= TCField.BD_FLOAT4; } else
if(type.equals("float8") || type.equals("NUMBER")) { this.type= TCField.BD_FLOAT8; } else
if(type.equals("varchar") || type.equals("VARCHAR2")) { this.type= TCField.BD_UTF8_2; } else
if(type.equals("text")) { this.type= TCField.BD_UTF8_4; } else
if(type.equals("bytea") || type.equals("longblob")) { this.type= TCField.BD_BLOB_4; } else
if(type.equals("timestamptz")) { this.type= TCField.BD_UTF8_1; } else
if(type.equals("timestamp")) { this.type= TCField.BD_UTF8_1; } else
if(type.equals("date")) { this.type= TCField.BD_UTF8_1; }
}
private int byteArrayToInt(byte[] b, int start, int length)
{
int dt = 0;
if ((b[start] & 0x80) != 0)
dt = Integer.MAX_VALUE;
for (int i = 0; i < length; i++)
dt = (dt << 8) + (b[start++] & 255);
return dt;
}
/*
private byte[] intToByteArray(int n, int byteCount)
{
byte[] res = new byte[byteCount];
for (int i = 0; i < byteCount; i++)
res[byteCount - i - 1] = (byte) ((n >> i * 8) & 255);
return res;
}
*/
//Прочитать значение из потока в соответствии с типом
public void ReadValue(InputStream fileHandle) throws IOException
{
if(this.type== TCField.BD_UINT1)
{
value=new byte[1];
fileHandle.read(value);
}else
if(this.type== TCField.BD_UINT2)
{
value=new byte[2];
fileHandle.read(value);
}else
if(this.type== TCField.BD_UINT4)
{
value=new byte[4];
fileHandle.read(value);
}else
if(this.type== TCField.BD_UINT8)
{
value=new byte[8];
fileHandle.read(value);
}else
if(this.type== TCField.BD_INT1)
{
value=new byte[1];
fileHandle.read(value);
}else
if(this.type== TCField.BD_INT2)
{
value=new byte[2];
fileHandle.read(value);
}else
if(this.type== TCField.BD_INT4)
{
value=new byte[4];
fileHandle.read(value);
}else
if(this.type== TCField.BD_INT8)
{
value=new byte[8];
fileHandle.read(value);
}else
if(this.type== TCField.BD_FLOAT4)
{
value=new byte[4];
fileHandle.read(value);
}else
if(this.type== TCField.BD_FLOAT8)
{
value=new byte[8];
fileHandle.read(value);
}else
if(this.type== TCField.BD_UTF8_1 || this.type== TCField.BD_SUINT8 || this.type== TCField.BD_SINT8 || this.type== TCField.BD_SFLOAT8)
{
byte[] s=new byte[1];
fileHandle.read(s);
if(s[0]==0) value=null;
else
{
value=new byte[s[0]];
fileHandle.read(value);
}
}else
if(this.type== TCField.BD_UTF8_2)
{
int s=Tools.readUShort(fileHandle);
if(s==0) value=null;
else
{
value=new byte[s];
fileHandle.read(value);
}
}else
if(this.type== TCField.BD_UTF8_4)
{
long s=Tools.readUInt(fileHandle);
if(s==0) value=null;
else
{
value=new byte[(int)s];
fileHandle.read(value);
}
}else
if(this.type== TCField.BD_BLOB_4)
{
byte[] ss=new byte[4];
fileHandle.read(ss);
int s=byteArrayToInt(ss, 0, 4);
if(s==0) value=null;
else
{
value=new byte[s];
fileHandle.read(value);
}
}
}
public String getStrVal()
{
String result=null;
try
{
if(value==null) result = "";
if(type== TCField.BD_UINT1) result = String.valueOf(getUByteVal());
if(type== TCField.BD_UINT4) result = String.valueOf(getUIntVal());
if(type== TCField.BD_UINT8) result = String.valueOf(getULongVal());
if(type== TCField.BD_INT4) result = String.valueOf(getIntVal());
if(type== TCField.BD_INT8) result = String.valueOf(getLongVal());
if(type== TCField.BD_FLOAT4) result = String.valueOf(getFloatVal());
if(type== TCField.BD_FLOAT8) result = String.valueOf(getDoubleVal());
if(type== TCField.BD_UTF8_1 || type== TCField.BD_UTF8_2 || type== TCField.BD_UTF8_4 || type== TCField.BD_SUINT8 || type== TCField.BD_SINT8 || type== TCField.BD_SFLOAT8)
{
result = new String(value, "UTF8");
}
} catch (Exception e) {}
return result;
}
public boolean getBoolVal(){
String result=getStrVal();
if(result==null)
return false;
else {
result=result.toLowerCase();
if (result.equals("1") || result.equals("true") || result.equals("t"))
return true;
else
return false;
}
}
public int getIntVal()
{
int val=0;
if(type==BD_INT4) {
int i1 = value[0] & 0xff;
int i2 = value[1] & 0xff;
int i3 = value[2] & 0xff;
int i4 = value[3] & 0xff;
val = i4 << 24 | i3 << 16 | i2 << 8 | i1;
}else{
String sVal = getStrVal();
if(sVal!=null) {
try {
val = Integer.valueOf(sVal);
} catch (NumberFormatException e) {
}
}
}
return val;
}
public long getLongVal()
{
long val=0;
if(type==BD_INT8) {
long ch1, ch2, ch3, ch4, ch5, ch6, ch7, ch8;
ch1 = value[0] & 0xff;
ch2 = value[1] & 0xff;
ch3 = value[2] & 0xff;
ch4 = value[3] & 0xff;
ch5 = value[4] & 0xff;
ch6 = value[5] & 0xff;
ch7 = value[6] & 0xff;
ch8 = value[7] & 0xff;
val = (ch8 << 56) | (ch7 << 48) | (ch6 << 40) | (ch5 << 32) | (ch4 << 24) | (ch3 << 16) | (ch2 << 8) | ch1;
}else{
String sVal = getStrVal();
if(sVal!=null) {
try {
val = Long.valueOf(sVal);
} catch (NumberFormatException e) {
}
}
}
return val;
}
/** Пока не использую но если буду использовать протестировать с большими числами */
public long getUIntVal()
{
long val=0;
if(type==BD_UINT4) {
long ch1, ch2, ch3, ch4;
ch1 = value[0] & 0xff;
ch2 = value[1] & 0xff;
ch3 = value[2] & 0xff;
ch4 = value[3] & 0xff;
val = (ch4 << 24) | (ch3 << 16) | (ch2 << 8) | ch1;
}else{
String sVal = getStrVal();
if(sVal!=null) {
try {
val = Long.valueOf(sVal);
} catch (NumberFormatException e) {
}
}
}
return val;
}
public long getULongVal()
{
long val=0;
if(type==BD_UINT8) {
long ch1, ch2, ch3, ch4, ch5, ch6, ch7, ch8;
ch1 = value[0] & 0xff;
ch2 = value[1] & 0xff;
ch3 = value[2] & 0xff;
ch4 = value[3] & 0xff;
ch5 = value[4] & 0xff;
ch6 = value[5] & 0xff;
ch7 = value[6] & 0xff;
ch8 = value[7] & 0xff;
val = (ch8 << 56) | (ch7 << 48) | (ch6 << 40) | (ch5 << 32) | (ch4 << 24) | (ch3 << 16) | (ch2 << 8) | ch1;
}else{
String sVal = getStrVal();
if(sVal!=null) {
try {
val = Long.valueOf(sVal);
} catch (NumberFormatException e) {
}
}
}
return val;
}
public short getUByteVal()
{
short val=0;
if(type==BD_UINT1) {
val = (short) (value[0] & 0xff);
}else{
String sVal = getStrVal();
if(sVal!=null) {
try {
val = Short.valueOf(sVal);
} catch (NumberFormatException e) {
}
}
}
return val;
}
public float getFloatVal()
{
float val=0;
if(type==BD_FLOAT4) {
int ch1, ch2, ch3, ch4, count;
ch1 = value[0] & 0xFF;
ch2 = value[1] & 0xFF;
ch3 = value[2] & 0xFF;
ch4 = value[3] & 0xFF;
count = (ch4 << 24) | (ch3 << 16) | (ch2 << 8) | ch1;
val = Float.intBitsToFloat(count);
}else{
String sVal = getStrVal();
if(sVal!=null) {
try {
val = Float.valueOf(sVal);
} catch (NumberFormatException e) {
}
}
}
return val;
}
public double getDoubleVal()
{
double val=0;
if(type==BD_FLOAT8) {
int ch1, ch2, ch3, ch4, ch5, ch6, ch7, ch8;
long count;
ch1 = value[0] & 0xFF;
ch2 = value[1] & 0xFF;
ch3 = value[2] & 0xFF;
ch4 = value[3] & 0xFF;
ch5 = value[4] & 0xFF;
ch6 = value[5] & 0xFF;
ch7 = value[6] & 0xFF;
ch8 = value[7] & 0xFF;
count = ((long) ch8 << 56) |
((long) ch7 << 48) |
((long) ch6 << 40) |
((long) ch5 << 32) |
((long) ch4 << 24) |
((long) ch3 << 16) |
((long) ch2 << 8) |
ch1;
val = Double.longBitsToDouble(count);
}else{
String sVal = getStrVal();
if(sVal!=null) {
try {
val = Double.valueOf(sVal);
} catch (NumberFormatException e) {
}
}
}
return val;
}
public boolean setDoubleVal(Double v){
long iv= Double.doubleToLongBits(v);
value=new byte[8];
value[0] = (byte)((iv & 0x00000000000000ffl));
value[1] = (byte)((iv & 0x000000000000ff00l) >> 8);
value[2] = (byte)((iv & 0x0000000000ff0000l) >> 16);
value[3] = (byte)((iv & 0x00000000ff000000l) >> 24);
value[4] = (byte)((iv & 0x000000ff00000000l) >> 32);
value[5] = (byte)((iv & 0x0000ff0000000000l) >> 40);
value[6] = (byte)((iv & 0x00ff000000000000l) >> 48);
value[7] = (byte)((iv & 0xff00000000000000l) >> 56);
return true;
}
public boolean setValue(String val)
{
boolean result=true;
if(val==null)
{ value=null;
}else if(type== TCField.BD_UINT1)
{
if(val.equals("f") || val.equals("false")) val="0";
else if(val.equals("t") || val.equals("true")) val="1";
int v= Integer.parseInt(val);
if(v<0 || v>255) result=false;
value=new byte[1];
value[0]=(byte)v;
}else if(type== TCField.BD_UINT2)
{
int v= Integer.parseInt(val);
if(v<0 || v>65535) result=false;
value=new byte[2];
value[0] = (byte)((v & 0x000000ff));
value[1] = (byte)((v & 0x0000ff00) >> 8);
}else if(type== TCField.BD_UINT4)
{
long v= Long.parseLong(val);
value=new byte[4];
value[0] = (byte)((v & 0x000000ff));
value[1] = (byte)((v & 0x0000ff00) >> 8);
value[2] = (byte)((v & 0x00ff0000) >> 16);
value[3] = (byte)((v & 0xff000000) >> 24);
}else if(type== TCField.BD_UINT8)
{
long v= Long.parseLong(val);
value=new byte[8];
value[0] = (byte) (v & 0x00000000000000ffl);
value[1] = (byte)((v & 0x000000000000ff00l) >> 8);
value[2] = (byte)((v & 0x0000000000ff0000l) >> 16);
value[3] = (byte)((v & 0x00000000ff000000l) >> 24);
value[4] = (byte)((v & 0x000000ff00000000l) >> 32);
value[5] = (byte)((v & 0x0000ff0000000000l) >> 40);
value[6] = (byte)((v & 0x00ff000000000000l) >> 48);
value[7] = (byte)((v & 0xff00000000000000l) >> 56);
}else if(type== TCField.BD_INT1)
{
int v= Integer.parseInt(val);
value=new byte[1];
value[0]=(byte)v;
}else if(type== TCField.BD_INT2)
{
int v= Integer.parseInt(val);
value=new byte[2];
value[0] = (byte)((v & 0x000000ff));
value[1] = (byte)((v & 0x0000ff00) >> 8);
}else if(type== TCField.BD_INT4)
{
long v= Long.parseLong(val);
value=new byte[4];
value[0] = (byte)((v & 0x000000ff));
value[1] = (byte)((v & 0x0000ff00) >> 8);
value[2] = (byte)((v & 0x00ff0000) >> 16);
value[3] = (byte)((v & 0xff000000) >> 24);
}else if(type== TCField.BD_INT8)
{
long v= Long.parseLong(val);
value=new byte[8];
value[0] = (byte) (v & 0x00000000000000ffl);
value[1] = (byte)((v & 0x000000000000ff00l) >> 8);
value[2] = (byte)((v & 0x0000000000ff0000l) >> 16);
value[3] = (byte)((v & 0x00000000ff000000l) >> 24);
value[4] = (byte)((v & 0x000000ff00000000l) >> 32);
value[5] = (byte)((v & 0x0000ff0000000000l) >> 40);
value[6] = (byte)((v & 0x00ff000000000000l) >> 48);
value[7] = (byte)((v & 0xff00000000000000l) >> 56);
}else if(type== TCField.BD_FLOAT4)
{
Float v= Float.parseFloat(val);
int iv= Float.floatToIntBits(v);
value=new byte[4];
value[0] = (byte)((iv & 0x000000ff));
value[1] = (byte)((iv & 0x0000ff00) >> 8);
value[2] = (byte)((iv & 0x00ff0000) >> 16);
value[3] = (byte)((iv & 0xff000000) >> 24);
}else if(type== TCField.BD_FLOAT8)
{
setDoubleVal(Double.parseDouble(val));
}else if(type== TCField.BD_UTF8_1 || this.type== TCField.BD_SUINT8 || this.type== TCField.BD_SINT8 || this.type== TCField.BD_SFLOAT8)
{
value=null;
if(val!=null && !val.equals(""))
{
byte[] b=null;
try {
b = val.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
result=false;
}
if(b!=null)
{
int len=b.length;
if(len>255) len=255;
value=new byte[len+1];
value[0]=(byte)len;
for(int i=0;i<len;i++)
{
value[i+1]=b[i];
}
}
}
}else if(type== TCField.BD_UTF8_2)
{
value=null;
if(val!=null && !val.equals(""))
{
byte[] b=null;
try {
b = val.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
result=false;
}
if(b!=null)
{
int len=b.length;
if(len>65535) len=65535;
value=new byte[len+2];
value[0]=(byte) (len & 0x000000ff);
value[1]=(byte)((len & 0x0000ff00) >> 8);
for(int i=0;i<len;i++)
{
value[i+2]=b[i];
}
}
}
}else if(type== TCField.BD_UTF8_4)
{
value=null;
if(val!=null && !val.equals(""))
{
byte[] b=null;
try {
b = val.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
result=false;
}
if(b!=null)
{
int len=b.length;
value=new byte[len+4];
value[0]=(byte) (len & 0x000000ff);
value[1]=(byte)((len & 0x0000ff00) >> 8);
value[2]=(byte)((len & 0x00ff0000) >> 16);
value[3]=(byte)((len & 0xff000000) >> 24);
for(int i=0;i<len;i++)
{
value[i+4]=b[i];
}
}
}
}
return result;
}
public boolean isNull() {
return value==null;
}
public BigDecimal getBigDecimalVal() {
BigDecimal val=new BigDecimal("0");
String sVal = getStrVal();
if(sVal!=null) {
try {
val = new BigDecimal(sVal);
} catch (NumberFormatException e) {
}
}
return val;
}
}

200
tctable/TCTable.java Normal file
View File

@ -0,0 +1,200 @@
package tctable;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
public class TCTable
{
public int id=0; //Идентификатор таблицы
public String name=""; //Название таблицы
public List<TCField> fields=new ArrayList<TCField>(); //Список полей
private int nc=0; //Байтов под NULL значения
private byte[] m_NULL=null; //NULL значения
private InputStream m_file;
/**
* Конструктор
* @param Строка name Название таблицы
* @param Целое id Идентификатор таблицы (обычно уникальный)
*/
public TCTable(String name, int id)
{ this.name=name;
this.id=id;
}
//Открыть таблицу по названию файла
/*function OpenTableF(file)
{
if(file_exists(file))
{
this.OpenTableH(fopen(file,'r'));
}
}*/
//Открыть таблицу из потока HANDLE
public boolean OpenTableH(InputStream handle) throws IOException
{
this.m_file=handle;
DataInputStream dis = new DataInputStream(handle);
if(Tools.readUShort(dis)!=65500) return false; //id файла
if(Tools.readUShort(dis)!=1) return false; //Версия файла
this.id= Tools.readInt(dis); //ID таблицы или запроса (4 байта можно сделать 2)
if(dis.readByte()!=0) return false; //Только плотные таблицы
//Считываем название таблицы
this.name = Tools.readUTF8_1(dis);
//Считываем столбцы
int count=dis.readUnsignedByte(); //Количество столбцов
for(int i=0;i<count;i++)
{
TCField field=new TCField(Tools.readUTF8_1(dis), dis.readUnsignedByte());
this.addField(field);
}
return true;
}
//Открыть таблицу из потока
//OpenTable
//Прочитать следующую запись из потока
public boolean ReadNextRecord()
{
Boolean result=true;
try
{
DataInputStream dis = new DataInputStream(m_file);
//if(m_file.available()) return false; //Неработает
if(dis.available()==0)
return false;
//Считываем NULL значения
if(m_NULL==null) m_NULL = new byte[nc];
for(int i=0;i<nc;i++)
{
m_NULL[i]=(byte)dis.readUnsignedByte();
}
clearRows();
for(int i=0;i<fields.size();i++)
{
if(Tools.getBit(m_NULL,i))
{
fields.get(i).ReadValue(m_file);
}
}
}catch(Exception e)
{
result=false;
}
return result;
}
//Добавить поле к таблице
public void addField(TCField field)
{ if(field!=null)
{ fields.add(field);
this.nc=(int) Math.ceil(fields.size()/8.0); //Байтов под NULL
m_NULL=new byte[nc];
}
}
//Получить заголовок плотной таблицы в виде двоичной строки
public boolean getHeader(OutputStream os)
{
boolean result=true;
try {
//File ID: 2 bytes.
os.write((65500 & 0x000000ff));
os.write((65500 & 0x0000ff00) >> 8);
//File version: 2 bytes.
os.write((1 & 0x000000ff));
os.write((1 & 0x0000ff00) >> 8);
//Table ID (or Request ID): 4 bytes.
os.write((this.id & 0x000000ff));
os.write((this.id & 0x0000ff00) >> 8);
os.write((this.id & 0x00ff0000) >> 16);
os.write((this.id & 0xff000000) >> 24);
//Table type: 1 byte (0- "Dense" 1- "Loose")
os.write(0);
//UTF8_1 String
byte[] ba = this.name.getBytes("UTF-8");
os.write(ba.length);
os.write(ba);
//Count of fields: 1 byte.
os.write(this.fields.size());
//Write name and type id
for(int i=0;i<this.fields.size();i++)
{
ba = this.fields.get(i).name.getBytes("UTF-8");
os.write(ba.length);
os.write(ba);
os.write(this.fields.get(i).type);
}
} catch (IOException e) {
result=false;
}
return result;
}
//Получить данные 1 записи в виде строки
public boolean getCol(OutputStream os)
{
boolean result=true;
//Запишем NULL значения побайтно (1-есть данные 0-нету данных)
int nc=(int) Math.ceil(fields.size()/8.0); //Байтов под NULL
byte[] fNULL=new byte[nc];
for(int i=0;i<nc*8;i++)
{
if(i<this.fields.size() && this.fields.get(i).value!=null)
{
Tools.setBit(fNULL,i);
}
}
//Write NULL fields
try {
os.write(fNULL);
} catch (IOException e1) {
result=false;
}
//Запишем сами данные в строку
for(int i=0;i<fields.size();i++)
{
try {
if(fields.get(i).value!=null)
os.write(fields.get(i).value);
} catch (IOException e) {
result=false;
}
}
return result;
}
//Row очистить запись
void clearRows()
{ for(int i=0;i<fields.size();i++)
{
fields.get(i).value=null;
}
}
//Получить обьект столбца по имени
public TCField getRowByName(String name)
{ for(int i=0;i<fields.size();i++)
{ if(fields.get(i).name.toUpperCase().equals(name.toUpperCase())) return fields.get(i);
}
return null;
}
//Получить объект столбца по номеру
TCField getRowByNum(int num)
{ return fields.get(num);
}
}

74
tctable/TCTableTools.java Normal file
View File

@ -0,0 +1,74 @@
package tctable;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
//В андроид не используется данный класс
public class TCTableTools {
//Записать таблицу в OutputStream
public static boolean getTCTableFromResultSet(String name, int id, ResultSet rs, OutputStream os){
TCTable tbl=new TCTable(name,id);
try {
ResultSetMetaData rsmd = rs.getMetaData();
for(int i=1;i<=rsmd.getColumnCount();i++)
{
TCField field = new TCField(rsmd.getColumnName(i), rsmd.getColumnTypeName(i));
tbl.addField(field);
}
tbl.getHeader(os);
while (rs.next())
{
for(int i=1;i<=rsmd.getColumnCount();i++)
{
if(rsmd.getColumnTypeName(i).equals("geometry")) { //Геометрию не сохраняю пока не знаю как лучьше сохранять
tbl.fields.get(i - 1).setValue(null);
}else {
tbl.fields.get(i - 1).setValue(rs.getString(i));
}
}
tbl.getCol(os);
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
//Напиши функцию: Получить ассоциативный массив название полей таблицы и их тип
public static Map<String, String> getTableSchema(Connection connection, String schemaName, String tableName) {
Map<String, String> schemaMap = new HashMap<>();
String query = """
SELECT c.column_name,
CASE
WHEN t.typtype = 'e' THEN 'enum'
WHEN t.typname = 'USER-DEFINED' THEN
(SELECT pt.typname FROM pg_type pt WHERE pt.oid = c.udt_name::regtype::oid)
ELSE t.typname
END as data_type
FROM information_schema.columns c
JOIN pg_type t ON c.udt_name = t.typname
WHERE c.table_schema = ?
AND c.table_name = ?
""";
try (PreparedStatement statement = connection.prepareStatement(query)) {
statement.setString(1, schemaName);
statement.setString(2, tableName);
try (ResultSet resultSet = statement.executeQuery()) {
while (resultSet.next()) {
String columnName = resultSet.getString("column_name");
String columnType = resultSet.getString("data_type");
schemaMap.put(columnName, columnType);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return schemaMap;
}
}

2529
tctable/Tools.java Normal file

File diff suppressed because it is too large Load Diff