diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..af94e9d --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +**/Objects +**/AutoBackups \ No newline at end of file diff --git a/DB1.bas b/DB1.bas new file mode 100644 index 0000000..f29a0b8 --- /dev/null +++ b/DB1.bas @@ -0,0 +1,320 @@ +B4J=true +Group=Default Group +ModulesStructureVersion=1 +Type=Class +Version=10 +@EndOfDesignText@ +'Handler class +Sub Class_Globals +' #if VERSION1 + Private const T_NULL = 0, T_STRING = 1, T_SHORT = 2, T_INT = 3, T_LONG = 4, T_FLOAT = 5 _ + ,T_DOUBLE = 6, T_BOOLEAN = 7, T_BLOB = 8 As Byte + Private bc As ByteConverter + Private cs As CompressedStreams +' #end if + Private DateTimeMethods As Map +End Sub + +Public Sub Initialize + DateTimeMethods = CreateMap(91: "getDate", 92: "getTime", 93: "getTimestamp") +End Sub + +Sub Handle(req As ServletRequest, resp As ServletResponse) + Log("***********************************************") + Dim start As Long = DateTime.Now + Dim q As String + Dim in As InputStream = req.InputStream + Dim method As String = req.GetParameter("method") + Dim con As SQL + Try + log(">>>>>> " & Main.rdcConnectorDB1.config) + con = Main.rdcConnectorDB1.GetConnection("DB1") + If method = "query2" Then + q = ExecuteQuery2(con, in, resp) + '#if VERSION1 + Else if method = "query" Then + in = cs.WrapInputStream(in, "gzip") + q = ExecuteQuery(con, in, resp) + Else if method = "batch" Then + in = cs.WrapInputStream(in, "gzip") + q = ExecuteBatch(con, in, resp) + '#end if + Else if method = "batch2" Then + q = ExecuteBatch2(con, in, resp) + Else + Log("Unknown method: " & method) + resp.SendError(500, "unknown method") + End If + Catch + Log(LastException) + resp.SendError(500, LastException.Message) + End Try + If con <> Null And con.IsInitialized Then con.Close + Log($"Command: ${q}, took: ${DateTime.Now - start}ms, client=${req.RemoteAddress}"$) +End Sub + +Private Sub ExecuteQuery2 (con As SQL, in As InputStream, resp As ServletResponse) As String + Dim ser As B4XSerializator + Dim m As Map = ser.ConvertBytesToObject(Bit.InputStreamToBytes(in)) + Dim cmd As DBCommand = m.Get("command") + Dim limit As Int = m.Get("limit") + Dim rs As ResultSet = con.ExecQuery2(Main.rdcConnectorDB1.GetCommand(cmd.Name), cmd.Parameters) + If limit <= 0 Then limit = 0x7fffffff 'max int + Dim jrs As JavaObject = rs + Dim rsmd As JavaObject = jrs.RunMethod("getMetaData", Null) + Dim cols As Int = rs.ColumnCount + Dim res As DBResult + res.Initialize + res.columns.Initialize + res.Tag = Null 'without this the Tag properly will not be serializable. + For i = 0 To cols - 1 + res.columns.Put(rs.GetColumnName(i), i) + Next + res.Rows.Initialize + Do While rs.NextRow And limit > 0 + Dim row(cols) As Object + For i = 0 To cols - 1 + Dim ct As Int = rsmd.RunMethod("getColumnType", Array(i + 1)) + 'check whether it is a blob field + If ct = -2 Or ct = 2004 Or ct = -3 Or ct = -4 Then + row(i) = rs.GetBlob2(i) + Else If ct = 2005 Then + row(i) = rs.GetString2(i) + Else if ct = 2 Or ct = 3 Then + row(i) = rs.GetDouble2(i) + Else If DateTimeMethods.ContainsKey(ct) Then + Dim SQLTime As JavaObject = jrs.RunMethodJO(DateTimeMethods.Get(ct), Array(i + 1)) + If SQLTime.IsInitialized Then + row(i) = SQLTime.RunMethod("getTime", Null) + Else + row(i) = Null + End If + Else + row(i) = jrs.RunMethod("getObject", Array(i + 1)) + End If + Next + res.Rows.Add(row) + Loop + rs.Close + Dim data() As Byte = ser.ConvertObjectToBytes(res) + resp.OutputStream.WriteBytes(data, 0, data.Length) + Return "query: " & cmd.Name +End Sub + +Private Sub ExecuteBatch2(con As SQL, in As InputStream, resp As ServletResponse) As String + Dim ser As B4XSerializator + Dim m As Map = ser.ConvertBytesToObject(Bit.InputStreamToBytes(in)) + Dim commands As List = m.Get("commands") + Dim res As DBResult + res.Initialize + res.columns = CreateMap("AffectedRows (N/A)": 0) + res.Rows.Initialize + res.Tag = Null + Try + con.BeginTransaction + For Each cmd As DBCommand In commands + con.ExecNonQuery2(Main.rdcConnectorDB1.GetCommand(cmd.Name), _ + cmd.Parameters) + Next + res.Rows.Add(Array As Object(0)) + con.TransactionSuccessful + Catch + con.Rollback + Log(LastException) + resp.SendError(500, LastException.Message) + End Try + Dim data() As Byte = ser.ConvertObjectToBytes(res) + resp.OutputStream.WriteBytes(data, 0, data.Length) + Return $"batch (size=${commands.Size})"$ +End Sub + +'#if VERSION1 + +Private Sub ExecuteBatch(con As SQL, in As InputStream, resp As ServletResponse) As String + Dim clientVersion As Float = ReadObject(in) 'ignore + Dim numberOfStatements As Int = ReadInt(in) + Dim res(numberOfStatements) As Int + Try + con.BeginTransaction + For i = 0 To numberOfStatements - 1 + Dim queryName As String = ReadObject(in) + Dim params As List = ReadList(in) + con.ExecNonQuery2(Main.rdcConnectorDB1.GetCommand(queryName), _ + params) + Next + con.TransactionSuccessful + + Dim out As OutputStream = cs.WrapOutputStream(resp.OutputStream, "gzip") + WriteObject(Main.VERSION, out) + WriteObject("batch", out) + WriteInt(res.Length, out) + For Each r As Int In res + WriteInt(r, out) + Next + out.Close + Catch + con.Rollback + Log(LastException) + resp.SendError(500, LastException.Message) + End Try + Return $"batch (size=${numberOfStatements})"$ +End Sub + +Private Sub ExecuteQuery (con As SQL, in As InputStream, resp As ServletResponse) As String +' Log("==== ExecuteQuery ==== ") + Dim clientVersion As Float = ReadObject(in) 'ignore + Dim queryName As String = ReadObject(in) + Dim limit As Int = ReadInt(in) + Dim params As List = ReadList(in) +' Log("EL QUERY: |" & queryName & "|") + Private theSql As String = Main.rdcConnectorDB1.GetCommand(queryName) +' Log(theSql) +' Log(params) +' Log(params.Size) + Dim rs As ResultSet = con.ExecQuery2(theSql, params) + If limit <= 0 Then limit = 0x7fffffff 'max int + Dim jrs As JavaObject = rs + Dim rsmd As JavaObject = jrs.RunMethod("getMetaData", Null) + Dim cols As Int = rs.ColumnCount + Dim out As OutputStream = cs.WrapOutputStream(resp.OutputStream, "gzip") + WriteObject(Main.VERSION, out) + WriteObject("query", out) + WriteInt(rs.ColumnCount, out) +' Log($"cols: ${cols}"$) + For i = 0 To cols - 1 + WriteObject(rs.GetColumnName(i), out) + Next + + Do While rs.NextRow And limit > 0 + WriteByte(1, out) + For i = 0 To cols - 1 + Dim ct As Int = rsmd.RunMethod("getColumnType", Array(i + 1)) + 'check whether it is a blob field + If ct = -2 Or ct = 2004 Or ct = -3 Or ct = -4 Then + WriteObject(rs.GetBlob2(i), out) + Else + WriteObject(jrs.RunMethod("getObject", Array(i + 1)), out) + End If + Next + Loop + WriteByte(0, out) + out.Close + rs.Close + + Return "query: " & queryName +End Sub + +Private Sub WriteByte(value As Byte, out As OutputStream) + out.WriteBytes(Array As Byte(value), 0, 1) +End Sub + + + +Private Sub WriteObject(o As Object, out As OutputStream) + Dim data() As Byte + If o = Null Then + out.WriteBytes(Array As Byte(T_NULL), 0, 1) + Else If o Is Short Then + out.WriteBytes(Array As Byte(T_SHORT), 0, 1) + data = bc.ShortsToBytes(Array As Short(o)) + Else If o Is Int Then + out.WriteBytes(Array As Byte(T_INT), 0, 1) + data = bc.IntsToBytes(Array As Int(o)) + Else If o Is Float Then + out.WriteBytes(Array As Byte(T_FLOAT), 0, 1) + data = bc.FloatsToBytes(Array As Float(o)) + Else If o Is Double Then + out.WriteBytes(Array As Byte(T_DOUBLE), 0, 1) + data = bc.DoublesToBytes(Array As Double(o)) + Else If o Is Long Then + out.WriteBytes(Array As Byte(T_LONG), 0, 1) + data = bc.LongsToBytes(Array As Long(o)) + Else If o Is Boolean Then + out.WriteBytes(Array As Byte(T_BOOLEAN), 0, 1) + Dim b As Boolean = o + Dim data(1) As Byte + If b Then data(0) = 1 Else data(0) = 0 + Else If GetType(o) = "[B" Then + data = o + out.WriteBytes(Array As Byte(T_BLOB), 0, 1) + WriteInt(data.Length, out) + Else 'If o Is String Then (treat all other values as string) + out.WriteBytes(Array As Byte(T_STRING), 0, 1) + data = bc.StringToBytes(o, "UTF8") + WriteInt(data.Length, out) + End If + If data.Length > 0 Then out.WriteBytes(data, 0, data.Length) +End Sub + +Private Sub ReadObject(In As InputStream) As Object + Dim data(1) As Byte + In.ReadBytes(data, 0, 1) + Select data(0) + Case T_NULL + Return Null + Case T_SHORT + Dim data(2) As Byte + Return bc.ShortsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_INT + Dim data(4) As Byte + Return bc.IntsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_LONG + Dim data(8) As Byte + Return bc.LongsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_FLOAT + Dim data(4) As Byte + Return bc.FloatsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_DOUBLE + Dim data(8) As Byte + Return bc.DoublesFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_BOOLEAN + Dim b As Byte = ReadByte(In) + Return b = 1 + Case T_BLOB + Dim len As Int = ReadInt(In) + Dim data(len) As Byte + Return ReadBytesFully(In, data, data.Length) + Case Else + Dim len As Int = ReadInt(In) + Dim data(len) As Byte + ReadBytesFully(In, data, data.Length) + Return BytesToString(data, 0, data.Length, "UTF8") + End Select +End Sub + +Private Sub ReadBytesFully(In As InputStream, Data() As Byte, Len As Int) As Byte() + Dim count = 0, Read As Int + Do While count < Len And Read > -1 + Read = In.ReadBytes(Data, count, Len - count) + count = count + Read + Loop + Return Data +End Sub + +Private Sub WriteInt(i As Int, out As OutputStream) + Dim data() As Byte + data = bc.IntsToBytes(Array As Int(i)) + out.WriteBytes(data, 0, data.Length) +End Sub + +Private Sub ReadInt(In As InputStream) As Int + Dim data(4) As Byte + Return bc.IntsFromBytes(ReadBytesFully(In, data, data.Length))(0) +End Sub + +Private Sub ReadByte(In As InputStream) As Byte + Dim data(1) As Byte + In.ReadBytes(data, 0, 1) + Return data(0) +End Sub + +Private Sub ReadList(in As InputStream) As List + Dim len As Int = ReadInt(in) + Dim l1 As List + l1.Initialize + For i = 0 To len - 1 + l1.Add(ReadObject(in)) + Next + Return l1 +End Sub +'#end If \ No newline at end of file diff --git a/DB1Handler.bas b/DB1Handler.bas new file mode 100644 index 0000000..40d2772 --- /dev/null +++ b/DB1Handler.bas @@ -0,0 +1,320 @@ +B4J=true +Group=Default Group +ModulesStructureVersion=1 +Type=Class +Version=4.19 +@EndOfDesignText@ +'Handler class +Sub Class_Globals +' #if VERSION1 + Private const T_NULL = 0, T_STRING = 1, T_SHORT = 2, T_INT = 3, T_LONG = 4, T_FLOAT = 5 _ + ,T_DOUBLE = 6, T_BOOLEAN = 7, T_BLOB = 8 As Byte + Private bc As ByteConverter + Private cs As CompressedStreams +' #end if + Private DateTimeMethods As Map + Private Connector As RDCConnector +End Sub + +Public Sub Initialize + DateTimeMethods = CreateMap(91: "getDate", 92: "getTime", 93: "getTimestamp") +End Sub + +Sub Handle(req As ServletRequest, resp As ServletResponse) + Log("********************* DB1 ********************") + Dim start As Long = DateTime.Now + Dim q As String + Dim in As InputStream = req.InputStream + Dim method As String = req.GetParameter("method") + Connector = Main.Connectors.Get("DB1") + Dim con As SQL + Try + con = Connector.GetConnection("DB1") +' con = Main.rdcConnectorDB1.GetConnection("") + If method = "query2" Then + q = ExecuteQuery2("DB1", con, in, resp) + '#if VERSION1 + Else if method = "query" Then + in = cs.WrapInputStream(in, "gzip") + q = ExecuteQuery("DB1", con, in, resp) + Else if method = "batch" Then + in = cs.WrapInputStream(in, "gzip") + q = ExecuteBatch("DB1", con, in, resp) + '#end if + Else if method = "batch2" Then + q = ExecuteBatch2("DB1", con, in, resp) + Else + Log("Unknown method: " & method) + resp.SendError(500, "unknown method") + End If +Catch +Log(LastException) +resp.SendError(500, LastException.Message) +End Try + If con <> Null And con.IsInitialized Then con.Close + Log($"Command: ${q}, took: ${DateTime.Now - start}ms, client=${req.RemoteAddress}"$) +End Sub + +Private Sub ExecuteQuery2 (DB As String, con As SQL, in As InputStream, resp As ServletResponse) As String + Dim ser As B4XSerializator + Dim m As Map = ser.ConvertBytesToObject(Bit.InputStreamToBytes(in)) + Dim cmd As DBCommand = m.Get("command") + Dim limit As Int = m.Get("limit") + Dim rs As ResultSet = con.ExecQuery2(Connector.GetCommand(DB, cmd.Name), cmd.Parameters) + If limit <= 0 Then limit = 0x7fffffff 'max int + Dim jrs As JavaObject = rs + Dim rsmd As JavaObject = jrs.RunMethod("getMetaData", Null) + Dim cols As Int = rs.ColumnCount + Dim res As DBResult + res.Initialize + res.columns.Initialize + res.Tag = Null 'without this the Tag properly will not be serializable. + For i = 0 To cols - 1 + res.columns.Put(rs.GetColumnName(i), i) + Next + res.Rows.Initialize + Do While rs.NextRow And limit > 0 + Dim row(cols) As Object + For i = 0 To cols - 1 + Dim ct As Int = rsmd.RunMethod("getColumnType", Array(i + 1)) + 'check whether it is a blob field + If ct = -2 Or ct = 2004 Or ct = -3 Or ct = -4 Then + row(i) = rs.GetBlob2(i) + Else If ct = 2005 Then + row(i) = rs.GetString2(i) + Else if ct = 2 Or ct = 3 Then + row(i) = rs.GetDouble2(i) + Else If DateTimeMethods.ContainsKey(ct) Then + Dim SQLTime As JavaObject = jrs.RunMethodJO(DateTimeMethods.Get(ct), Array(i + 1)) + If SQLTime.IsInitialized Then + row(i) = SQLTime.RunMethod("getTime", Null) + Else + row(i) = Null + End If + Else + row(i) = jrs.RunMethod("getObject", Array(i + 1)) + End If + Next + res.Rows.Add(row) + Loop + rs.Close + Dim data() As Byte = ser.ConvertObjectToBytes(res) + resp.OutputStream.WriteBytes(data, 0, data.Length) + Return "query: " & cmd.Name +End Sub + +Private Sub ExecuteBatch2(DB As String, con As SQL, in As InputStream, resp As ServletResponse) As String + Dim ser As B4XSerializator + Dim m As Map = ser.ConvertBytesToObject(Bit.InputStreamToBytes(in)) + Dim commands As List = m.Get("commands") + Dim res As DBResult + res.Initialize + res.columns = CreateMap("AffectedRows (N/A)": 0) + res.Rows.Initialize + res.Tag = Null + Try + con.BeginTransaction + For Each cmd As DBCommand In commands + con.ExecNonQuery2(Connector.GetCommand(DB, cmd.Name), _ + cmd.Parameters) + Next + res.Rows.Add(Array As Object(0)) + con.TransactionSuccessful + Catch + con.Rollback + Log(LastException) + resp.SendError(500, LastException.Message) + End Try + Dim data() As Byte = ser.ConvertObjectToBytes(res) + resp.OutputStream.WriteBytes(data, 0, data.Length) + Return $"batch (size=${commands.Size})"$ +End Sub + +'#if VERSION1 + +Private Sub ExecuteBatch(DB As String, con As SQL, in As InputStream, resp As ServletResponse) As String + Dim clientVersion As Float = ReadObject(in) 'ignore + Dim numberOfStatements As Int = ReadInt(in) + Dim res(numberOfStatements) As Int + Try + con.BeginTransaction + For i = 0 To numberOfStatements - 1 + Dim queryName As String = ReadObject(in) + Dim params As List = ReadList(in) + con.ExecNonQuery2(Connector.GetCommand(DB, queryName), _ + params) + Next + con.TransactionSuccessful + + Dim out As OutputStream = cs.WrapOutputStream(resp.OutputStream, "gzip") + WriteObject(Main.VERSION, out) + WriteObject("batch", out) + WriteInt(res.Length, out) + For Each r As Int In res + WriteInt(r, out) + Next + out.Close +Catch +con.Rollback +Log(LastException) +resp.SendError(500, LastException.Message) +End Try + Return $"batch (size=${numberOfStatements})"$ +End Sub + +Private Sub ExecuteQuery(DB As String, con As SQL, in As InputStream, resp As ServletResponse) As String +' Log("==== ExecuteQuery ==== ") + Dim clientVersion As Float = ReadObject(in) 'ignore + Dim queryName As String = ReadObject(in) + Dim limit As Int = ReadInt(in) + Dim params As List = ReadList(in) +' Log("EL QUERY: |" & queryName & "|") + Private theSql As String = Connector.GetCommand(DB, queryName) +' Log(theSql) +' Log(params) +' Log(params.Size) + Dim rs As ResultSet = con.ExecQuery2(theSql, params) + If limit <= 0 Then limit = 0x7fffffff 'max int + Dim jrs As JavaObject = rs + Dim rsmd As JavaObject = jrs.RunMethod("getMetaData", Null) + Dim cols As Int = rs.ColumnCount + Dim out As OutputStream = cs.WrapOutputStream(resp.OutputStream, "gzip") + WriteObject(Main.VERSION, out) + WriteObject("query", out) + WriteInt(rs.ColumnCount, out) +' Log($"cols: ${cols}"$) + For i = 0 To cols - 1 + WriteObject(rs.GetColumnName(i), out) + Next + + Do While rs.NextRow And limit > 0 + WriteByte(1, out) + For i = 0 To cols - 1 + Dim ct As Int = rsmd.RunMethod("getColumnType", Array(i + 1)) + 'check whether it is a blob field + If ct = -2 Or ct = 2004 Or ct = -3 Or ct = -4 Then + WriteObject(rs.GetBlob2(i), out) + Else + WriteObject(jrs.RunMethod("getObject", Array(i + 1)), out) + End If + Next + Loop + WriteByte(0, out) + out.Close + rs.Close + + Return "query: " & queryName +End Sub + +Private Sub WriteByte(value As Byte, out As OutputStream) + out.WriteBytes(Array As Byte(value), 0, 1) +End Sub + +Private Sub WriteObject(o As Object, out As OutputStream) + Dim data() As Byte + If o = Null Then + out.WriteBytes(Array As Byte(T_NULL), 0, 1) + Else If o Is Short Then + out.WriteBytes(Array As Byte(T_SHORT), 0, 1) + data = bc.ShortsToBytes(Array As Short(o)) + Else If o Is Int Then + out.WriteBytes(Array As Byte(T_INT), 0, 1) + data = bc.IntsToBytes(Array As Int(o)) + Else If o Is Float Then + out.WriteBytes(Array As Byte(T_FLOAT), 0, 1) + data = bc.FloatsToBytes(Array As Float(o)) + Else If o Is Double Then + out.WriteBytes(Array As Byte(T_DOUBLE), 0, 1) + data = bc.DoublesToBytes(Array As Double(o)) + Else If o Is Long Then + out.WriteBytes(Array As Byte(T_LONG), 0, 1) + data = bc.LongsToBytes(Array As Long(o)) + Else If o Is Boolean Then + out.WriteBytes(Array As Byte(T_BOOLEAN), 0, 1) + Dim b As Boolean = o + Dim data(1) As Byte + If b Then data(0) = 1 Else data(0) = 0 + Else If GetType(o) = "[B" Then + data = o + out.WriteBytes(Array As Byte(T_BLOB), 0, 1) + WriteInt(data.Length, out) + Else 'If o Is String Then (treat all other values as string) + out.WriteBytes(Array As Byte(T_STRING), 0, 1) + data = bc.StringToBytes(o, "UTF8") + WriteInt(data.Length, out) + End If + If data.Length > 0 Then out.WriteBytes(data, 0, data.Length) +End Sub + +Private Sub ReadObject(In As InputStream) As Object + Dim data(1) As Byte + In.ReadBytes(data, 0, 1) + Select data(0) + Case T_NULL + Return Null + Case T_SHORT + Dim data(2) As Byte + Return bc.ShortsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_INT + Dim data(4) As Byte + Return bc.IntsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_LONG + Dim data(8) As Byte + Return bc.LongsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_FLOAT + Dim data(4) As Byte + Return bc.FloatsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_DOUBLE + Dim data(8) As Byte + Return bc.DoublesFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_BOOLEAN + Dim b As Byte = ReadByte(In) + Return b = 1 + Case T_BLOB + Dim len As Int = ReadInt(In) + Dim data(len) As Byte + Return ReadBytesFully(In, data, data.Length) + Case Else + Dim len As Int = ReadInt(In) + Dim data(len) As Byte + ReadBytesFully(In, data, data.Length) + Return BytesToString(data, 0, data.Length, "UTF8") + End Select +End Sub + +Private Sub ReadBytesFully(In As InputStream, Data() As Byte, Len As Int) As Byte() + Dim count = 0, Read As Int + Do While count < Len And Read > -1 + Read = In.ReadBytes(Data, count, Len - count) + count = count + Read + Loop + Return Data +End Sub + +Private Sub WriteInt(i As Int, out As OutputStream) + Dim data() As Byte + data = bc.IntsToBytes(Array As Int(i)) + out.WriteBytes(data, 0, data.Length) +End Sub + +Private Sub ReadInt(In As InputStream) As Int + Dim data(4) As Byte + Return bc.IntsFromBytes(ReadBytesFully(In, data, data.Length))(0) +End Sub + +Private Sub ReadByte(In As InputStream) As Byte + Dim data(1) As Byte + In.ReadBytes(data, 0, 1) + Return data(0) +End Sub + +Private Sub ReadList(in As InputStream) As List + Dim len As Int = ReadInt(in) + Dim l1 As List + l1.Initialize + For i = 0 To len - 1 + l1.Add(ReadObject(in)) + Next + Return l1 +End Sub +'#end If \ No newline at end of file diff --git a/DB2Handler.bas b/DB2Handler.bas new file mode 100644 index 0000000..6b0d5c4 --- /dev/null +++ b/DB2Handler.bas @@ -0,0 +1,320 @@ +B4J=true +Group=Default Group +ModulesStructureVersion=1 +Type=Class +Version=10 +@EndOfDesignText@ +'Handler class +Sub Class_Globals +' #if VERSION1 + Private const T_NULL = 0, T_STRING = 1, T_SHORT = 2, T_INT = 3, T_LONG = 4, T_FLOAT = 5 _ + ,T_DOUBLE = 6, T_BOOLEAN = 7, T_BLOB = 8 As Byte + Private bc As ByteConverter + Private cs As CompressedStreams +' #end if + Private DateTimeMethods As Map + Private Connector As RDCConnector +End Sub + +Public Sub Initialize + DateTimeMethods = CreateMap(91: "getDate", 92: "getTime", 93: "getTimestamp") +End Sub + +Sub Handle(req As ServletRequest, resp As ServletResponse) + Log("********************* DB2 ********************") + Dim start As Long = DateTime.Now + Dim q As String + Dim in As InputStream = req.InputStream + Dim method As String = req.GetParameter("method") + Connector = Main.Connectors.Get("DB2") + Dim con As SQL + Try + con = Connector.GetConnection("DB2") +' con = Main.rdcConnectorDB2.GetConnection("DB2") + If method = "query2" Then + q = ExecuteQuery2("DB2", con, in, resp) + '#if VERSION1 + Else if method = "query" Then + in = cs.WrapInputStream(in, "gzip") + q = ExecuteQuery("DB2", con, in, resp) + Else if method = "batch" Then + in = cs.WrapInputStream(in, "gzip") + q = ExecuteBatch("DB2", con, in, resp) + '#end if + Else if method = "batch2" Then + q = ExecuteBatch2("DB2", con, in, resp) + Else + Log("Unknown method: " & method) + resp.SendError(500, "unknown method") + End If + Catch + Log(LastException) + resp.SendError(500, LastException.Message) + End Try + If con <> Null And con.IsInitialized Then con.Close + Log($"Command: ${q}, took: ${DateTime.Now - start}ms, client=${req.RemoteAddress}"$) +End Sub + +Private Sub ExecuteQuery2 (DB As String, con As SQL, in As InputStream, resp As ServletResponse) As String + Dim ser As B4XSerializator + Dim m As Map = ser.ConvertBytesToObject(Bit.InputStreamToBytes(in)) + Dim cmd As DBCommand = m.Get("command") + Dim limit As Int = m.Get("limit") + Dim rs As ResultSet = con.ExecQuery2(Connector.GetCommand(DB, cmd.Name), cmd.Parameters) + If limit <= 0 Then limit = 0x7fffffff 'max int + Dim jrs As JavaObject = rs + Dim rsmd As JavaObject = jrs.RunMethod("getMetaData", Null) + Dim cols As Int = rs.ColumnCount + Dim res As DBResult + res.Initialize + res.columns.Initialize + res.Tag = Null 'without this the Tag properly will not be serializable. + For i = 0 To cols - 1 + res.columns.Put(rs.GetColumnName(i), i) + Next + res.Rows.Initialize + Do While rs.NextRow And limit > 0 + Dim row(cols) As Object + For i = 0 To cols - 1 + Dim ct As Int = rsmd.RunMethod("getColumnType", Array(i + 1)) + 'check whether it is a blob field + If ct = -2 Or ct = 2004 Or ct = -3 Or ct = -4 Then + row(i) = rs.GetBlob2(i) + Else If ct = 2005 Then + row(i) = rs.GetString2(i) + Else if ct = 2 Or ct = 3 Then + row(i) = rs.GetDouble2(i) + Else If DateTimeMethods.ContainsKey(ct) Then + Dim SQLTime As JavaObject = jrs.RunMethodJO(DateTimeMethods.Get(ct), Array(i + 1)) + If SQLTime.IsInitialized Then + row(i) = SQLTime.RunMethod("getTime", Null) + Else + row(i) = Null + End If + Else + row(i) = jrs.RunMethod("getObject", Array(i + 1)) + End If + Next + res.Rows.Add(row) + Loop + rs.Close + Dim data() As Byte = ser.ConvertObjectToBytes(res) + resp.OutputStream.WriteBytes(data, 0, data.Length) + Return "query: " & cmd.Name +End Sub + +Private Sub ExecuteBatch2(DB As String, con As SQL, in As InputStream, resp As ServletResponse) As String + Dim ser As B4XSerializator + Dim m As Map = ser.ConvertBytesToObject(Bit.InputStreamToBytes(in)) + Dim commands As List = m.Get("commands") + Dim res As DBResult + res.Initialize + res.columns = CreateMap("AffectedRows (N/A)": 0) + res.Rows.Initialize + res.Tag = Null + Try + con.BeginTransaction + For Each cmd As DBCommand In commands + con.ExecNonQuery2(Connector.GetCommand(DB, cmd.Name), _ + cmd.Parameters) + Next + res.Rows.Add(Array As Object(0)) + con.TransactionSuccessful + Catch + con.Rollback + Log(LastException) + resp.SendError(500, LastException.Message) + End Try + Dim data() As Byte = ser.ConvertObjectToBytes(res) + resp.OutputStream.WriteBytes(data, 0, data.Length) + Return $"batch (size=${commands.Size})"$ +End Sub + +'#if VERSION1 + +Private Sub ExecuteBatch(DB As String, con As SQL, in As InputStream, resp As ServletResponse) As String + Dim clientVersion As Float = ReadObject(in) 'ignore + Dim numberOfStatements As Int = ReadInt(in) + Dim res(numberOfStatements) As Int + Try + con.BeginTransaction + For i = 0 To numberOfStatements - 1 + Dim queryName As String = ReadObject(in) + Dim params As List = ReadList(in) + con.ExecNonQuery2(Connector.GetCommand(DB, queryName), _ + params) + Next + con.TransactionSuccessful + + Dim out As OutputStream = cs.WrapOutputStream(resp.OutputStream, "gzip") + WriteObject(Main.VERSION, out) + WriteObject("batch", out) + WriteInt(res.Length, out) + For Each r As Int In res + WriteInt(r, out) + Next + out.Close + Catch + con.Rollback + Log(LastException) + resp.SendError(500, LastException.Message) + End Try + Return $"batch (size=${numberOfStatements})"$ +End Sub + +Private Sub ExecuteQuery (DB As String, con As SQL, in As InputStream, resp As ServletResponse) As String +' Log("==== ExecuteQuery ==== ") + Dim clientVersion As Float = ReadObject(in) 'ignore + Dim queryName As String = ReadObject(in) + Dim limit As Int = ReadInt(in) + Dim params As List = ReadList(in) +' Log("EL QUERY: |" & queryName & "|") + Private theSql As String = Connector.GetCommand(DB, queryName) +' Log(theSql) +' Log(params) +' Log(params.Size) + Dim rs As ResultSet = con.ExecQuery2(theSql, params) + If limit <= 0 Then limit = 0x7fffffff 'max int + Dim jrs As JavaObject = rs + Dim rsmd As JavaObject = jrs.RunMethod("getMetaData", Null) + Dim cols As Int = rs.ColumnCount + Dim out As OutputStream = cs.WrapOutputStream(resp.OutputStream, "gzip") + WriteObject(Main.VERSION, out) + WriteObject("query", out) + WriteInt(rs.ColumnCount, out) +' Log($"cols: ${cols}"$) + For i = 0 To cols - 1 + WriteObject(rs.GetColumnName(i), out) + Next + + Do While rs.NextRow And limit > 0 + WriteByte(1, out) + For i = 0 To cols - 1 + Dim ct As Int = rsmd.RunMethod("getColumnType", Array(i + 1)) + 'check whether it is a blob field + If ct = -2 Or ct = 2004 Or ct = -3 Or ct = -4 Then + WriteObject(rs.GetBlob2(i), out) + Else + WriteObject(jrs.RunMethod("getObject", Array(i + 1)), out) + End If + Next + Loop + WriteByte(0, out) + out.Close + rs.Close + + Return "query: " & queryName +End Sub + +Private Sub WriteByte(value As Byte, out As OutputStream) + out.WriteBytes(Array As Byte(value), 0, 1) +End Sub + +Private Sub WriteObject(o As Object, out As OutputStream) + Dim data() As Byte + If o = Null Then + out.WriteBytes(Array As Byte(T_NULL), 0, 1) + Else If o Is Short Then + out.WriteBytes(Array As Byte(T_SHORT), 0, 1) + data = bc.ShortsToBytes(Array As Short(o)) + Else If o Is Int Then + out.WriteBytes(Array As Byte(T_INT), 0, 1) + data = bc.IntsToBytes(Array As Int(o)) + Else If o Is Float Then + out.WriteBytes(Array As Byte(T_FLOAT), 0, 1) + data = bc.FloatsToBytes(Array As Float(o)) + Else If o Is Double Then + out.WriteBytes(Array As Byte(T_DOUBLE), 0, 1) + data = bc.DoublesToBytes(Array As Double(o)) + Else If o Is Long Then + out.WriteBytes(Array As Byte(T_LONG), 0, 1) + data = bc.LongsToBytes(Array As Long(o)) + Else If o Is Boolean Then + out.WriteBytes(Array As Byte(T_BOOLEAN), 0, 1) + Dim b As Boolean = o + Dim data(1) As Byte + If b Then data(0) = 1 Else data(0) = 0 + Else If GetType(o) = "[B" Then + data = o + out.WriteBytes(Array As Byte(T_BLOB), 0, 1) + WriteInt(data.Length, out) + Else 'If o Is String Then (treat all other values as string) + out.WriteBytes(Array As Byte(T_STRING), 0, 1) + data = bc.StringToBytes(o, "UTF8") + WriteInt(data.Length, out) + End If + If data.Length > 0 Then out.WriteBytes(data, 0, data.Length) +End Sub + +Private Sub ReadObject(In As InputStream) As Object + Dim data(1) As Byte + In.ReadBytes(data, 0, 1) + Select data(0) + Case T_NULL + Return Null + Case T_SHORT + Dim data(2) As Byte + Return bc.ShortsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_INT + Dim data(4) As Byte + Return bc.IntsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_LONG + Dim data(8) As Byte + Return bc.LongsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_FLOAT + Dim data(4) As Byte + Return bc.FloatsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_DOUBLE + Dim data(8) As Byte + Return bc.DoublesFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_BOOLEAN + Dim b As Byte = ReadByte(In) + Return b = 1 + Case T_BLOB + Dim len As Int = ReadInt(In) + Dim data(len) As Byte + Return ReadBytesFully(In, data, data.Length) + Case Else + Dim len As Int = ReadInt(In) + Dim data(len) As Byte + ReadBytesFully(In, data, data.Length) + Return BytesToString(data, 0, data.Length, "UTF8") + End Select +End Sub + +Private Sub ReadBytesFully(In As InputStream, Data() As Byte, Len As Int) As Byte() + Dim count = 0, Read As Int + Do While count < Len And Read > -1 + Read = In.ReadBytes(Data, count, Len - count) + count = count + Read + Loop + Return Data +End Sub + +Private Sub WriteInt(i As Int, out As OutputStream) + Dim data() As Byte + data = bc.IntsToBytes(Array As Int(i)) + out.WriteBytes(data, 0, data.Length) +End Sub + +Private Sub ReadInt(In As InputStream) As Int + Dim data(4) As Byte + Return bc.IntsFromBytes(ReadBytesFully(In, data, data.Length))(0) +End Sub + +Private Sub ReadByte(In As InputStream) As Byte + Dim data(1) As Byte + In.ReadBytes(data, 0, 1) + Return data(0) +End Sub + +Private Sub ReadList(in As InputStream) As List + Dim len As Int = ReadInt(in) + Dim l1 As List + l1.Initialize + For i = 0 To len - 1 + l1.Add(ReadObject(in)) + Next + Return l1 +End Sub +'#end If \ No newline at end of file diff --git a/DB3Handler.bas b/DB3Handler.bas new file mode 100644 index 0000000..b837ad3 --- /dev/null +++ b/DB3Handler.bas @@ -0,0 +1,320 @@ +B4J=true +Group=Default Group +ModulesStructureVersion=1 +Type=Class +Version=10 +@EndOfDesignText@ +'Handler class +Sub Class_Globals +' #if VERSION1 + Private const T_NULL = 0, T_STRING = 1, T_SHORT = 2, T_INT = 3, T_LONG = 4, T_FLOAT = 5 _ + ,T_DOUBLE = 6, T_BOOLEAN = 7, T_BLOB = 8 As Byte + Private bc As ByteConverter + Private cs As CompressedStreams +' #end if + Private DateTimeMethods As Map + Private Connector As RDCConnector +End Sub + +Public Sub Initialize + DateTimeMethods = CreateMap(91: "getDate", 92: "getTime", 93: "getTimestamp") +End Sub + +Sub Handle(req As ServletRequest, resp As ServletResponse) + Log("********************* DB3 ********************") + Dim start As Long = DateTime.Now + Dim q As String + Dim in As InputStream = req.InputStream + Dim method As String = req.GetParameter("method") + Connector = Main.Connectors.Get("DB3") + Dim con As SQL + Try +' con = Main.rdcConnectorDB3.GetConnection("DB3") + con = Connector.GetConnection("DB3") + If method = "query2" Then + q = ExecuteQuery2("DB3", con, in, resp) + '#if VERSION1 + Else if method = "query" Then + in = cs.WrapInputStream(in, "gzip") + q = ExecuteQuery("DB3", con, in, resp) + Else if method = "batch" Then + in = cs.WrapInputStream(in, "gzip") + q = ExecuteBatch("DB3", con, in, resp) + '#end if + Else if method = "batch2" Then + q = ExecuteBatch2("DB3", con, in, resp) + Else + Log("Unknown method: " & method) + resp.SendError(500, "unknown method") + End If + Catch + Log(LastException) + resp.SendError(500, LastException.Message) + End Try + If con <> Null And con.IsInitialized Then con.Close + Log($"Command: ${q}, took: ${DateTime.Now - start}ms, client=${req.RemoteAddress}"$) +End Sub + +Private Sub ExecuteQuery2 (DB As String, con As SQL, in As InputStream, resp As ServletResponse) As String + Dim ser As B4XSerializator + Dim m As Map = ser.ConvertBytesToObject(Bit.InputStreamToBytes(in)) + Dim cmd As DBCommand = m.Get("command") + Dim limit As Int = m.Get("limit") + Dim rs As ResultSet = con.ExecQuery2(Connector.GetCommand(DB, cmd.Name), cmd.Parameters) + If limit <= 0 Then limit = 0x7fffffff 'max int + Dim jrs As JavaObject = rs + Dim rsmd As JavaObject = jrs.RunMethod("getMetaData", Null) + Dim cols As Int = rs.ColumnCount + Dim res As DBResult + res.Initialize + res.columns.Initialize + res.Tag = Null 'without this the Tag properly will not be serializable. + For i = 0 To cols - 1 + res.columns.Put(rs.GetColumnName(i), i) + Next + res.Rows.Initialize + Do While rs.NextRow And limit > 0 + Dim row(cols) As Object + For i = 0 To cols - 1 + Dim ct As Int = rsmd.RunMethod("getColumnType", Array(i + 1)) + 'check whether it is a blob field + If ct = -2 Or ct = 2004 Or ct = -3 Or ct = -4 Then + row(i) = rs.GetBlob2(i) + Else If ct = 2005 Then + row(i) = rs.GetString2(i) + Else if ct = 2 Or ct = 3 Then + row(i) = rs.GetDouble2(i) + Else If DateTimeMethods.ContainsKey(ct) Then + Dim SQLTime As JavaObject = jrs.RunMethodJO(DateTimeMethods.Get(ct), Array(i + 1)) + If SQLTime.IsInitialized Then + row(i) = SQLTime.RunMethod("getTime", Null) + Else + row(i) = Null + End If + Else + row(i) = jrs.RunMethod("getObject", Array(i + 1)) + End If + Next + res.Rows.Add(row) + Loop + rs.Close + Dim data() As Byte = ser.ConvertObjectToBytes(res) + resp.OutputStream.WriteBytes(data, 0, data.Length) + Return "query: " & cmd.Name +End Sub + +Private Sub ExecuteBatch2(DB As String, con As SQL, in As InputStream, resp As ServletResponse) As String + Dim ser As B4XSerializator + Dim m As Map = ser.ConvertBytesToObject(Bit.InputStreamToBytes(in)) + Dim commands As List = m.Get("commands") + Dim res As DBResult + res.Initialize + res.columns = CreateMap("AffectedRows (N/A)": 0) + res.Rows.Initialize + res.Tag = Null + Try + con.BeginTransaction + For Each cmd As DBCommand In commands + con.ExecNonQuery2(Connector.GetCommand(DB, cmd.Name), _ + cmd.Parameters) + Next + res.Rows.Add(Array As Object(0)) + con.TransactionSuccessful + Catch + con.Rollback + Log(LastException) + resp.SendError(500, LastException.Message) + End Try + Dim data() As Byte = ser.ConvertObjectToBytes(res) + resp.OutputStream.WriteBytes(data, 0, data.Length) + Return $"batch (size=${commands.Size})"$ +End Sub + +'#if VERSION1 + +Private Sub ExecuteBatch(DB As String, con As SQL, in As InputStream, resp As ServletResponse) As String + Dim clientVersion As Float = ReadObject(in) 'ignore + Dim numberOfStatements As Int = ReadInt(in) + Dim res(numberOfStatements) As Int + Try + con.BeginTransaction + For i = 0 To numberOfStatements - 1 + Dim queryName As String = ReadObject(in) + Dim params As List = ReadList(in) + con.ExecNonQuery2(Connector.GetCommand(DB, queryName), _ + params) + Next + con.TransactionSuccessful + + Dim out As OutputStream = cs.WrapOutputStream(resp.OutputStream, "gzip") + WriteObject(Main.VERSION, out) + WriteObject("batch", out) + WriteInt(res.Length, out) + For Each r As Int In res + WriteInt(r, out) + Next + out.Close + Catch + con.Rollback + Log(LastException) + resp.SendError(500, LastException.Message) + End Try + Return $"batch (size=${numberOfStatements})"$ +End Sub + +Private Sub ExecuteQuery (DB As String, con As SQL, in As InputStream, resp As ServletResponse) As String +' Log("==== ExecuteQuery ==== ") + Dim clientVersion As Float = ReadObject(in) 'ignore + Dim queryName As String = ReadObject(in) + Dim limit As Int = ReadInt(in) + Dim params As List = ReadList(in) +' Log("EL QUERY: |" & queryName & "|") + Private theSql As String = Connector.GetCommand(DB, queryName) +' Log(theSql) +' Log(params) +' Log(params.Size) + Dim rs As ResultSet = con.ExecQuery2(theSql, params) + If limit <= 0 Then limit = 0x7fffffff 'max int + Dim jrs As JavaObject = rs + Dim rsmd As JavaObject = jrs.RunMethod("getMetaData", Null) + Dim cols As Int = rs.ColumnCount + Dim out As OutputStream = cs.WrapOutputStream(resp.OutputStream, "gzip") + WriteObject(Main.VERSION, out) + WriteObject("query", out) + WriteInt(rs.ColumnCount, out) +' Log($"cols: ${cols}"$) + For i = 0 To cols - 1 + WriteObject(rs.GetColumnName(i), out) + Next + + Do While rs.NextRow And limit > 0 + WriteByte(1, out) + For i = 0 To cols - 1 + Dim ct As Int = rsmd.RunMethod("getColumnType", Array(i + 1)) + 'check whether it is a blob field + If ct = -2 Or ct = 2004 Or ct = -3 Or ct = -4 Then + WriteObject(rs.GetBlob2(i), out) + Else + WriteObject(jrs.RunMethod("getObject", Array(i + 1)), out) + End If + Next + Loop + WriteByte(0, out) + out.Close + rs.Close + + Return "query: " & queryName +End Sub + +Private Sub WriteByte(value As Byte, out As OutputStream) + out.WriteBytes(Array As Byte(value), 0, 1) +End Sub + +Private Sub WriteObject(o As Object, out As OutputStream) + Dim data() As Byte + If o = Null Then + out.WriteBytes(Array As Byte(T_NULL), 0, 1) + Else If o Is Short Then + out.WriteBytes(Array As Byte(T_SHORT), 0, 1) + data = bc.ShortsToBytes(Array As Short(o)) + Else If o Is Int Then + out.WriteBytes(Array As Byte(T_INT), 0, 1) + data = bc.IntsToBytes(Array As Int(o)) + Else If o Is Float Then + out.WriteBytes(Array As Byte(T_FLOAT), 0, 1) + data = bc.FloatsToBytes(Array As Float(o)) + Else If o Is Double Then + out.WriteBytes(Array As Byte(T_DOUBLE), 0, 1) + data = bc.DoublesToBytes(Array As Double(o)) + Else If o Is Long Then + out.WriteBytes(Array As Byte(T_LONG), 0, 1) + data = bc.LongsToBytes(Array As Long(o)) + Else If o Is Boolean Then + out.WriteBytes(Array As Byte(T_BOOLEAN), 0, 1) + Dim b As Boolean = o + Dim data(1) As Byte + If b Then data(0) = 1 Else data(0) = 0 + Else If GetType(o) = "[B" Then + data = o + out.WriteBytes(Array As Byte(T_BLOB), 0, 1) + WriteInt(data.Length, out) + Else 'If o Is String Then (treat all other values as string) + out.WriteBytes(Array As Byte(T_STRING), 0, 1) + data = bc.StringToBytes(o, "UTF8") + WriteInt(data.Length, out) + End If + If data.Length > 0 Then out.WriteBytes(data, 0, data.Length) +End Sub + +Private Sub ReadObject(In As InputStream) As Object + Dim data(1) As Byte + In.ReadBytes(data, 0, 1) + Select data(0) + Case T_NULL + Return Null + Case T_SHORT + Dim data(2) As Byte + Return bc.ShortsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_INT + Dim data(4) As Byte + Return bc.IntsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_LONG + Dim data(8) As Byte + Return bc.LongsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_FLOAT + Dim data(4) As Byte + Return bc.FloatsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_DOUBLE + Dim data(8) As Byte + Return bc.DoublesFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_BOOLEAN + Dim b As Byte = ReadByte(In) + Return b = 1 + Case T_BLOB + Dim len As Int = ReadInt(In) + Dim data(len) As Byte + Return ReadBytesFully(In, data, data.Length) + Case Else + Dim len As Int = ReadInt(In) + Dim data(len) As Byte + ReadBytesFully(In, data, data.Length) + Return BytesToString(data, 0, data.Length, "UTF8") + End Select +End Sub + +Private Sub ReadBytesFully(In As InputStream, Data() As Byte, Len As Int) As Byte() + Dim count = 0, Read As Int + Do While count < Len And Read > -1 + Read = In.ReadBytes(Data, count, Len - count) + count = count + Read + Loop + Return Data +End Sub + +Private Sub WriteInt(i As Int, out As OutputStream) + Dim data() As Byte + data = bc.IntsToBytes(Array As Int(i)) + out.WriteBytes(data, 0, data.Length) +End Sub + +Private Sub ReadInt(In As InputStream) As Int + Dim data(4) As Byte + Return bc.IntsFromBytes(ReadBytesFully(In, data, data.Length))(0) +End Sub + +Private Sub ReadByte(In As InputStream) As Byte + Dim data(1) As Byte + In.ReadBytes(data, 0, 1) + Return data(0) +End Sub + +Private Sub ReadList(in As InputStream) As List + Dim len As Int = ReadInt(in) + Dim l1 As List + l1.Initialize + For i = 0 To len - 1 + l1.Add(ReadObject(in)) + Next + Return l1 +End Sub +'#end If \ No newline at end of file diff --git a/DB4Handler.bas b/DB4Handler.bas new file mode 100644 index 0000000..c832ae5 --- /dev/null +++ b/DB4Handler.bas @@ -0,0 +1,320 @@ +B4J=true +Group=Default Group +ModulesStructureVersion=1 +Type=Class +Version=10 +@EndOfDesignText@ +'Handler class +Sub Class_Globals +' #if VERSION1 + Private const T_NULL = 0, T_STRING = 1, T_SHORT = 2, T_INT = 3, T_LONG = 4, T_FLOAT = 5 _ + ,T_DOUBLE = 6, T_BOOLEAN = 7, T_BLOB = 8 As Byte + Private bc As ByteConverter + Private cs As CompressedStreams +' #end if + Private DateTimeMethods As Map + Private Connector As RDCConnector +End Sub + +Public Sub Initialize + DateTimeMethods = CreateMap(91: "getDate", 92: "getTime", 93: "getTimestamp") +End Sub + +Sub Handle(req As ServletRequest, resp As ServletResponse) + Log("********************* DB4 ********************") + Dim start As Long = DateTime.Now + Dim q As String + Dim in As InputStream = req.InputStream + Dim method As String = req.GetParameter("method") + Connector = Main.Connectors.Get("DB4") + Dim con As SQL + Try +' con = Main.rdcConnectorDB4.GetConnection("DB4") + con = Connector.GetConnection("DB4") + If method = "query2" Then + q = ExecuteQuery2("DB4", con, in, resp) + '#if VERSION1 + Else if method = "query" Then + in = cs.WrapInputStream(in, "gzip") + q = ExecuteQuery("DB4", con, in, resp) + Else if method = "batch" Then + in = cs.WrapInputStream(in, "gzip") + q = ExecuteBatch("DB4", con, in, resp) + '#end if + Else if method = "batch2" Then + q = ExecuteBatch2("DB4", con, in, resp) + Else + Log("Unknown method: " & method) + resp.SendError(500, "unknown method") + End If + Catch + Log(LastException) + resp.SendError(500, LastException.Message) + End Try + If con <> Null And con.IsInitialized Then con.Close + Log($"Command: ${q}, took: ${DateTime.Now - start}ms, client=${req.RemoteAddress}"$) +End Sub + +Private Sub ExecuteQuery2 (DB As String, con As SQL, in As InputStream, resp As ServletResponse) As String + Dim ser As B4XSerializator + Dim m As Map = ser.ConvertBytesToObject(Bit.InputStreamToBytes(in)) + Dim cmd As DBCommand = m.Get("command") + Dim limit As Int = m.Get("limit") + Dim rs As ResultSet = con.ExecQuery2(Connector.GetCommand(DB, cmd.Name), cmd.Parameters) + If limit <= 0 Then limit = 0x7fffffff 'max int + Dim jrs As JavaObject = rs + Dim rsmd As JavaObject = jrs.RunMethod("getMetaData", Null) + Dim cols As Int = rs.ColumnCount + Dim res As DBResult + res.Initialize + res.columns.Initialize + res.Tag = Null 'without this the Tag properly will not be serializable. + For i = 0 To cols - 1 + res.columns.Put(rs.GetColumnName(i), i) + Next + res.Rows.Initialize + Do While rs.NextRow And limit > 0 + Dim row(cols) As Object + For i = 0 To cols - 1 + Dim ct As Int = rsmd.RunMethod("getColumnType", Array(i + 1)) + 'check whether it is a blob field + If ct = -2 Or ct = 2004 Or ct = -3 Or ct = -4 Then + row(i) = rs.GetBlob2(i) + Else If ct = 2005 Then + row(i) = rs.GetString2(i) + Else if ct = 2 Or ct = 3 Then + row(i) = rs.GetDouble2(i) + Else If DateTimeMethods.ContainsKey(ct) Then + Dim SQLTime As JavaObject = jrs.RunMethodJO(DateTimeMethods.Get(ct), Array(i + 1)) + If SQLTime.IsInitialized Then + row(i) = SQLTime.RunMethod("getTime", Null) + Else + row(i) = Null + End If + Else + row(i) = jrs.RunMethod("getObject", Array(i + 1)) + End If + Next + res.Rows.Add(row) + Loop + rs.Close + Dim data() As Byte = ser.ConvertObjectToBytes(res) + resp.OutputStream.WriteBytes(data, 0, data.Length) + Return "query: " & cmd.Name +End Sub + +Private Sub ExecuteBatch2(DB As String, con As SQL, in As InputStream, resp As ServletResponse) As String + Dim ser As B4XSerializator + Dim m As Map = ser.ConvertBytesToObject(Bit.InputStreamToBytes(in)) + Dim commands As List = m.Get("commands") + Dim res As DBResult + res.Initialize + res.columns = CreateMap("AffectedRows (N/A)": 0) + res.Rows.Initialize + res.Tag = Null + Try + con.BeginTransaction + For Each cmd As DBCommand In commands + con.ExecNonQuery2(Connector.GetCommand(DB, cmd.Name), _ + cmd.Parameters) + Next + res.Rows.Add(Array As Object(0)) + con.TransactionSuccessful + Catch + con.Rollback + Log(LastException) + resp.SendError(500, LastException.Message) + End Try + Dim data() As Byte = ser.ConvertObjectToBytes(res) + resp.OutputStream.WriteBytes(data, 0, data.Length) + Return $"batch (size=${commands.Size})"$ +End Sub + +'#if VERSION1 + +Private Sub ExecuteBatch(DB As String, con As SQL, in As InputStream, resp As ServletResponse) As String + Dim clientVersion As Float = ReadObject(in) 'ignore + Dim numberOfStatements As Int = ReadInt(in) + Dim res(numberOfStatements) As Int + Try + con.BeginTransaction + For i = 0 To numberOfStatements - 1 + Dim queryName As String = ReadObject(in) + Dim params As List = ReadList(in) + con.ExecNonQuery2(Connector.GetCommand(DB, queryName), _ + params) + Next + con.TransactionSuccessful + + Dim out As OutputStream = cs.WrapOutputStream(resp.OutputStream, "gzip") + WriteObject(Main.VERSION, out) + WriteObject("batch", out) + WriteInt(res.Length, out) + For Each r As Int In res + WriteInt(r, out) + Next + out.Close + Catch + con.Rollback + Log(LastException) + resp.SendError(500, LastException.Message) + End Try + Return $"batch (size=${numberOfStatements})"$ +End Sub + +Private Sub ExecuteQuery (DB As String, con As SQL, in As InputStream, resp As ServletResponse) As String +' Log("==== ExecuteQuery ==== ") + Dim clientVersion As Float = ReadObject(in) 'ignore + Dim queryName As String = ReadObject(in) + Dim limit As Int = ReadInt(in) + Dim params As List = ReadList(in) +' Log("EL QUERY: |" & queryName & "|") + Private theSql As String = Connector.GetCommand(DB, queryName) +' Log(theSql) +' Log(params) +' Log(params.Size) + Dim rs As ResultSet = con.ExecQuery2(theSql, params) + If limit <= 0 Then limit = 0x7fffffff 'max int + Dim jrs As JavaObject = rs + Dim rsmd As JavaObject = jrs.RunMethod("getMetaData", Null) + Dim cols As Int = rs.ColumnCount + Dim out As OutputStream = cs.WrapOutputStream(resp.OutputStream, "gzip") + WriteObject(Main.VERSION, out) + WriteObject("query", out) + WriteInt(rs.ColumnCount, out) +' Log($"cols: ${cols}"$) + For i = 0 To cols - 1 + WriteObject(rs.GetColumnName(i), out) + Next + + Do While rs.NextRow And limit > 0 + WriteByte(1, out) + For i = 0 To cols - 1 + Dim ct As Int = rsmd.RunMethod("getColumnType", Array(i + 1)) + 'check whether it is a blob field + If ct = -2 Or ct = 2004 Or ct = -3 Or ct = -4 Then + WriteObject(rs.GetBlob2(i), out) + Else + WriteObject(jrs.RunMethod("getObject", Array(i + 1)), out) + End If + Next + Loop + WriteByte(0, out) + out.Close + rs.Close + + Return "query: " & queryName +End Sub + +Private Sub WriteByte(value As Byte, out As OutputStream) + out.WriteBytes(Array As Byte(value), 0, 1) +End Sub + +Private Sub WriteObject(o As Object, out As OutputStream) + Dim data() As Byte + If o = Null Then + out.WriteBytes(Array As Byte(T_NULL), 0, 1) + Else If o Is Short Then + out.WriteBytes(Array As Byte(T_SHORT), 0, 1) + data = bc.ShortsToBytes(Array As Short(o)) + Else If o Is Int Then + out.WriteBytes(Array As Byte(T_INT), 0, 1) + data = bc.IntsToBytes(Array As Int(o)) + Else If o Is Float Then + out.WriteBytes(Array As Byte(T_FLOAT), 0, 1) + data = bc.FloatsToBytes(Array As Float(o)) + Else If o Is Double Then + out.WriteBytes(Array As Byte(T_DOUBLE), 0, 1) + data = bc.DoublesToBytes(Array As Double(o)) + Else If o Is Long Then + out.WriteBytes(Array As Byte(T_LONG), 0, 1) + data = bc.LongsToBytes(Array As Long(o)) + Else If o Is Boolean Then + out.WriteBytes(Array As Byte(T_BOOLEAN), 0, 1) + Dim b As Boolean = o + Dim data(1) As Byte + If b Then data(0) = 1 Else data(0) = 0 + Else If GetType(o) = "[B" Then + data = o + out.WriteBytes(Array As Byte(T_BLOB), 0, 1) + WriteInt(data.Length, out) + Else 'If o Is String Then (treat all other values as string) + out.WriteBytes(Array As Byte(T_STRING), 0, 1) + data = bc.StringToBytes(o, "UTF8") + WriteInt(data.Length, out) + End If + If data.Length > 0 Then out.WriteBytes(data, 0, data.Length) +End Sub + +Private Sub ReadObject(In As InputStream) As Object + Dim data(1) As Byte + In.ReadBytes(data, 0, 1) + Select data(0) + Case T_NULL + Return Null + Case T_SHORT + Dim data(2) As Byte + Return bc.ShortsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_INT + Dim data(4) As Byte + Return bc.IntsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_LONG + Dim data(8) As Byte + Return bc.LongsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_FLOAT + Dim data(4) As Byte + Return bc.FloatsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_DOUBLE + Dim data(8) As Byte + Return bc.DoublesFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_BOOLEAN + Dim b As Byte = ReadByte(In) + Return b = 1 + Case T_BLOB + Dim len As Int = ReadInt(In) + Dim data(len) As Byte + Return ReadBytesFully(In, data, data.Length) + Case Else + Dim len As Int = ReadInt(In) + Dim data(len) As Byte + ReadBytesFully(In, data, data.Length) + Return BytesToString(data, 0, data.Length, "UTF8") + End Select +End Sub + +Private Sub ReadBytesFully(In As InputStream, Data() As Byte, Len As Int) As Byte() + Dim count = 0, Read As Int + Do While count < Len And Read > -1 + Read = In.ReadBytes(Data, count, Len - count) + count = count + Read + Loop + Return Data +End Sub + +Private Sub WriteInt(i As Int, out As OutputStream) + Dim data() As Byte + data = bc.IntsToBytes(Array As Int(i)) + out.WriteBytes(data, 0, data.Length) +End Sub + +Private Sub ReadInt(In As InputStream) As Int + Dim data(4) As Byte + Return bc.IntsFromBytes(ReadBytesFully(In, data, data.Length))(0) +End Sub + +Private Sub ReadByte(In As InputStream) As Byte + Dim data(1) As Byte + In.ReadBytes(data, 0, 1) + Return data(0) +End Sub + +Private Sub ReadList(in As InputStream) As List + Dim len As Int = ReadInt(in) + Dim l1 As List + l1.Initialize + For i = 0 To len - 1 + l1.Add(ReadObject(in)) + Next + Return l1 +End Sub +'#end If \ No newline at end of file diff --git a/Files/config.properties b/Files/config.properties new file mode 100644 index 0000000..d29470b --- /dev/null +++ b/Files/config.properties @@ -0,0 +1,29 @@ +#Lines starting with '#' are comments. +#Backslash character at the end of line means that the command continues in the next line. + +#DATABASE CONFIGURATION +DriverClass=com.mysql.jdbc.Driver +JdbcUrl=jdbc:mysql://localhost/test?characterEncoding=utf8 +User=root +Password= +#Java server port +ServerPort=17178 + +#example of MS SQL Server configuration: +#DriverClass=net.sourceforge.jtds.jdbc.Driver +#JdbcUrl=jdbc:jtds:sqlserver:/// + +#example of postegres configuration: +#JdbcUrl=jdbc:postgresql://localhost/test +#DriverClass=org.postgresql.Driver + +#SQL COMMANDS +sql.create_table=CREATE TABLE IF NOT EXISTS animals (\ + id INTEGER PRIMARY KEY AUTO_INCREMENT,\ + name CHAR(30) NOT NULL,\ + image BLOB) +sql.insert_animal=INSERT INTO animals VALUES (null, ?,?) +sql.select_animal=SELECT name, image, id FROM animals WHERE id = ?; +sql.create_table=CREATE TABLE article (col1 numeric(10,4) ,col2 text); +sql.select=select * from article +sql.insert=INSERT INTO article VALUES(?, ?) \ No newline at end of file diff --git a/Files/reiniciaProcesoPM2.bat b/Files/reiniciaProcesoPM2.bat new file mode 100644 index 0000000..dc1bd70 --- /dev/null +++ b/Files/reiniciaProcesoPM2.bat @@ -0,0 +1,9 @@ +@rem Este script reinicia el proceso en PM2 del servidor de jRDC2 + +@rem estas lineas sirven para que el archivo bat corra en modo administrador. +set "params=%*" +cd /d "%~dp0" && ( if exist "%temp%\getadmin.vbs" del "%temp%\getadmin.vbs" ) && fsutil dirty query %systemdrive% 1>nul 2>nul || ( echo Set UAC = CreateObject^("Shell.Application"^) : UAC.ShellExecute "cmd.exe", "/k cd ""%~sdp0"" && ""%~s0"" %params%", "", "runas", 1 >> "%temp%\getadmin.vbs" && "%temp%\getadmin.vbs" && exit /B ) + +pm2 start RDC-Multi + +exit \ No newline at end of file diff --git a/Files/start.bat b/Files/start.bat new file mode 100644 index 0000000..04641ae --- /dev/null +++ b/Files/start.bat @@ -0,0 +1,8 @@ +@rem Este script mata el proceso del servidor y despues lo reinicia, necesita los archivos stop.bat y start2.bat + +start cmd.exe /c stop.bat +timeout 2 + +start cmd.exe /c start2.bat %1 + +exit \ No newline at end of file diff --git a/Files/start2.bat b/Files/start2.bat new file mode 100644 index 0000000..384def3 --- /dev/null +++ b/Files/start2.bat @@ -0,0 +1,3 @@ +@TITLE -== DBR Server %1 %2 ==- + +"C:\Program Files (x86)\Java\jdk-14\bin\java.exe" -jar jRDC_Multi.jar \ No newline at end of file diff --git a/Files/stop.bat b/Files/stop.bat new file mode 100644 index 0000000..f9fb157 --- /dev/null +++ b/Files/stop.bat @@ -0,0 +1 @@ +wmic Path win32_process Where "CommandLine Like '%%jRDC_Multi.jar%%'" Call Terminate \ No newline at end of file diff --git a/GlobalParameters.bas b/GlobalParameters.bas new file mode 100644 index 0000000..67a50c2 --- /dev/null +++ b/GlobalParameters.bas @@ -0,0 +1,17 @@ +B4J=true +Group=Default Group +ModulesStructureVersion=1 +Type=StaticCode +Version=8.8 +@EndOfDesignText@ + +Sub Process_Globals + Public javaExe As String +' Public WorkingDirectory As String ="C:\jrdcinterface" + Public WorkingDirectory As String = File.DirApp + Public IsPaused As Int = 0 + Public mpLogs As Map + Public mpTotalRequests As Map + Public mpTotalConnections As Map + Public mpBlockConnection As Map +End Sub \ No newline at end of file diff --git a/Manager.bas b/Manager.bas new file mode 100644 index 0000000..56312ce --- /dev/null +++ b/Manager.bas @@ -0,0 +1,134 @@ +B4J=true +Group=Default Group +ModulesStructureVersion=1 +Type=Class +Version=8.8 +@EndOfDesignText@ +'Handler class +Sub Class_Globals + Dim j As JSONGenerator +' Dim rdcc As RDCConnector +End Sub + +Public Sub Initialize + +End Sub + +Sub Handle(req As ServletRequest, resp As ServletResponse) + Dim Command As String = req.GetParameter("command") + Log($"Command: ${Command}"$) + resp.ContentType = "text/html" + If Command = "reload" Then 'Reload config.properties +' rdcc.Initialize + Private estaDB As String = "" +' Log(Main.listaDeCP) + resp.Write($"Test | Reload |
"$) + For i = 0 To Main.listaDeCP.Size - 1 + Main.Connectors.Get(Main.listaDeCP.get(i)).As(RDCConnector).Initialize(Main.listaDeCP.get(i)) + If Main.listaDeCP.get(i) <> "DB1" Then estaDB = "." & Main.listaDeCP.get(i) Else estaDB = "" + resp.Write($"Recargando config${estaDB}.properties ($DateTime{DateTime.Now})
"$) + resp.Write($"Queries en config.properties: ${Main.Connectors.Get(Main.listaDeCP.get(i)).As(RDCConnector).commands.Size}
"$) + resp.Write($"JdbcUrl: ${Main.Connectors.Get(Main.listaDeCP.get(i)).As(RDCConnector).config.Get("JdbcUrl")}
"$) + resp.Write($"User: ${Main.Connectors.Get(Main.listaDeCP.get(i)).As(RDCConnector).config.Get("User")}
"$) + resp.Write($"ServerPort: ${Main.srvr.Port}

