Загрузка чужих из базы

This commit is contained in:
Igor I
2024-07-12 17:03:56 +05:00
parent a427ed1add
commit de65b08de2
6 changed files with 12 additions and 882 deletions

View File

@ -1462,7 +1462,7 @@ public class DbOpenHelper extends SQLiteOpenHelper
String[] par = new String[] { tbl.getRowByName("id").getStrVal() };
Cursor cursor = getReadableDatabase().rawQuery(sql, par);
boolean b=cursor.moveToFirst();
boolean exists=cursor.moveToFirst();
cursor.close();
ContentValues cv = new ContentValues();
@ -1471,7 +1471,7 @@ public class DbOpenHelper extends SQLiteOpenHelper
//if(b && tbl.fields.get(i).name.equals("id")) continue; //Если существует не записываем
//Log.i("igor","fld="+tbl.fields.get(i).name+" val="+tbl.fields.get(i).getStrVal()); //Для дебага
if(fb[i]) //Присваиваем только поля существующие локально
if(fb[i]) //Присваиваем только поля существующие в локальной базе
{
if(tbl.fields.get(i).value==null)
cv.putNull(tbl.fields.get(i).name);
@ -1480,7 +1480,7 @@ public class DbOpenHelper extends SQLiteOpenHelper
}
}
if(!b)
if(!exists)
{
db.beginTransaction(); //Вроде как защита от многопоточности (для сервиса)
try {
@ -1502,7 +1502,6 @@ public class DbOpenHelper extends SQLiteOpenHelper
}
db.close();
/*
//Для дебага
Cursor cursor = getReadableDatabase().rawQuery("select sum(1) s from "+tbl.name,null);
if(cursor.moveToFirst())
@ -1512,7 +1511,7 @@ public class DbOpenHelper extends SQLiteOpenHelper
}while (cursor.moveToNext());
}
cursor.close();
*/
/**/
return true;
}

View File

@ -335,9 +335,11 @@ public class MySynchronizationOld
String xml="";
String android_id = Settings.Secure.getString(_context.getContentResolver(), Settings.Secure.ANDROID_ID);
//Последовательно отправляю изменёные пользователям записи (send=0 и они заполнены)
DbOpenHelper dboh = new DbOpenHelper(_context);
Cursor cursor = dboh.getReadableDatabase().rawQuery("select uid from frmlocust where send=0 and filled=1", null);
Cursor cursor = dboh.getReadableDatabase().rawQuery("select uid from frmlocust where send=0 and filled=1 and device_id=?", new String[]{ android_id });
if(cursor.moveToFirst())
{
do{
@ -349,7 +351,7 @@ public class MySynchronizationOld
//Последовательно отправляю изменёные пользователям записи (send=0 и они заполнены)
dboh = new DbOpenHelper(_context);
cursor = dboh.getReadableDatabase().rawQuery("select uid from frmlocustdel where send=0 and filled=1", null);
cursor = dboh.getReadableDatabase().rawQuery("select uid from frmlocustdel where send=0 and filled=1 and device_id=?", new String[]{ android_id });
if(cursor.moveToFirst())
{
do{

View File

@ -1,14 +0,0 @@
/**
* 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;
}

View File

@ -0,0 +1 @@
O:/projects/Workspace_Java/CCALM_main/src/main/java/tctable/Point.java

View File

@ -1,388 +0,0 @@
package tctable;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
public class TCField
{
//Типы данных
static int BD_UINT1 = 0; //1 байт без знаковый
static int BD_UINT2 = 1; //2 байта без знаковый
static int BD_UINT4 = 3; //4 байта без знаковый
static int BD_INT1 = 10; //1 байт со знаковый
static int BD_INT2 = 11; //2 байта со знаковый
static int BD_INT4 = 13; //4 байта со знаковый
static int BD_INT8 = 17; //8 байт со знаковый
static int BD_FLOAT4 = 20; //4 байта
static int BD_FLOAT8 = 22; //8 байт double
static int BD_UTF8_1 = 100; //100 - utf8_1 string 1й байт размер строки в байтах
static int BD_UTF8_2 = 101; //101 - utf8_2 string 1х 2 байта размер строки в байтах
static int BD_UTF8_4 = 102; //102 - utf8_4 string 1х 4 байта размер строки в байтах
static int BD_BLOB_2 = 141;
static 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("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_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)
{
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_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_INT4) result = String.valueOf(getIntVal());
if(type== TCField.BD_FLOAT4) result = String.valueOf(getFloatVal());
if(type== TCField.BD_UTF8_1 || type== TCField.BD_UTF8_2)
{
result = new String(value, "UTF8");
}
} catch (Exception e) {}
return result;
}
public int getIntVal()
{
int i1 = value[0] & 0xff;
int i2 = value[1] & 0xff;
int i3 = value[2] & 0xff;
int i4 = value[3] & 0xff;
int val = i4 << 24 | i3 << 16 | i2 << 8 | i1;
return val;
}
/** Пока не использую но если буду использовать протестировать с большими числами */
public long getUIntVal()
{
long 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;
return count;
}
public short getUByteVal()
{
return (short) (value[0] & 0xff);
}
public float getFloatVal()
{
float f;
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;
f = Float.intBitsToFloat(count);
return f;
}
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_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)
{
Double v= Double.parseDouble(val);
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);
}else if(type== TCField.BD_UTF8_1)
{
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];
}
}
}
}
/*
if($this->type==TCField::$BD_BLOB_4)
{ return pack("I",strlen($value)).$value;
}
*/
return result;
}
}