"$) + Next +' Public shl As Shell +' shl.Initialize("shl11","cmd",Array("/c","restart.bat")) +' shl.WorkingDirectory = GlobalParameters.WorkingDirectory +' shl.Run(-1) + else If Command = "stop" Then +' Public shl As Shell +' shl.Initialize("shl","cmd",Array("/c","stop.bat")) +' shl.WorkingDirectory = GlobalParameters.WorkingDirectory +' shl.Run(-1) + else If Command = "rsx" Then 'Reiniciamos el servidor DBReq + resp.Write($"Test | Reload |
"$) + Log($"Ejecutamos ${File.DirApp}\start.bat"$) + resp.Write($"Ejecutamos ${File.DirApp}\start.bat"$) + Public shl As Shell + shl.Initialize("shl","cmd",Array("/c",File.DirApp & "\start.bat " & Main.srvr.Port)) + shl.WorkingDirectory = File.DirApp + shl.Run(-1) + else If Command = "rpm2" Then 'Reiniciamos el proceso DBReq en PM2 + resp.Write($"Test | Reload |
"$) + Log($"Ejecutamos ${File.DirApp}\reiniciaProcesoPM2.bat"$) + resp.Write($"Ejecutamos ${File.DirApp}\reiniciaProcesoPM2.bat"$) + Public shl As Shell + shl.Initialize("shl","cmd",Array("/c",File.DirApp & "\reiniciaProcesoPM2.bat " & Main.srvr.Port)) + shl.WorkingDirectory = File.DirApp + shl.Run(-1) + else If Command = "paused" Then + GlobalParameters.IsPaused = 1 + else If Command = "continue" Then + GlobalParameters.IsPaused = 0 + else If Command = "logs" Then + If GlobalParameters.mpLogs.IsInitialized Then + j.Initialize(GlobalParameters.mpLogs) + j.ToString + resp.Write(j.ToString) + End If + else If Command = "block" Then + Dim BlockedConIP As String = req.GetParameter("IP") + If GlobalParameters.mpBlockConnection.IsInitialized Then + GlobalParameters.mpBlockConnection.Put(BlockedConIP,BlockedConIP) + End If + else If Command = "unblock" Then + Dim UnBlockedConIP As String = req.GetParameter("IP") + If GlobalParameters.mpBlockConnection.IsInitialized Then + GlobalParameters.mpBlockConnection.Remove(UnBlockedConIP) + End If + else if Command = "restartserver" Then + Log($"Ejecutamos ${File.DirApp}/restarServer.bat"$) +' Public shl As Shell +' shl.Initialize("shl","cmd",Array("/c","retartserver.bat")) +' shl.WorkingDirectory = GlobalParameters.WorkingDirectory +' shl.Run(-1) + else if Command = "snapshot" Then + Try + resp.ContentType = "image/png" + Dim robot, toolkit, rectangle, ImageIO As JavaObject + robot.InitializeNewInstance("java.awt.Robot", Null) + toolkit.InitializeStatic("java.awt.Toolkit") + Dim rectangle As JavaObject + rectangle.InitializeNewInstance("java.awt.Rectangle", Array As Object( _ + toolkit.RunMethodJO("getDefaultToolkit", Null).RunMethod("getScreenSize", Null))) + Dim image As JavaObject = robot.RunMethod("createScreenCapture", Array As Object(rectangle)) + ImageIO.InitializeStatic("javax.imageio.ImageIO").RunMethod("write", Array As Object( _ + image, "png", resp.OutputStream)) 'the image is written to the response + Catch + resp.SendError(500, LastException.Message) + End Try + else if Command = "runatstartup" Then + '----- You Need to go to the folder on the server : C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp +' ------ then right click - Properties - Security - Edit - Add --> "Everyone" then OK -- then check Full Control (Allow) -- OK + File.Copy("C:\jrdcinterface","startup.bat","C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp","startup.bat") + else if Command = "stoprunatstartup" Then + '----- You Need to go to the folder on the server : C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp +' ------ then right click - Properties - Security - Edit - Add --> "Everyone" then OK -- then check Full Control (Allow) -- OK + File.Delete("C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp","startup.bat") + else if Command = "totalrequests" Then + If GlobalParameters.mpTotalRequests.IsInitialized Then + j.Initialize(GlobalParameters.mpTotalRequests) + j.ToString + resp.Write(j.ToString) + End If + else if Command = "totalblocked" Then + If GlobalParameters.mpBlockConnection.IsInitialized Then + j.Initialize(GlobalParameters.mpBlockConnection) + j.ToString + resp.Write(j.ToString) + End If + else if Command = "totalcon" Then + If GlobalParameters.mpTotalConnections.IsInitialized Then + j.Initialize(GlobalParameters.mpTotalConnections) + j.ToString + resp.Write(j.ToString) + End If + End If + If GlobalParameters.mpLogs.IsInitialized Then GlobalParameters.mpLogs.Put(Command, "Manager : " & Command & " - Time : " & DateTime.Time(DateTime.Now)) +End Sub +'Sub shl11_ProcessCompleted (Success As Boolean, ExitCode As Int, StdOut As String, StdErr As String) +' If Success Then +' Log(Success) +' End If +'End Sub diff --git a/RDCConnector.bas b/RDCConnector.bas new file mode 100644 index 0000000..299fae4 --- /dev/null +++ b/RDCConnector.bas @@ -0,0 +1,81 @@ +B4J=true +Group=Default Group +ModulesStructureVersion=1 +Type=Class +Version=4.19 +@EndOfDesignText@ +'Class module +Sub Class_Globals + Private pool As ConnectionPool + Private DebugQueries As Boolean + Dim commands As Map + Public serverPort As Int + Public usePool As Boolean = True + Dim config As Map +End Sub + +'Initializes the object. You can add parameters to this method if needed. +Public Sub Initialize(DB As String) +' Log("RDCConnector Initialize") + If DB.EqualsIgnoreCase("DB1") Then DB = "" 'Esto para el config.properties or default +' If DB.EqualsIgnoreCase("DB1") Then DB = "" 'Esto para el config.properties or default + Dim config As Map = LoadConfigMap(DB) + Log($"Inicializamos ${DB}, usuario: ${config.Get("User")}"$) + pool.Initialize(config.Get("DriverClass"), config.Get("JdbcUrl"), config.Get("User"), _ + config.Get("Password")) +#if DEBUG + DebugQueries = True +#else + DebugQueries = False +#end if + serverPort = config.Get("ServerPort") + If DB = "" Then DB = "DB1" + LoadSQLCommands(config, DB) +End Sub + +'Sub closePool +' If pool.GetConnection.IsInitialized Then +' pool.ClosePool +' Log("----- Cerramos pool") +' End If +'End Sub + +Private Sub LoadConfigMap(DB As String) As Map + Private DBX As String = "" + If DB <> "" Then DBX = "." & DB + Log("===========================================") + Log($"Leemos el config${DBX}.properties"$) + Return File.ReadMap("./", "config" & DBX & ".properties") +End Sub + +Public Sub GetCommand(DB As String, Key As String) As String +' Log("==== GetCommand ====") +' Log("|" & Key & "|") + commands = Main.commandsMap.get(DB).As(Map) + If commands.ContainsKey("sql." & Key) = False Then + Log("*** Command not found: " & Key) + End If + Log("**** " & Key & " ****") + Log(commands.Get("sql." & Key)) + Return commands.Get("sql." & Key) +End Sub + +Public Sub GetConnection(DB As String) As SQL + If DB.EqualsIgnoreCase("DB1") Then DB = "" 'Esto para el config.properties or default + If DebugQueries Then LoadSQLCommands(LoadConfigMap(DB), DB) + Return pool.GetConnection +End Sub + +Private Sub LoadSQLCommands(config2 As Map, DB As String) + Log($"Cargamos los comandos desde el config.${DB}.properties"$) + Dim newCommands As Map + newCommands.Initialize + For Each k As String In config2.Keys + If k.StartsWith("sql.") Then + newCommands.Put(k, config2.Get(k)) + End If + Next + commands = newCommands +' Log($"Inicializado: ${DB} "$ & Main.commandsMap.IsInitialized) + Main.commandsMap.Put(DB, commands) +End Sub diff --git a/RDCHandler.bas b/RDCHandler.bas new file mode 100644 index 0000000..718efeb --- /dev/null +++ b/RDCHandler.bas @@ -0,0 +1,320 @@ +B4J=true +Group=Default Group +ModulesStructureVersion=1 +Type=Class +Version=4.19 +@EndOfDesignText@ +'Handler class +Sub Class_Globals +' #if VERSION1 + Private const T_NULL = 0, T_STRING = 1, T_SHORT = 2, T_INT = 3, T_LONG = 4, T_FLOAT = 5 _ + ,T_DOUBLE = 6, T_BOOLEAN = 7, T_BLOB = 8 As Byte + Private bc As ByteConverter + Private cs As CompressedStreams +' #end if + Private DateTimeMethods As Map +End Sub + +Public Sub Initialize + DateTimeMethods = CreateMap(91: "getDate", 92: "getTime", 93: "getTimestamp") +End Sub + +Sub Handle(req As ServletRequest, resp As ServletResponse) + Log("***********************************************") + Log(">>>> RDC") + Dim start As Long = DateTime.Now + Dim q As String + Dim in As InputStream = req.InputStream + Dim method As String = req.GetParameter("method") + Dim con As SQL + Try + con = Main.rdcConnector0.GetConnection("") + If method = "query2" Then + q = ExecuteQuery2(con, in, resp) + '#if VERSION1 + Else if method = "query" Then + in = cs.WrapInputStream(in, "gzip") + q = ExecuteQuery(con, in, resp) + Else if method = "batch" Then + in = cs.WrapInputStream(in, "gzip") + q = ExecuteBatch(con, in, resp) + '#end if + Else if method = "batch2" Then + q = ExecuteBatch2(con, in, resp) + Else + Log("Unknown method: " & method) + resp.SendError(500, "unknown method") + End If + Catch + Log(LastException) + resp.SendError(500, LastException.Message) + End Try + If con <> Null And con.IsInitialized Then con.Close + Log($"Command: ${q}, took: ${DateTime.Now - start}ms, client=${req.RemoteAddress}"$) +End Sub + +Private Sub ExecuteQuery2 (con As SQL, in As InputStream, resp As ServletResponse) As String + Dim ser As B4XSerializator + Dim m As Map = ser.ConvertBytesToObject(Bit.InputStreamToBytes(in)) + Dim cmd As DBCommand = m.Get("command") + Dim limit As Int = m.Get("limit") + Dim rs As ResultSet = con.ExecQuery2(Main.rdcConnector0.GetCommand(cmd.Name), cmd.Parameters) + If limit <= 0 Then limit = 0x7fffffff 'max int + Dim jrs As JavaObject = rs + Dim rsmd As JavaObject = jrs.RunMethod("getMetaData", Null) + Dim cols As Int = rs.ColumnCount + Dim res As DBResult + res.Initialize + res.columns.Initialize + res.Tag = Null 'without this the Tag properly will not be serializable. + For i = 0 To cols - 1 + res.columns.Put(rs.GetColumnName(i), i) + Next + res.Rows.Initialize + Do While rs.NextRow And limit > 0 + Dim row(cols) As Object + For i = 0 To cols - 1 + Dim ct As Int = rsmd.RunMethod("getColumnType", Array(i + 1)) + 'check whether it is a blob field + If ct = -2 Or ct = 2004 Or ct = -3 Or ct = -4 Then + row(i) = rs.GetBlob2(i) + Else If ct = 2005 Then + row(i) = rs.GetString2(i) + Else if ct = 2 Or ct = 3 Then + row(i) = rs.GetDouble2(i) + Else If DateTimeMethods.ContainsKey(ct) Then + Dim SQLTime As JavaObject = jrs.RunMethodJO(DateTimeMethods.Get(ct), Array(i + 1)) + If SQLTime.IsInitialized Then + row(i) = SQLTime.RunMethod("getTime", Null) + Else + row(i) = Null + End If + Else + row(i) = jrs.RunMethod("getObject", Array(i + 1)) + End If + Next + res.Rows.Add(row) + Loop + rs.Close + Dim data() As Byte = ser.ConvertObjectToBytes(res) + resp.OutputStream.WriteBytes(data, 0, data.Length) + Return "query: " & cmd.Name +End Sub + +Private Sub ExecuteBatch2(con As SQL, in As InputStream, resp As ServletResponse) As String + Dim ser As B4XSerializator + Dim m As Map = ser.ConvertBytesToObject(Bit.InputStreamToBytes(in)) + Dim commands As List = m.Get("commands") + Dim res As DBResult + res.Initialize + res.columns = CreateMap("AffectedRows (N/A)": 0) + res.Rows.Initialize + res.Tag = Null + Try + con.BeginTransaction + For Each cmd As DBCommand In commands + con.ExecNonQuery2(Main.rdcConnector0.GetCommand(cmd.Name), _ + cmd.Parameters) + Next + res.Rows.Add(Array As Object(0)) + con.TransactionSuccessful + Catch + con.Rollback + Log(LastException) + resp.SendError(500, LastException.Message) + End Try + Dim data() As Byte = ser.ConvertObjectToBytes(res) + resp.OutputStream.WriteBytes(data, 0, data.Length) + Return $"batch (size=${commands.Size})"$ +End Sub + +'#if VERSION1 + +Private Sub ExecuteBatch(con As SQL, in As InputStream, resp As ServletResponse) As String + Dim clientVersion As Float = ReadObject(in) 'ignore + Dim numberOfStatements As Int = ReadInt(in) + Dim res(numberOfStatements) As Int + Try + con.BeginTransaction + For i = 0 To numberOfStatements - 1 + Dim queryName As String = ReadObject(in) + Dim params As List = ReadList(in) + con.ExecNonQuery2(Main.rdcConnector0.GetCommand(queryName), _ + params) + Next + con.TransactionSuccessful + + Dim out As OutputStream = cs.WrapOutputStream(resp.OutputStream, "gzip") + WriteObject(Main.VERSION, out) + WriteObject("batch", out) + WriteInt(res.Length, out) + For Each r As Int In res + WriteInt(r, out) + Next + out.Close + Catch + con.Rollback + Log(LastException) + resp.SendError(500, LastException.Message) + End Try + Return $"batch (size=${numberOfStatements})"$ +End Sub + +Private Sub ExecuteQuery (con As SQL, in As InputStream, resp As ServletResponse) As String +' Log("==== ExecuteQuery ==== ") + Dim clientVersion As Float = ReadObject(in) 'ignore + Dim queryName As String = ReadObject(in) + Dim limit As Int = ReadInt(in) + Dim params As List = ReadList(in) +' Log("EL QUERY: |" & queryName & "|") + Private theSql As String = Main.rdcConnector0.GetCommand(queryName) +' Log(theSql) +' Log(params) +' Log(params.Size) + Dim rs As ResultSet = con.ExecQuery2(theSql, params) + If limit <= 0 Then limit = 0x7fffffff 'max int + Dim jrs As JavaObject = rs + Dim rsmd As JavaObject = jrs.RunMethod("getMetaData", Null) + Dim cols As Int = rs.ColumnCount + Dim out As OutputStream = cs.WrapOutputStream(resp.OutputStream, "gzip") + WriteObject(Main.VERSION, out) + WriteObject("query", out) + WriteInt(rs.ColumnCount, out) +' Log($"cols: ${cols}"$) + For i = 0 To cols - 1 + WriteObject(rs.GetColumnName(i), out) + Next + + Do While rs.NextRow And limit > 0 + WriteByte(1, out) + For i = 0 To cols - 1 + Dim ct As Int = rsmd.RunMethod("getColumnType", Array(i + 1)) + 'check whether it is a blob field + If ct = -2 Or ct = 2004 Or ct = -3 Or ct = -4 Then + WriteObject(rs.GetBlob2(i), out) + Else + WriteObject(jrs.RunMethod("getObject", Array(i + 1)), out) + End If + Next + Loop + WriteByte(0, out) + out.Close + rs.Close + + Return "query: " & queryName +End Sub + +Private Sub WriteByte(value As Byte, out As OutputStream) + out.WriteBytes(Array As Byte(value), 0, 1) +End Sub + + + +Private Sub WriteObject(o As Object, out As OutputStream) + Dim data() As Byte + If o = Null Then + out.WriteBytes(Array As Byte(T_NULL), 0, 1) + Else If o Is Short Then + out.WriteBytes(Array As Byte(T_SHORT), 0, 1) + data = bc.ShortsToBytes(Array As Short(o)) + Else If o Is Int Then + out.WriteBytes(Array As Byte(T_INT), 0, 1) + data = bc.IntsToBytes(Array As Int(o)) + Else If o Is Float Then + out.WriteBytes(Array As Byte(T_FLOAT), 0, 1) + data = bc.FloatsToBytes(Array As Float(o)) + Else If o Is Double Then + out.WriteBytes(Array As Byte(T_DOUBLE), 0, 1) + data = bc.DoublesToBytes(Array As Double(o)) + Else If o Is Long Then + out.WriteBytes(Array As Byte(T_LONG), 0, 1) + data = bc.LongsToBytes(Array As Long(o)) + Else If o Is Boolean Then + out.WriteBytes(Array As Byte(T_BOOLEAN), 0, 1) + Dim b As Boolean = o + Dim data(1) As Byte + If b Then data(0) = 1 Else data(0) = 0 + Else If GetType(o) = "[B" Then + data = o + out.WriteBytes(Array As Byte(T_BLOB), 0, 1) + WriteInt(data.Length, out) + Else 'If o Is String Then (treat all other values as string) + out.WriteBytes(Array As Byte(T_STRING), 0, 1) + data = bc.StringToBytes(o, "UTF8") + WriteInt(data.Length, out) + End If + If data.Length > 0 Then out.WriteBytes(data, 0, data.Length) +End Sub + +Private Sub ReadObject(In As InputStream) As Object + Dim data(1) As Byte + In.ReadBytes(data, 0, 1) + Select data(0) + Case T_NULL + Return Null + Case T_SHORT + Dim data(2) As Byte + Return bc.ShortsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_INT + Dim data(4) As Byte + Return bc.IntsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_LONG + Dim data(8) As Byte + Return bc.LongsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_FLOAT + Dim data(4) As Byte + Return bc.FloatsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_DOUBLE + Dim data(8) As Byte + Return bc.DoublesFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_BOOLEAN + Dim b As Byte = ReadByte(In) + Return b = 1 + Case T_BLOB + Dim len As Int = ReadInt(In) + Dim data(len) As Byte + Return ReadBytesFully(In, data, data.Length) + Case Else + Dim len As Int = ReadInt(In) + Dim data(len) As Byte + ReadBytesFully(In, data, data.Length) + Return BytesToString(data, 0, data.Length, "UTF8") + End Select +End Sub + +Private Sub ReadBytesFully(In As InputStream, Data() As Byte, Len As Int) As Byte() + Dim count = 0, Read As Int + Do While count < Len And Read > -1 + Read = In.ReadBytes(Data, count, Len - count) + count = count + Read + Loop + Return Data +End Sub + +Private Sub WriteInt(i As Int, out As OutputStream) + Dim data() As Byte + data = bc.IntsToBytes(Array As Int(i)) + out.WriteBytes(data, 0, data.Length) +End Sub + +Private Sub ReadInt(In As InputStream) As Int + Dim data(4) As Byte + Return bc.IntsFromBytes(ReadBytesFully(In, data, data.Length))(0) +End Sub + +Private Sub ReadByte(In As InputStream) As Byte + Dim data(1) As Byte + In.ReadBytes(data, 0, 1) + Return data(0) +End Sub + +Private Sub ReadList(in As InputStream) As List + Dim len As Int = ReadInt(in) + Dim l1 As List + l1.Initialize + For i = 0 To len - 1 + l1.Add(ReadObject(in)) + Next + Return l1 +End Sub +'#end If \ No newline at end of file diff --git a/TestHandler.bas b/TestHandler.bas new file mode 100644 index 0000000..d698a1b --- /dev/null +++ b/TestHandler.bas @@ -0,0 +1,35 @@ +B4J=true +Group=Default Group +ModulesStructureVersion=1 +Type=Class +Version=4.19 +@EndOfDesignText@ +'Handler class +Sub Class_Globals + +End Sub + +Public Sub Initialize + +End Sub + +Sub Handle(req As ServletRequest, resp As ServletResponse) + Log("TEST") + resp.ContentType = "text/html" + resp.Write($"Test | Reload |
"$) + resp.Write($"RemoteServer is running on port ${Main.srvr.Port} ($DateTime{DateTime.Now})
"$) + Try +' Dim con As SQL = Main.rdcConnectorDB1.GetConnection("") + Dim con As SQL = Main.Connectors.Get("DB1").As(RDCConnector).GetConnection("") + resp.Write("Connection successful.

") + Private estaDB As String = "" + Log(Main.listaDeCP) + For i = 0 To Main.listaDeCP.Size - 1 + If Main.listaDeCP.get(i) <> "" Then estaDB = "." & Main.listaDeCP.get(i) + resp.Write($"Using config${estaDB}.properties
"$) + Next + con.Close + Catch + resp.Write("Error fetching connection.") + End Try +End Sub \ No newline at end of file diff --git a/config.properties.original b/config.properties.original new file mode 100644 index 0000000..e55e120 --- /dev/null +++ b/config.properties.original @@ -0,0 +1,75 @@ +#Lines starting with '#' are comments. +#Backslash character at the end of line means that the command continues in the next line. + +DriverClass=oracle.jdbc.driver.OracleDriver +#JdbcUrl=jdbc:mysql://localhost/test?characterEncoding=utf8 + +#SQL Server +#DriverClass=net.sourceforge.jtds.jdbc.Driver + +# este para produccion GHAN JdbcUrl=jdbc:oracle:thin:@//192.168.15.53:1521/DBKMT +#GOHAN ---> server +JdbcUrl=jdbc:oracle:thin:@//10.0.0.205:1521/DBKMT +#JdbcUrl=jdbc:oracle:thin:@//10.0.0.236:1521/DBKMT + + +# SVR-KEYMON-PRODUCCION--> Usuario +User=GUNA +Password=GUNAD2015M + +#User=TORRADOCONAUTO +#Password=TORRADOCONAUTOD2016M + + +#--> Puertos +#SAC - DFR - MDA / GOHAN -->COBRANZA +#ServerPort=1783 +#GUNA - SALMA - DURAKELO - DBC / SVR-KEYMON-PRODUCCION --> DISTRIBUIDORAS +ServerPort=1783 +#CMG - TORRADO / TRUNKS -->COBRANZA/ GM +#ServerPort=1781 + +#If Debug is true then this file will be reloaded on every query. +#This is useful if you need to modify the queries. +Debug=true + +#SQL COMMANDS + +################## +################# +################ S O P O R T E +################# +################## + +sql.select_soporte=select * from GUNA.soporte + +sql.select_almacenes_KELL=select CAT_AG_ID, CAT_AG_NOMBRE from KELLOGGS.cat_agencias order by CAT_AG_NOMBRE +sql.select_almacenes_GUNA=select CAT_AG_ID, CAT_AG_NOMBRE from GUNA.cat_agencias order by CAT_AG_NOMBRE +sql.select_almacenes_SALMA=select CAT_AG_ID, CAT_AG_NOMBRE from SALMA.cat_agencias order by CAT_AG_NOMBRE +sql.select_almacenes_DANVIT=select CAT_AG_ID, CAT_AG_NOMBRE from DANVIT.cat_agencias order by CAT_AG_NOMBRE + +sql.proc_QUITAR_VENTA_KELL=BEGIN EXECUTE IMMEDIATE ('DECLARE Cursor_SYS Sys_Refcursor; BEGIN KELLOGGS.SP_QUITAR_VENTA_X_TIPO( '''||(?)||''', '''||(?)||''', '''||(?)||''', '''||(?)||''', '''||(?)||''', Cursor_SYS); end;'); END; +sql.proc_QUITAR_VENTA_GUNA=BEGIN EXECUTE IMMEDIATE ('DECLARE Cursor_SYS Sys_Refcursor; BEGIN GUNA.SP_QUITAR_VENTA( '''||(?)||''', '''||(?)||''', '''||(?)||''', Cursor_SYS, '''||(?)||'''); end;'); END; +sql.proc_QUITAR_VENTA_SALMA=BEGIN EXECUTE IMMEDIATE ('DECLARE Cursor_SYS Sys_Refcursor; BEGIN SALMA.SP_QUITAR_VENTA( '''||(?)||''', '''||(?)||''', '''||(?)||''', Cursor_SYS); end;'); END; +sql.proc_QUITAR_VENTA_DANVIT=BEGIN EXECUTE IMMEDIATE ('DECLARE Cursor_SYS Sys_Refcursor; BEGIN DANVIT.SP_QUITAR_VENTA( '''||(?)||''', '''||(?)||''', '''||(?)||''', Cursor_SYS); end;'); END; +sql.proc_QUITAR_PAGOPAGARE_KELLOGGS=BEGIN EXECUTE IMMEDIATE ('DECLARE Cursor_SYS Sys_Refcursor; BEGIN KELLOGGS.SP_ELIMINAS_PAGOS_PAGARES_REP( '''||(?)||''', '''||(?)||''', '''||(?)||''', Cursor_SYS); end;'); END; +sql.proc_LIBERA_BANDERA_FACTURACION_KELLOGGS=BEGIN EXECUTE IMMEDIATE ('DECLARE Cursor_SYS Sys_Refcursor; BEGIN KELLOGGS.SP_LIBERA_FACTURACION(Cursor_SYS); end;'); END; +sql.proc_LIBERA_BANDERA_CARGAFORANEA_KELLOGGS=BEGIN EXECUTE IMMEDIATE ('DECLARE Cursor_SYS Sys_Refcursor; BEGIN KELLOGGS.SP_LLENAR_FILTROS ( '''||(?)||''', '''||(?)||''', Cursor_SYS); end;'); END; + + +sql.proc_QUITAR_TICKET_KELLOGGS=BEGIN EXECUTE IMMEDIATE ('DECLARE Cursor_SYS Sys_Refcursor; BEGIN KELLOGGS.SP_QUITAR_TICKET( '''||(?)||''', '''||(?)||''', '''||(?)||''', Cursor_SYS); end;'); END; + +sql.revisa_liquidada_Guna=SELECT COUNT(*) as liquidada FROM GUNA.HIST_VENTAS_DETALLE WHERE trunc(HVD_DTESYNC) = trunc(sysdate) and hvd_almacen = (?) and hvd_ruta = (?) AND (HVD_DESCUENTO != 0 or HVD_FECHA_AVION IS NOT NULL) +sql.revisa_liquidada_Kell=SELECT COUNT(*) as liquidada FROM KELLOGGS.HIST_VENTAS_DETALLE WHERE trunc(HVD_DTESYNC) = trunc(sysdate) and hvd_almacen = (?) and hvd_ruta = (?) and HVD_TIPOVENTA = (?) AND HVD_ESTATUS = 'Liquidado' + +sql.select_todos_soporte=select cat_lo_usuario, cat_lo_estatus, cat_lo_nombre, cat_lo_contrasena, cat_lo_agencia, cat_agencias.cat_ag_nombre, cat_lo_ruta from cat_logins left join cat_agencias on cat_lo_agencia = cat_ag_id where (cat_lo_usuario LIKE ('%'||(?)||'%') or cat_lo_nombre LIKE ('%'||(?)||'%')) and cat_ag_nombre LIKE ('%'||(?)||'%') and cat_lo_ruta LIKE ('%'||(?)||'%') and rownum <= 20 +sql.select_todosGUNA_soporte=select cat_lo_usuario, cat_lo_estatus, cat_lo_nombre, cat_lo_contrasena, cat_lo_agencia, cat_agencias.cat_ag_nombre, cat_ru_ruta from cat_logins left join cat_agencias on cat_lo_agencia = cat_ag_id left join cat_rutas on cat_lo_usuario = cat_ru_vendedor where (cat_lo_usuario LIKE ('%'||(?)||'%') or cat_lo_nombre LIKE ('%'||(?)||'%')) and cat_ag_nombre LIKE ('%'||(?)||'%') and cat_ru_ruta LIKE ('%'||(?)||'%') and rownum <= 20 +sql.select_todosKELLOGGS_soporte=select cat_lo_usuario, cat_lo_estatus, cat_lo_nombre, cat_lo_contrasena, cat_lo_agencia, cat_agencias.cat_ag_nombre, cat_ru_ruta from KELLOGGS.cat_logins left join KELLOGGS.cat_agencias on cat_lo_agencia = cat_ag_id left join KELLOGGS.cat_rutas on cat_lo_usuario = cat_ru_vendedor where (cat_lo_usuario LIKE ('%'||(?)||'%') or cat_lo_nombre LIKE ('%'||(?)||'%')) and cat_ag_nombre LIKE ('%'||(?)||'%') and cat_ru_ruta LIKE ('%'||(?)||'%') and rownum <= 20 +sql.select_todosSALMA_soporte=select cat_lo_usuario, cat_lo_estatus, cat_lo_nombre, cat_lo_contrasena, cat_lo_agencia, cat_agencias.cat_ag_nombre, cat_lo_ruta as cat_ru_ruta from SALMA.cat_logins left join SALMA.cat_agencias on cat_lo_agencia = cat_ag_id where (cat_lo_usuario LIKE ('%'||(?)||'%') or cat_lo_nombre LIKE ('%'||(?)||'%')) and cat_ag_nombre LIKE ('%'||(?)||'%') and cat_lo_ruta LIKE ('%'||(?)||'%') and rownum <= 20 +sql.select_todosDANVIT_soporte=select cat_lo_usuario, cat_lo_estatus, cat_lo_nombre, cat_lo_contrasena, cat_lo_agencia, cat_agencias.cat_ag_nombre, cat_ru_ruta from DANVIT.cat_logins left join DANVIT.cat_agencias on cat_lo_agencia = cat_ag_id left join DANVIT.cat_rutas on cat_lo_usuario = cat_ru_vendedor where (cat_lo_usuario LIKE ('%'||(?)||'%') or cat_lo_nombre LIKE ('%'||(?)||'%')) and cat_ag_nombre LIKE ('%'||(?)||'%') and cat_ru_ruta LIKE ('%'||(?)||'%') and rownum <= 20 +sql.select_ventaXrutaGuna_soporte=select hvd_ruta, sum(hvd_costo_tot) as monto, hvd_tipoventa from hist_ventas_detalle where trunc(hvd_fecha)=trunc(sysdate) and hvd_ruta=(?) and hvd_almacen=(?) AND hvd_codpromo <> 'BASICA' group by hvd_ruta, hvd_tipoventa +sql.select_ventaXrutaKelloggs_soporte=select hvd_ruta, sum(hvd_costo_tot) as monto, hvd_tipoventa from KELLOGGS.hist_ventas_detalle where trunc(hvd_fecha)=trunc(sysdate) and hvd_ruta=(?) and hvd_almacen=(?) and hvd_tipoventa=(?) AND hvd_codpromo <> 'BASICA' group by hvd_ruta, hvd_tipoventa +sql.select_ventaXrutaSalma_soporte=select hvd_ruta, sum(hvd_costo_tot) as monto, hvd_tipoventa from SALMA.hist_ventas_detalle where trunc(hvd_fecha)=trunc(sysdate) and hvd_ruta=(?) and hvd_almacen=(?) AND hvd_codpromo <> 'BASICA' group by hvd_ruta, hvd_tipoventa +sql.select_ventaXrutaDanvit_soporte=select hvd_ruta, sum(hvd_costo_tot) as monto, hvd_tipoventa from DANVIT.hist_ventas_detalle where trunc(hvd_fecha)=trunc(sysdate) and hvd_ruta=(?) and hvd_almacen=(?) AND hvd_codpromo <> 'BASICA' group by hvd_ruta, hvd_tipoventa +sql.select_prodsTicket_Kelloggs=SELECT HVD_CLIENTE CLIENTE, HVD_PROID PRODUCTO_ID, HVD_PRONOMBRE NOMBRE_PRODUCTO, HVD_CANT CANTIDAD, HVD_COSTO_TOT COSTO_TOTAL, HVD_RUTA RUTA, HVD_CODPROMO CODPROMO,NVL(HVD_TIPOVENTA,' ') TIPOVENTA, NVL(HVD_ESTATUS,' ') ESTATUS, hvd_cedis FROM KELLOGGS.HIST_VENTAS_DETALLE WHERE TRUNC(HVD_FECHA) = TRUNC(SYSDATE) AND HVD_ALMACEN = (?) AND HVD_CLIENTE = (?) and hvd_rechazo is null ORDER BY HVD_CODPROMO, HVD_PRONOMBRE + diff --git a/config.properties.postgres b/config.properties.postgres new file mode 100644 index 0000000..86f0df2 --- /dev/null +++ b/config.properties.postgres @@ -0,0 +1,80 @@ +#Lines starting with '#' are comments. +#Backslash character at the end of line means that the command continues in the next line. + +#DriverClass=oracle.jdbc.driver.OracleDriver +#JdbcUrl=jdbc:mysql://localhost/test?characterEncoding=utf8 +DriverClass=org.postgresql.Driver + +#SQL Server +#DriverClass=net.sourceforge.jtds.jdbc.Driver + +# este para produccion GHAN JdbcUrl=jdbc:oracle:thin:@//192.168.15.53:1521/DBKMT +#GOHAN ---> server +#JdbcUrl=jdbc:oracle:thin:@//10.0.0.205:1521/DBKMT +#JdbcUrl=jdbc:oracle:thin:@//10.0.0.236:1521/DBKMT +JdbcUrl=jdbc:postgresql://localhost/pruebaKMT + +# SVR-KEYMON-PRODUCCION--> Usuario +#User=GUNA +#Password=GUNAD2015M + +User=postgres +Password=Demo1234 + +#User=TORRADOCONAUTO +#Password=TORRADOCONAUTOD2016M + + +#--> Puertos +#SAC - DFR - MDA / GOHAN -->COBRANZA +#ServerPort=1783 +#GUNA - SALMA - DURAKELO - DBC / SVR-KEYMON-PRODUCCION --> DISTRIBUIDORAS +#ServerPort=1783 +#CMG - TORRADO / TRUNKS -->COBRANZA/ GM +#ServerPort=1781 +ServerPort=5432 + +#If Debug is true then this file will be reloaded on every query. +#This is useful if you need to modify the queries. +Debug=true + +#SQL COMMANDS + +################## +################# +################ S O P O R T E +################# +################## + +sql.select_soporte=select * from GUNA.soporte + +sql.select_almacenes_KELL=select CAT_AG_ID, CAT_AG_NOMBRE from KELLOGGS.cat_agencias order by CAT_AG_NOMBRE +sql.select_almacenes_GUNA=select CAT_AG_ID, CAT_AG_NOMBRE from GUNA.cat_agencias order by CAT_AG_NOMBRE +sql.select_almacenes_SALMA=select CAT_AG_ID, CAT_AG_NOMBRE from SALMA.cat_agencias order by CAT_AG_NOMBRE +sql.select_almacenes_DANVIT=select CAT_AG_ID, CAT_AG_NOMBRE from DANVIT.cat_agencias order by CAT_AG_NOMBRE + +sql.proc_QUITAR_VENTA_KELL=BEGIN EXECUTE IMMEDIATE ('DECLARE Cursor_SYS Sys_Refcursor; BEGIN KELLOGGS.SP_QUITAR_VENTA_X_TIPO( '''||(?)||''', '''||(?)||''', '''||(?)||''', '''||(?)||''', '''||(?)||''', Cursor_SYS); end;'); END; +sql.proc_QUITAR_VENTA_GUNA=BEGIN EXECUTE IMMEDIATE ('DECLARE Cursor_SYS Sys_Refcursor; BEGIN GUNA.SP_QUITAR_VENTA( '''||(?)||''', '''||(?)||''', '''||(?)||''', Cursor_SYS, '''||(?)||'''); end;'); END; +sql.proc_QUITAR_VENTA_SALMA=BEGIN EXECUTE IMMEDIATE ('DECLARE Cursor_SYS Sys_Refcursor; BEGIN SALMA.SP_QUITAR_VENTA( '''||(?)||''', '''||(?)||''', '''||(?)||''', Cursor_SYS); end;'); END; +sql.proc_QUITAR_VENTA_DANVIT=BEGIN EXECUTE IMMEDIATE ('DECLARE Cursor_SYS Sys_Refcursor; BEGIN DANVIT.SP_QUITAR_VENTA( '''||(?)||''', '''||(?)||''', '''||(?)||''', Cursor_SYS); end;'); END; +sql.proc_QUITAR_PAGOPAGARE_KELLOGGS=BEGIN EXECUTE IMMEDIATE ('DECLARE Cursor_SYS Sys_Refcursor; BEGIN KELLOGGS.SP_ELIMINAS_PAGOS_PAGARES_REP( '''||(?)||''', '''||(?)||''', '''||(?)||''', Cursor_SYS); end;'); END; +sql.proc_LIBERA_BANDERA_FACTURACION_KELLOGGS=BEGIN EXECUTE IMMEDIATE ('DECLARE Cursor_SYS Sys_Refcursor; BEGIN KELLOGGS.SP_LIBERA_FACTURACION(Cursor_SYS); end;'); END; +sql.proc_LIBERA_BANDERA_CARGAFORANEA_KELLOGGS=BEGIN EXECUTE IMMEDIATE ('DECLARE Cursor_SYS Sys_Refcursor; BEGIN KELLOGGS.SP_LLENAR_FILTROS ( '''||(?)||''', '''||(?)||''', Cursor_SYS); end;'); END; + + +sql.proc_QUITAR_TICKET_KELLOGGS=BEGIN EXECUTE IMMEDIATE ('DECLARE Cursor_SYS Sys_Refcursor; BEGIN KELLOGGS.SP_QUITAR_TICKET( '''||(?)||''', '''||(?)||''', '''||(?)||''', Cursor_SYS); end;'); END; + +sql.revisa_liquidada_Guna=SELECT COUNT(*) as liquidada FROM GUNA.HIST_VENTAS_DETALLE WHERE trunc(HVD_DTESYNC) = trunc(sysdate) and hvd_almacen = (?) and hvd_ruta = (?) AND (HVD_DESCUENTO != 0 or HVD_FECHA_AVION IS NOT NULL) +sql.revisa_liquidada_Kell=SELECT COUNT(*) as liquidada FROM KELLOGGS.HIST_VENTAS_DETALLE WHERE trunc(HVD_DTESYNC) = trunc(sysdate) and hvd_almacen = (?) and hvd_ruta = (?) and HVD_TIPOVENTA = (?) AND HVD_ESTATUS = 'Liquidado' + +sql.select_todos_soporte=select cat_lo_usuario, cat_lo_estatus, cat_lo_nombre, cat_lo_contrasena, cat_lo_agencia, cat_agencias.cat_ag_nombre, cat_lo_ruta from cat_logins left join cat_agencias on cat_lo_agencia = cat_ag_id where (cat_lo_usuario LIKE ('%'||(?)||'%') or cat_lo_nombre LIKE ('%'||(?)||'%')) and cat_ag_nombre LIKE ('%'||(?)||'%') and cat_lo_ruta LIKE ('%'||(?)||'%') and rownum <= 20 +sql.select_todosGUNA_soporte=select cat_lo_usuario, cat_lo_estatus, cat_lo_nombre, cat_lo_contrasena, cat_lo_agencia, cat_agencias.cat_ag_nombre, cat_ru_ruta from cat_logins left join cat_agencias on cat_lo_agencia = cat_ag_id left join cat_rutas on cat_lo_usuario = cat_ru_vendedor where (cat_lo_usuario LIKE ('%'||(?)||'%') or cat_lo_nombre LIKE ('%'||(?)||'%')) and cat_ag_nombre LIKE ('%'||(?)||'%') and cat_ru_ruta LIKE ('%'||(?)||'%') and rownum <= 20 +sql.select_todosKELLOGGS_soporte=select cat_lo_usuario, cat_lo_estatus, cat_lo_nombre, cat_lo_contrasena, cat_lo_agencia, cat_agencias.cat_ag_nombre, cat_ru_ruta from KELLOGGS.cat_logins left join KELLOGGS.cat_agencias on cat_lo_agencia = cat_ag_id left join KELLOGGS.cat_rutas on cat_lo_usuario = cat_ru_vendedor where (cat_lo_usuario LIKE ('%'||(?)||'%') or cat_lo_nombre LIKE ('%'||(?)||'%')) and cat_ag_nombre LIKE ('%'||(?)||'%') and cat_ru_ruta LIKE ('%'||(?)||'%') and rownum <= 20 +sql.select_todosSALMA_soporte=select cat_lo_usuario, cat_lo_estatus, cat_lo_nombre, cat_lo_contrasena, cat_lo_agencia, cat_agencias.cat_ag_nombre, cat_lo_ruta as cat_ru_ruta from SALMA.cat_logins left join SALMA.cat_agencias on cat_lo_agencia = cat_ag_id where (cat_lo_usuario LIKE ('%'||(?)||'%') or cat_lo_nombre LIKE ('%'||(?)||'%')) and cat_ag_nombre LIKE ('%'||(?)||'%') and cat_lo_ruta LIKE ('%'||(?)||'%') and rownum <= 20 +sql.select_todosDANVIT_soporte=select cat_lo_usuario, cat_lo_estatus, cat_lo_nombre, cat_lo_contrasena, cat_lo_agencia, cat_agencias.cat_ag_nombre, cat_ru_ruta from DANVIT.cat_logins left join DANVIT.cat_agencias on cat_lo_agencia = cat_ag_id left join DANVIT.cat_rutas on cat_lo_usuario = cat_ru_vendedor where (cat_lo_usuario LIKE ('%'||(?)||'%') or cat_lo_nombre LIKE ('%'||(?)||'%')) and cat_ag_nombre LIKE ('%'||(?)||'%') and cat_ru_ruta LIKE ('%'||(?)||'%') and rownum <= 20 +sql.select_ventaXrutaGuna_soporte=select hvd_ruta, sum(hvd_costo_tot) as monto, hvd_tipoventa from hist_ventas_detalle where trunc(hvd_fecha)=trunc(sysdate) and hvd_ruta=(?) and hvd_almacen=(?) AND hvd_codpromo <> 'BASICA' group by hvd_ruta, hvd_tipoventa +sql.select_ventaXrutaKelloggs_soporte=select hvd_ruta, sum(hvd_costo_tot) as monto, hvd_tipoventa from KELLOGGS.hist_ventas_detalle where trunc(hvd_fecha)=trunc(sysdate) and hvd_ruta=(?) and hvd_almacen=(?) and hvd_tipoventa=(?) AND hvd_codpromo <> 'BASICA' group by hvd_ruta, hvd_tipoventa +sql.select_ventaXrutaSalma_soporte=select hvd_ruta, sum(hvd_costo_tot) as monto, hvd_tipoventa from SALMA.hist_ventas_detalle where trunc(hvd_fecha)=trunc(sysdate) and hvd_ruta=(?) and hvd_almacen=(?) AND hvd_codpromo <> 'BASICA' group by hvd_ruta, hvd_tipoventa +sql.select_ventaXrutaDanvit_soporte=select hvd_ruta, sum(hvd_costo_tot) as monto, hvd_tipoventa from DANVIT.hist_ventas_detalle where trunc(hvd_fecha)=trunc(sysdate) and hvd_ruta=(?) and hvd_almacen=(?) AND hvd_codpromo <> 'BASICA' group by hvd_ruta, hvd_tipoventa +sql.select_prodsTicket_Kelloggs=SELECT HVD_CLIENTE CLIENTE, HVD_PROID PRODUCTO_ID, HVD_PRONOMBRE NOMBRE_PRODUCTO, HVD_CANT CANTIDAD, HVD_COSTO_TOT COSTO_TOTAL, HVD_RUTA RUTA, HVD_CODPROMO CODPROMO,NVL(HVD_TIPOVENTA,' ') TIPOVENTA, NVL(HVD_ESTATUS,' ') ESTATUS, hvd_cedis FROM KELLOGGS.HIST_VENTAS_DETALLE WHERE TRUNC(HVD_FECHA) = TRUNC(SYSDATE) AND HVD_ALMACEN = (?) AND HVD_CLIENTE = (?) and hvd_rechazo is null ORDER BY HVD_CODPROMO, HVD_PRONOMBRE + diff --git a/jRDC_Multi.b4j b/jRDC_Multi.b4j new file mode 100644 index 0000000..287f9ff --- /dev/null +++ b/jRDC_Multi.b4j @@ -0,0 +1,116 @@ +AppType=StandardJava +Build1=Default,b4j.JRDCMulti +File1=config.properties +FileGroup1=Default Group +Group=Default Group +Library1=javaobject +Library2=jcore +Library3=jrandomaccessfile +Library4=jserver +Library5=jshell +Library6=json +Library7=jsql +Library8=byteconverter +Module1=DB1Handler +Module2=DB2Handler +Module3=DB3Handler +Module4=DB4Handler +Module5=GlobalParameters +Module6=Manager +Module7=RDCConnector +Module8=TestHandler +NumberOfFiles=1 +NumberOfLibraries=8 +NumberOfModules=8 +Version=10 +@EndOfDesignText@ +'Non-UI application (console / server application) +#Region Project Attributes + #CommandLineArgs: + #MergeLibraries: True + ' VERSION 4.11.09 + '########################################################################################################### + '###################### PULL ############################################################# + 'Ctrl + click ide://run?file=%WINDIR%\System32\cmd.exe&Args=/c&Args=git&Args=pull + '########################################################################################################### + '###################### PUSH ############################################################# + 'Ctrl + click ide://run?file=%WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe&Args=github&Args=..\..\ + '########################################################################################################### + '###################### PUSH TORTOISE GIT ######################################################### + 'Ctrl + click ide://run?file=%WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe&Args=TortoiseGitProc&Args=/command:commit&Args=/path:"../"&Args=/closeonend:2 + '########################################################################################################### +#End Region + +'change based on the jdbc jar file +'#AdditionalJar: mysql-connector-java-5.1.27-bin +'#AdditionalJar: postgresql-42.7.0 +#AdditionalJar: ojdbc11 + +Sub Process_Globals + Public srvr As Server +' Public rdcConnectorDB1 As RDCConnector +' Public rdcConnectorDB2 As RDCConnector +' Public rdcConnectorDB3 As RDCConnector +' Public rdcConnectorDB4 As RDCConnector + Public const VERSION As Float = 2.23 + Type DBCommand (Name As String, Parameters() As Object) + Type DBResult (Tag As Object, Columns As Map, Rows As List) + Dim listaDeCP As List + Dim cpFiles As List + Public Connectors, commandsMap As Map +End Sub + +Sub AppStart (Args() As String) + listaDeCP.Initialize + srvr.Initialize("") + Dim con As RDCConnector + Connectors = srvr.CreateThreadSafeMap +' commandsMap = srvr.CreateThreadSafeMap + commandsMap.Initialize + con.Initialize("DB1") 'Inicializamos el default de config.properties + Connectors.Put("DB1", con) + srvr.Port = con.serverPort + listaDeCP.Add("DB1") + cpFiles = File.ListFiles("./") + If cpFiles.Size > 0 Then + Log(cpFiles) + For i = 0 To cpFiles.Size - 1 + If cpFiles.Get(i) = "config.DB2.properties" Then + Dim con As RDCConnector + con.Initialize("DB2") + Connectors.Put("DB2", con) + listaDeCP.Add("DB2") + End If + If cpFiles.Get(i) = "config.DB3.properties" Then + Dim con As RDCConnector + con.Initialize("DB3") + Connectors.Put("DB3", con) + listaDeCP.Add("DB3") + End If + If cpFiles.Get(i) = "config.DB4.properties" Then + con.Initialize("DB4") + Connectors.Put("DB4", con) + listaDeCP.Add("DB4") + End If + Next + End If +' con.Initialize("DB1") 'Inicializamos el default de config.properties +' Connectors.Put("DB1", con) +' srvr.Port = con.serverPort + srvr.AddHandler("/test", "TestHandler", False) + srvr.AddHandler("/manager", "Manager", False) + srvr.AddHandler("/*", "DB1Handler", False) + srvr.AddHandler("/db1", "DB1Handler", False) + srvr.AddHandler("/DB1", "DB1Handler", False) + srvr.AddHandler("/db2", "DB2Handler", False) + srvr.AddHandler("/DB2", "DB2Handler", False) + srvr.AddHandler("/db3", "DB3Handler", False) + srvr.AddHandler("/DB3", "DB3Handler", False) + srvr.AddHandler("/db4", "DB4Handler", False) + srvr.AddHandler("/DB4", "DB4Handler", False) + srvr.Start + Log("===========================================================") + Log($"-=== jRDC is running on port: ${srvr.port} (version = $1.2{VERSION}) ===-"$) + Log("===========================================================") + StartMessageLoop +End Sub \ No newline at end of file diff --git a/jRDC_Multi.b4j.meta b/jRDC_Multi.b4j.meta new file mode 100644 index 0000000..bf474b5 --- /dev/null +++ b/jRDC_Multi.b4j.meta @@ -0,0 +1,30 @@ +ModuleBookmarks0= +ModuleBookmarks1= +ModuleBookmarks2= +ModuleBookmarks3= +ModuleBookmarks4= +ModuleBookmarks5= +ModuleBookmarks6= +ModuleBookmarks7= +ModuleBookmarks8= +ModuleBreakpoints0= +ModuleBreakpoints1= +ModuleBreakpoints2= +ModuleBreakpoints3= +ModuleBreakpoints4= +ModuleBreakpoints5= +ModuleBreakpoints6= +ModuleBreakpoints7= +ModuleBreakpoints8= +ModuleClosedNodes0= +ModuleClosedNodes1=9,10,11,12,13,14,15 +ModuleClosedNodes2=9,10,11,12,13,14,15 +ModuleClosedNodes3=8,9,10,11,12,13,14,15 +ModuleClosedNodes4=8,9,10,11,12,13,14,15 +ModuleClosedNodes5= +ModuleClosedNodes6= +ModuleClosedNodes7= +ModuleClosedNodes8= +NavigationStack=RDCConnector,Class_Globals,4,0,RDCConnector,GetConnection,60,0,RDCConnector,LoadConfigMap,39,0,RDCConnector,Initialize,19,6,DB1Handler,ExecuteBatch,145,0,DB1Handler,Handle,17,0,RDCConnector,GetCommand,52,6,RDCConnector,LoadSQLCommands,66,6,Main,AppStart,28,6,Main,Process_Globals,14,0 +SelectedBuild=0 +VisibleModules=1,2,3,4,7,6,8 diff --git a/reiniciaProcesoPM2.bat b/reiniciaProcesoPM2.bat new file mode 100644 index 0000000..dc1bd70 --- /dev/null +++ b/reiniciaProcesoPM2.bat @@ -0,0 +1,9 @@ +@rem Este script reinicia el proceso en PM2 del servidor de jRDC2 + +@rem estas lineas sirven para que el archivo bat corra en modo administrador. +set "params=%*" +cd /d "%~dp0" && ( if exist "%temp%\getadmin.vbs" del "%temp%\getadmin.vbs" ) && fsutil dirty query %systemdrive% 1>nul 2>nul || ( echo Set UAC = CreateObject^("Shell.Application"^) : UAC.ShellExecute "cmd.exe", "/k cd ""%~sdp0"" && ""%~s0"" %params%", "", "runas", 1 >> "%temp%\getadmin.vbs" && "%temp%\getadmin.vbs" && exit /B ) + +pm2 start RDC-Multi + +exit \ No newline at end of file diff --git a/start.bat b/start.bat new file mode 100644 index 0000000..04641ae --- /dev/null +++ b/start.bat @@ -0,0 +1,8 @@ +@rem Este script mata el proceso del servidor y despues lo reinicia, necesita los archivos stop.bat y start2.bat + +start cmd.exe /c stop.bat +timeout 2 + +start cmd.exe /c start2.bat %1 + +exit \ No newline at end of file diff --git a/start2.bat b/start2.bat new file mode 100644 index 0000000..384def3 --- /dev/null +++ b/start2.bat @@ -0,0 +1,3 @@ +@TITLE -== DBR Server %1 %2 ==- + +"C:\Program Files (x86)\Java\jdk-14\bin\java.exe" -jar jRDC_Multi.jar \ No newline at end of file diff --git a/stop.bat b/stop.bat new file mode 100644 index 0000000..f9fb157 --- /dev/null +++ b/stop.bat @@ -0,0 +1 @@ +wmic Path win32_process Where "CommandLine Like '%%jRDC_Multi.jar%%'" Call Terminate \ No newline at end of file