View File

@ -0,0 +1 @@
O:/projects/Workspace_Java/CCALM_main/src/main/java/tctable/TCField.java

View File

@ -1,200 +0,0 @@
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);
}
}

View File

@ -0,0 +1 @@
O:/projects/Workspace_Java/CCALM_main/src/main/java/tctable/TCTable.java

View File

@ -1,273 +0,0 @@
package tctable;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.TimeZone;
public class Tools {
public static String readStringFromInputStream(InputStream inputStream) {
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
try {
while ((length = inputStream.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
} catch (IOException e1) {
e1.printStackTrace();
}
// StandardCharsets.UTF_8.name() > JDK 7
try {
return result.toString("UTF-8");
} catch (UnsupportedEncodingException e) {
}
return "";
}
//Преобразовать арабские и индийские в современные цифры
public static String numConvert(String str)
{
if(str==null) return null;
String persian = "۰۱۲۳۴۵۶۷۸۹";
String arabic = "٩٨٧٦٥٤٣٢١٠";
String num = "0123456789";
//Заменяю персидские
for(int i=0;i<str.length();i++)
{
for(int j=0;j<persian.length();j++)
{
if(str.charAt(i)==persian.charAt(j))
{
str = str.substring(0,i) + num.charAt(j) + str.substring(i+1);
break;
}
}
}
//Заменяю арабские
for(int i=0;i<str.length();i++)
{
for(int j=0;j<arabic.length();j++)
{
if(str.charAt(i)==arabic.charAt(j))
{
str = str.substring(0,i) + num.charAt(j) + str.substring(i+1);
break;
}
}
}
return str;
}
//Получить бит по его номеру нумерация лева на право
public static boolean getBit(byte[] mas, int pos)
{
int n=(int) Math.floor(pos/8.0);
int b=mas[n];
pos=pos - n * 8;
if(((b << pos) & 128) == 128)
return true;
else
return false;
}
//Установить 1й бит в номер нумерация с лева на право
public static void setBit(byte[] mas, int pos)
{
int n=(int) Math.floor(pos/8.0);
pos=pos - n * 8;
mas[n] = (byte)(mas[n] | (128 >> pos));
}
public static String readUTF8_1(InputStream handle) throws IOException
{
byte[] tmp=new byte[handle.read()];
handle.read(tmp);
return new String(tmp, "UTF8");
}
public static float readFloat(DataInputStream InStream) throws IOException
{
float f;
int ch1, ch2, ch3, ch4, count;
ch1 = InStream.readUnsignedByte();
ch2 = InStream.readUnsignedByte();
ch3 = InStream.readUnsignedByte();
ch4 = InStream.readUnsignedByte();
count = (ch4 << 24) | (ch3 << 16) | (ch2 << 8) | ch1;
f = Float.intBitsToFloat(count);
return f;
}
public static int readInt(DataInputStream InStream) throws IOException
{
int ch1, ch2, ch3, ch4, count;
ch1 = InStream.readUnsignedByte();
ch2 = InStream.readUnsignedByte();
ch3 = InStream.readUnsignedByte();
ch4 = InStream.readUnsignedByte();
count = (ch4 << 24) | (ch3 << 16) | (ch2 << 8) | ch1;
return count;
}
public static short readShort(DataInputStream InStream) throws IOException
{
int ch1, ch2, count;
ch1 = InStream.readUnsignedByte();
ch2 = InStream.readUnsignedByte();
count = (ch2 << 8) | ch1;
return (short)count;
}
public static int readUShort(InputStream InStream) throws IOException
{
int ch1, ch2;
ch1 = InStream.read();
ch2 = InStream.read();
return (ch2 << 8) | ch1;
}
public static String afterLast(String str, String ch)
{
int i=str.lastIndexOf(ch);
if(i!=-1)
{
return str.substring(i+ch.length());
}
return "";
}
public static String beforeLast(String str, String ch)
{
int i=str.lastIndexOf(ch);
if(i!=-1)
{
return str.substring(0,i);
}
return "";
}
public static String beforeFirst(String str, String ch)
{
int i=str.indexOf(ch);
if(i!=-1)
{
return str.substring(0,i);
}
return "";
}
//узнать точку пересичений 2х линай если x=0 и y=0 то не пересиклась
public static Point getCrossingLine(Point PHead0, Point PTail0, Point PHead1, Point PTail1)
{
Point rezPoint = new Point();
double a0, b0, c0, a1, b1, c1;
boolean bRez = true;
a0 = PTail0.y - PHead0.y;
b0 = PHead0.x - PTail0.x;
c0 = PTail0.x * PHead0.y - PHead0.x * PTail0.y;
a1 = PTail1.y - PHead1.y;
b1 = PHead1.x - PTail1.x;
c1 = PTail1.x * PHead1.y - PHead1.x * PTail1.y;
if (b1 == 0) rezPoint.x = PHead1.x;//если перпендикулярна oy
else rezPoint.x = (-(b0 * c1 / b1) + c0) / ((b0 * a1 / b1) - a0);
if (a1 == 0) rezPoint.y = PHead1.y;//если перпендикулярна oy
else rezPoint.y = (-(c1 * a0 / a1) + c0) / ((a0 * b1 / a1) - b0);
//проверка на вхождение в отрезоки (с погрешностью 0.0000001 (зачем понадобилась погрешность?))
//по x
if ((rezPoint.x < Math.min(PHead0.x, PTail0.x) - 0.0000001) || (rezPoint.x > Math.max(PHead0.x, PTail0.x) + 0.0000001))
bRez = false;
if ((rezPoint.x < Math.min(PHead1.x, PTail1.x) - 0.0000001) || (rezPoint.x > Math.max(PHead1.x, PTail1.x) + 0.0000001))
bRez = false;
//по y
if ((rezPoint.y < Math.min(PHead0.y, PTail0.y) - 0.0000001) || (rezPoint.y > Math.max(PHead0.y, PTail0.y) + 0.0000001))
bRez = false;
if ((rezPoint.y < Math.min(PHead1.y, PTail1.y) - 0.0000001) || (rezPoint.y > Math.max(PHead1.y, PTail1.y) + 0.0000001))
bRez = false;
if (!bRez)
{
rezPoint.x = 0;
rezPoint.y = 0;
}
return rezPoint;
}
public static Point getCrossingLine2(Point PHead0,Point PTail0,Point PHead1,Point PTail1)
{
boolean bRez=true;
Point rezPoint = new Point();
rezPoint.x=0;
rezPoint.y=0;
double a0,b0,c0,a1,b1,c1;
a0=PTail0.y-PHead0.y;
b0=PHead0.x-PTail0.x;
c0=PTail0.x*PHead0.y-PHead0.x*PTail0.y;
a1=PTail1.y-PHead1.y;
b1=PHead1.x-PTail1.x;
c1=PTail1.x*PHead1.y-PHead1.x*PTail1.y;
if (b1==0) rezPoint.x=PHead1.x;//если перпендикулярна oy
else rezPoint.x=(-(b0*c1/b1)+c0)/((b0*a1/b1)-a0);
if (a1==0) rezPoint.y=PHead1.y;//если перпендикулярна ox
else rezPoint.y=(-(c1*a0/a1)+c0)/((a0*b1/a1)-b0);
//по x
if (rezPoint.x<Math.min(PHead0.x,PTail0.x)||rezPoint.x>Math.max(PHead0.x,PTail0.x))
bRez=false;
if (rezPoint.x<Math.min(PHead1.x,PTail1.x)||rezPoint.x>Math.max(PHead1.x,PTail1.x))
bRez=false;
//по y
if (rezPoint.y<Math.min(PHead0.y,PTail0.y)||rezPoint.y>Math.max(PHead0.y,PTail0.y))
bRez=false;
if (rezPoint.y<Math.min(PHead1.y,PTail1.y)||rezPoint.y>Math.max(PHead1.y,PTail1.y))
bRez=false;
if (!bRez)
{
rezPoint.x=0;
rezPoint.y=0;
}
return rezPoint;
}
//Так как в replaceAll много заморочек с регулярными выражениями
public static String replaceAll(String txt, String val, String rep) {
if(txt==null || val==null || rep==null) return txt;
return txt.replace(val,rep);
/*while(true)
{
String tmpstr=txt.replace(val, rep);
if(tmpstr.equals(txt))
{
txt=tmpstr;
break;
}else
{
txt=tmpstr;
}
}
return txt;*/
}
public static byte[] subArray(byte[] b, int offset, int length) {
byte[] sub = new byte[length];
for (int i = offset; i < offset + length; i++) {
try {
sub[i - offset] = b[i];
} catch (Exception e) {
}
}
return sub;
}
}

View File

@ -0,0 +1 @@
O:/projects/Workspace_Java/CCALM_main/src/main/java/tctable/Tools.java