mirror of
https://github.com/KeymonSoft/jRDC-Multi.git
synced 2026-04-19 05:39:15 +00:00
Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9d82925dec | |||
| 2bf75cadc0 | |||
|
|
4083696bbe | ||
|
|
93becc7b0e | ||
| e32019904f | |||
| cacf9e7b89 |
16
.gitattributes
vendored
Normal file
16
.gitattributes
vendored
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
# Auto detect text files and perform LF normalization
|
||||||
|
* text=auto
|
||||||
|
|
||||||
|
# linguist-language
|
||||||
|
*.b4a linguist-language=B4X
|
||||||
|
*.b4i linguist-language=B4X
|
||||||
|
*.b4j linguist-language=B4X
|
||||||
|
*.b4r linguist-language=B4X
|
||||||
|
*.bas linguist-language=B4X
|
||||||
|
|
||||||
|
# linguist-detectable
|
||||||
|
*.b4a linguist-detectable=true
|
||||||
|
*.b4i linguist-detectable=true
|
||||||
|
*.b4j linguist-detectable=true
|
||||||
|
*.b4r linguist-detectable=true
|
||||||
|
*.bas linguist-detectable=true
|
||||||
53
ChangePassHandler.bas
Normal file
53
ChangePassHandler.bas
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
B4J=true
|
||||||
|
Group=Default Group
|
||||||
|
ModulesStructureVersion=1
|
||||||
|
Type=Class
|
||||||
|
Version=10.3
|
||||||
|
@EndOfDesignText@
|
||||||
|
'Class module: ChangePassHandler
|
||||||
|
Sub Class_Globals
|
||||||
|
Private bc As BCrypt
|
||||||
|
End Sub
|
||||||
|
|
||||||
|
Public Sub Initialize
|
||||||
|
' bc.Initialize ' <<--- CORRECCIÓN 1: Descomentado para que el objeto se cree.
|
||||||
|
End Sub
|
||||||
|
|
||||||
|
Public Sub Handle(req As ServletRequest, resp As ServletResponse)
|
||||||
|
Log("--- CHANGEPASSHANDLER FUE LLAMADO ---") ' <--- ¡PON ESTA LÍNEA AQUÍ!
|
||||||
|
If req.GetSession.GetAttribute2("user_is_authorized", False) = False Then
|
||||||
|
resp.SendRedirect("/login")
|
||||||
|
Return
|
||||||
|
End If
|
||||||
|
|
||||||
|
Dim currentUser As String = req.GetSession.GetAttribute("username")
|
||||||
|
Dim currentPass As String = req.GetParameter("current_password")
|
||||||
|
Dim newPass As String = req.GetParameter("new_password")
|
||||||
|
Dim confirmPass As String = req.GetParameter("confirm_password")
|
||||||
|
|
||||||
|
If newPass <> confirmPass Then
|
||||||
|
resp.Write("<script>alert('Error: La nueva contraseña no coincide con la confirmación.'); history.back();</script>")
|
||||||
|
Return
|
||||||
|
End If
|
||||||
|
|
||||||
|
Try
|
||||||
|
Dim storedHash As String = Main.SQL1.ExecQuerySingleResult2("SELECT password_hash FROM users WHERE username = ?", Array As String(currentUser))
|
||||||
|
|
||||||
|
Log("--- Probando con contraseña fija ---")
|
||||||
|
Log("Valor de la BD (storedHash): " & storedHash)
|
||||||
|
If storedHash = Null Or bc.checkpw("12345", storedHash) = False Then ' <<--- CAMBIO CLAVE AQUÍ
|
||||||
|
resp.Write("<script>alert('Error: La contraseña actual es incorrecta.'); history.back();</script>")
|
||||||
|
Return
|
||||||
|
End If
|
||||||
|
|
||||||
|
' <<--- CORRECCIÓN 2: Usamos el método seguro y consistente con 'Main'.
|
||||||
|
Dim newHashedPass As String = bc.hashpw(newPass, bc.gensalt)
|
||||||
|
Main.SQL1.ExecNonQuery2("UPDATE users SET password_hash = ? WHERE username = ?", Array As Object(newHashedPass, currentUser))
|
||||||
|
|
||||||
|
resp.Write("<script>alert('Contraseña actualizada correctamente.'); window.location.href='/manager';</script>")
|
||||||
|
|
||||||
|
Catch
|
||||||
|
Log(LastException)
|
||||||
|
resp.Write("<script>alert('Error del servidor al intentar cambiar la contraseña.'); history.back();</script>")
|
||||||
|
End Try
|
||||||
|
End Sub
|
||||||
320
DB1.bas
320
DB1.bas
@@ -1,320 +0,0 @@
|
|||||||
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
|
|
||||||
319
DB1Handler.bas
319
DB1Handler.bas
@@ -1,319 +0,0 @@
|
|||||||
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")
|
|
||||||
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
|
|
||||||
320
DB2Handler.bas
320
DB2Handler.bas
@@ -1,320 +0,0 @@
|
|||||||
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")
|
|
||||||
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
|
|
||||||
Log("==== ExecuteQuery2 ==== ")
|
|
||||||
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
|
|
||||||
319
DB3Handler.bas
319
DB3Handler.bas
@@ -1,319 +0,0 @@
|
|||||||
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 = 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
|
|
||||||
319
DB4Handler.bas
319
DB4Handler.bas
@@ -1,319 +0,0 @@
|
|||||||
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 = 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
|
|
||||||
@@ -378,7 +378,7 @@ Private Sub ExecuteQuery(DB As String, con As SQL, in As InputStream, resp As S
|
|||||||
Dim params As List = ReadList(in)
|
Dim params As List = ReadList(in)
|
||||||
' Obtiene la sentencia SQL.
|
' Obtiene la sentencia SQL.
|
||||||
Dim theSql As String = Connector.GetCommand(DB, queryName)
|
Dim theSql As String = Connector.GetCommand(DB, queryName)
|
||||||
Log(444 & "|" & theSql)
|
' Log(444 & "|" & theSql)
|
||||||
|
|
||||||
' <<< INICIO NUEVA VALIDACIÓN: VERIFICAR SI EL COMANDO EXISTE (V1) >>>
|
' <<< INICIO NUEVA VALIDACIÓN: VERIFICAR SI EL COMANDO EXISTE (V1) >>>
|
||||||
If theSql = Null Or theSql ="null" Or theSql.Trim = "" Then
|
If theSql = Null Or theSql ="null" Or theSql.Trim = "" Then
|
||||||
@@ -125,7 +125,7 @@ Sub Handle(req As ServletRequest, resp As ServletResponse)
|
|||||||
Dim rs As ResultSet
|
Dim rs As ResultSet
|
||||||
|
|
||||||
' Si el comando SQL contiene placeholders ('?'), significa que espera parámetros.
|
' Si el comando SQL contiene placeholders ('?'), significa que espera parámetros.
|
||||||
If sqlCommand.Contains("?") Then
|
If sqlCommand.Contains("?") or orderedParams.Size > 0 Then
|
||||||
' =================================================================
|
' =================================================================
|
||||||
' === VALIDACIÓN DE CONTEO DE PARÁMETROS ==========================
|
' === VALIDACIÓN DE CONTEO DE PARÁMETROS ==========================
|
||||||
' =================================================================
|
' =================================================================
|
||||||
@@ -134,6 +134,9 @@ Sub Handle(req As ServletRequest, resp As ServletResponse)
|
|||||||
' Obtiene cuántos parámetros se recibieron.
|
' Obtiene cuántos parámetros se recibieron.
|
||||||
Dim receivedParams As Int = orderedParams.Size
|
Dim receivedParams As Int = orderedParams.Size
|
||||||
' Compara si la cantidad de parámetros esperados y recibidos es diferente.
|
' Compara si la cantidad de parámetros esperados y recibidos es diferente.
|
||||||
|
|
||||||
|
Log($"expectedParams: ${expectedParams}, receivedParams: ${receivedParams}"$)
|
||||||
|
|
||||||
If expectedParams <> receivedParams Then
|
If expectedParams <> receivedParams Then
|
||||||
' Si no coinciden, envía un error 400 detallado.
|
' Si no coinciden, envía un error 400 detallado.
|
||||||
SendErrorResponse(resp, 400, $"Número de parametros equivocado para '${queryName}'. Se esperaban ${expectedParams} y se recibieron ${receivedParams}."$)
|
SendErrorResponse(resp, 400, $"Número de parametros equivocado para '${queryName}'. Se esperaban ${expectedParams} y se recibieron ${receivedParams}."$)
|
||||||
42
DoLoginHandler.bas
Normal file
42
DoLoginHandler.bas
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
B4J=true
|
||||||
|
Group=Default Group
|
||||||
|
ModulesStructureVersion=1
|
||||||
|
Type=Class
|
||||||
|
Version=10.3
|
||||||
|
@EndOfDesignText@
|
||||||
|
'Class module: DoLoginHandler
|
||||||
|
Sub Class_Globals
|
||||||
|
Private bc As BCrypt
|
||||||
|
End Sub
|
||||||
|
|
||||||
|
Public Sub Initialize
|
||||||
|
' bc.Initialize
|
||||||
|
End Sub
|
||||||
|
|
||||||
|
Public Sub Handle(req As ServletRequest, resp As ServletResponse)
|
||||||
|
' Limpiamos el input del usuario para evitar errores
|
||||||
|
Dim u As String = req.GetParameter("username").Trim.ToLowerCase
|
||||||
|
Dim p As String = req.GetParameter("password")
|
||||||
|
|
||||||
|
Try
|
||||||
|
' Buscamos el hash en la base de datos usando el usuario limpio
|
||||||
|
Dim storedHash As String = Main.SQL1.ExecQuerySingleResult2("SELECT password_hash FROM users WHERE username = ?", Array As String(u))
|
||||||
|
|
||||||
|
' Verificamos la contraseña contra el hash
|
||||||
|
If storedHash <> Null And bc.checkpw(p, storedHash) Then
|
||||||
|
' CREDENCIALES CORRECTAS
|
||||||
|
' 1. Autorizamos la sesión
|
||||||
|
req.GetSession.SetAttribute("user_is_authorized", True)
|
||||||
|
' 2. ¡Y guardamos el nombre de usuario! (Esta es la línea que faltaba)
|
||||||
|
req.GetSession.SetAttribute("username", u)
|
||||||
|
|
||||||
|
resp.SendRedirect("/manager")
|
||||||
|
Else
|
||||||
|
' Credenciales incorrectas
|
||||||
|
resp.SendRedirect("/login")
|
||||||
|
End If
|
||||||
|
Catch
|
||||||
|
Log(LastException)
|
||||||
|
resp.SendRedirect("/login")
|
||||||
|
End Try
|
||||||
|
End Sub
|
||||||
85
Files/config.DB2.properties
Normal file
85
Files/config.DB2.properties
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
#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
|
||||||
|
JdbcUrl=jdbc:oracle:thin:@//192.168.101.13:1521/DBKMT
|
||||||
|
|
||||||
|
# SVR-KEYMON-PRODUCCION--> Usuario
|
||||||
|
User=SALMA
|
||||||
|
Password=SALMAD2016M
|
||||||
|
|
||||||
|
#User=TORRADOCONAUTO
|
||||||
|
#Password=TORRADOCONAUTOD2016M
|
||||||
|
|
||||||
|
|
||||||
|
#--> Puertos
|
||||||
|
#SAC - DFR - MDA / GOHAN -->COBRANZA
|
||||||
|
#ServerPort=1783
|
||||||
|
#GUNA - SALMA - DURAKELO - DBC / SVR-KEYMON-PRODUCCION --> DISTRIBUIDORAS
|
||||||
|
ServerPort=9010
|
||||||
|
#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.traeConexion=select 'DB2' as conexion from dual
|
||||||
|
sql.select_soporte=select * from GUNA.soporte
|
||||||
|
sql.select_conexion=SELECT 'OK' AS VALOR FROM DUAL
|
||||||
|
sql.select_version=select cat_ve_version from cat_version
|
||||||
|
sql.select_version_GV2=select cat_ve_version from GUNA.cat_version
|
||||||
|
sql.selectAlmacen=select * from cat_almacen where cat_al_id = ?
|
||||||
|
sql.sv=select * from cat_rutas where CAT_RU_RUTA = ?
|
||||||
|
|
||||||
|
sql.update_usuario_guna_nobajas=UPDATE GUNA.CAT_LOGINS SET CAT_LO_ESTATUS = 'Activo',CAT_LO_CONECTADO ='0' WHERE CAT_LO_ESTATUS != 'Baja' and CAT_LO_USUARIO = (?)
|
||||||
|
|
||||||
|
sql.proc_usuario=BEGIN EXECUTE IMMEDIATE ('DECLARE Cursor_SYS Sys_Refcursor; BEGIN SP_ACTIVAR_USUARIO( '''||(?)||''',Cursor_SYS); end;'); END;
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
76
Files/config.DB3.properties
Normal file
76
Files/config.DB3.properties
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
#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
|
||||||
|
JdbcUrl=jdbc:oracle:thin:@//192.168.101.12: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=9010
|
||||||
|
#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.traeConexion=select 'DB3' as conexion from dual
|
||||||
|
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
|
||||||
|
|
||||||
77
Files/config.DB4.properties
Normal file
77
Files/config.DB4.properties
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
#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
|
||||||
|
JdbcUrl=jdbc:oracle:thin:@//192.168.101.13:1521/DBKMT
|
||||||
|
|
||||||
|
# SVR-KEYMON-PRODUCCION--> Usuario
|
||||||
|
User=SALMA
|
||||||
|
Password=SALMAD2016M
|
||||||
|
|
||||||
|
#User=TORRADOCONAUTO
|
||||||
|
#Password=TORRADOCONAUTOD2016M
|
||||||
|
|
||||||
|
|
||||||
|
#--> Puertos
|
||||||
|
#SAC - DFR - MDA / GOHAN -->COBRANZA
|
||||||
|
#ServerPort=1783
|
||||||
|
#GUNA - SALMA - DURAKELO - DBC / SVR-KEYMON-PRODUCCION --> DISTRIBUIDORAS
|
||||||
|
ServerPort=9000
|
||||||
|
#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.traeConexion=select 'DB4' as conexion from dual
|
||||||
|
sql.select_soporte=select * from GUNA.soporte
|
||||||
|
sql.select_conexion=SELECT 'OK' AS VALOR FROM DUAL
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
@@ -1,29 +1,57 @@
|
|||||||
#Lines starting with '#' are comments.
|
#Lines starting with '#' are comments.
|
||||||
#Backslash character at the end of line means that the command continues in the next line.
|
#Backslash character at the end of line means that the command continues in the next line.
|
||||||
|
|
||||||
#DATABASE CONFIGURATION
|
DriverClass=oracle.jdbc.driver.OracleDriver
|
||||||
DriverClass=com.mysql.jdbc.Driver
|
#JdbcUrl=jdbc:mysql://localhost/test?characterEncoding=utf8
|
||||||
JdbcUrl=jdbc:mysql://localhost/test?characterEncoding=utf8
|
|
||||||
User=root
|
|
||||||
Password=
|
|
||||||
#Java server port
|
|
||||||
ServerPort=17178
|
|
||||||
|
|
||||||
#example of MS SQL Server configuration:
|
#SQL Server
|
||||||
#DriverClass=net.sourceforge.jtds.jdbc.Driver
|
#DriverClass=net.sourceforge.jtds.jdbc.Driver
|
||||||
#JdbcUrl=jdbc:jtds:sqlserver://<server address>/<database>
|
|
||||||
|
|
||||||
#example of postegres configuration:
|
# este para produccion GHAN JdbcUrl=jdbc:oracle:thin:@//192.168.15.53:1521/DBKMT
|
||||||
#JdbcUrl=jdbc:postgresql://localhost/test
|
#GOHAN ---> server
|
||||||
#DriverClass=org.postgresql.Driver
|
#JdbcUrl=jdbc:oracle:thin:@//10.0.0.205:1521/DBKMT
|
||||||
|
#JdbcUrl=jdbc:oracle:thin:@//10.0.0.236:1521/DBKMT
|
||||||
|
JdbcUrl=jdbc:oracle:thin:@//192.168.101.10:1521/DBKMT?oracle.jdbc.defaultClientIdentifier=jRDC_Multi
|
||||||
|
|
||||||
|
|
||||||
|
# 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=9010
|
||||||
|
#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
|
#SQL COMMANDS
|
||||||
sql.create_table=CREATE TABLE IF NOT EXISTS animals (\
|
|
||||||
id INTEGER PRIMARY KEY AUTO_INCREMENT,\
|
##################
|
||||||
name CHAR(30) NOT NULL,\
|
#################
|
||||||
image BLOB)
|
################ S O P O R T E
|
||||||
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.select_revisaClienteCredito_GUNA2=select (select count(CAT_CL_CODIGO) from GUNA.CAT_CLIENTES where CAT_CL_CODIGO = ? and CAT_CL_IDALMACEN <> '100') as cuantos, (select count(ID_CLIENTE) from GUNA.CAT_CLIENTES_CREDITO where ID_CLIENTE = ?) as cuantosCredito from DUAL
|
||||||
sql.insert=INSERT INTO article VALUES(?, ?)
|
|
||||||
|
sql.traeConexion=select 'DB1' as conexion from dual
|
||||||
|
sql.traeConexion2=select 'DB1' as conexion from dual
|
||||||
|
sql.select_soporte=select * from GUNA.soporte
|
||||||
|
sql.select_conexion=SELECT 'OK' AS VALOR FROM DUAL
|
||||||
|
sql.selectAlmacen=select cat_al_id, cat_al_desc, cat_al_archftp from cat_almacen where cat_al_id = ?
|
||||||
|
sql.select_version=select cat_ve_version from cat_version
|
||||||
|
sql.select_version_GV2=select cat_ve_version from GUNA.cat_version
|
||||||
|
|
||||||
|
sql.update_usuario_guna_nobajas=UPDATE GUNA.CAT_LOGINS SET CAT_LO_ESTATUS = 'Activo',CAT_LO_CONECTADO ='0' WHERE CAT_LO_ESTATUS != 'Baja' and CAT_LO_USUARIO = (?)
|
||||||
|
|
||||||
|
sql.proc_usuario=BEGIN EXECUTE IMMEDIATE ('DECLARE Cursor_SYS Sys_Refcursor; BEGIN SP_ACTIVAR_USUARIO( '''||(?)||''',Cursor_SYS); end;'); END;
|
||||||
|
|||||||
21
Files/login.html
Normal file
21
Files/login.html
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="es">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>Login jRDC Server</title>
|
||||||
|
<style>
|
||||||
|
body { font-family: sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f0f0f0; }
|
||||||
|
form { background: white; padding: 2em; border-radius: 8px; box-shadow: 0 4px 8px rgba(0,0,0,0.1); }
|
||||||
|
input { display: block; margin-bottom: 1em; padding: 0.5em; width: 200px; }
|
||||||
|
button { padding: 0.7em; width: 100%; border: none; background-color: #007bff; color: white; cursor: pointer; border-radius: 4px; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<form action="/dologin" method="post">
|
||||||
|
<h2>Acceso al Manager</h2>
|
||||||
|
<input type="text" name="username" placeholder="Usuario" required>
|
||||||
|
<input type="password" name="password" placeholder="Contraseña" required>
|
||||||
|
<button type="submit">Entrar</button>
|
||||||
|
</form>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
9
Files/reiniciaProcesoBow.bat
Normal file
9
Files/reiniciaProcesoBow.bat
Normal file
@@ -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 restart BotSoporte_4.0
|
||||||
|
|
||||||
|
exit
|
||||||
@@ -4,6 +4,6 @@
|
|||||||
set "params=%*"
|
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 )
|
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
|
pm2 restart jRDC-Multi
|
||||||
|
|
||||||
exit
|
exit
|
||||||
21
Files/www/login.html
Normal file
21
Files/www/login.html
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="es">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>Login jRDC Server</title>
|
||||||
|
<style>
|
||||||
|
body { font-family: sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f0f0f0; }
|
||||||
|
form { background: white; padding: 2em; border-radius: 8px; box-shadow: 0 4px 8px rgba(0,0,0,0.1); }
|
||||||
|
input { display: block; margin-bottom: 1em; padding: 0.5em; width: 200px; }
|
||||||
|
button { padding: 0.7em; width: 100%; border: none; background-color: #007bff; color: white; cursor: pointer; border-radius: 4px; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<form action="/dologin" method="post">
|
||||||
|
<h2>Acceso al Manager</h2>
|
||||||
|
<input type="text" name="username" placeholder="Usuario" required>
|
||||||
|
<input type="password" name="password" placeholder="Contraseña" required>
|
||||||
|
<button type="submit">Entrar</button>
|
||||||
|
</form>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
23
LoginHandler.bas
Normal file
23
LoginHandler.bas
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
B4J=true
|
||||||
|
Group=Default Group
|
||||||
|
ModulesStructureVersion=1
|
||||||
|
Type=Class
|
||||||
|
Version=10.3
|
||||||
|
@EndOfDesignText@
|
||||||
|
'Class module: LoginHandler
|
||||||
|
Sub Class_Globals
|
||||||
|
End Sub
|
||||||
|
|
||||||
|
Public Sub Initialize
|
||||||
|
End Sub
|
||||||
|
|
||||||
|
Public Sub Handle(req As ServletRequest, resp As ServletResponse)
|
||||||
|
resp.ContentType = "text/html"
|
||||||
|
' Suponiendo que el archivo login.html está en la carpeta www de tu proyecto
|
||||||
|
Try
|
||||||
|
resp.Write(File.ReadString(File.DirApp, "www/login.html"))
|
||||||
|
Catch
|
||||||
|
Log("Error: No se encontró el archivo www/login.html")
|
||||||
|
resp.Write("Error: Archivo de login no encontrado.")
|
||||||
|
End Try
|
||||||
|
End Sub
|
||||||
17
LogoutHandler.bas
Normal file
17
LogoutHandler.bas
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
B4J=true
|
||||||
|
Group=Default Group
|
||||||
|
ModulesStructureVersion=1
|
||||||
|
Type=Class
|
||||||
|
Version=10.3
|
||||||
|
@EndOfDesignText@
|
||||||
|
'Class module: LogoutHandler
|
||||||
|
Sub Class_Globals
|
||||||
|
End Sub
|
||||||
|
|
||||||
|
Public Sub Initialize
|
||||||
|
End Sub
|
||||||
|
|
||||||
|
Public Sub Handle(req As ServletRequest, resp As ServletResponse)
|
||||||
|
req.GetSession.Invalidate ' Cierra la sesión
|
||||||
|
resp.SendRedirect("/login") ' Manda al usuario a la página de login
|
||||||
|
End Sub
|
||||||
327
Manager.bas
327
Manager.bas
@@ -15,120 +15,289 @@ Public Sub Initialize
|
|||||||
End Sub
|
End Sub
|
||||||
|
|
||||||
Sub Handle(req As ServletRequest, resp As ServletResponse)
|
Sub Handle(req As ServletRequest, resp As ServletResponse)
|
||||||
|
' 1. --- Bloque de Seguridad ---
|
||||||
|
If req.GetSession.GetAttribute2("user_is_authorized", False) = False Then
|
||||||
|
resp.SendRedirect("/login")
|
||||||
|
Return
|
||||||
|
End If
|
||||||
|
|
||||||
Dim Command As String = req.GetParameter("command")
|
Dim Command As String = req.GetParameter("command")
|
||||||
|
If Command = "" Then Command = "ping"
|
||||||
Log($"Command: ${Command}"$)
|
Log($"Command: ${Command}"$)
|
||||||
|
|
||||||
|
' --- MANEJO ESPECIAL PARA SNAPSHOT ---
|
||||||
|
' El comando "snapshot" no devuelve HTML, sino una imagen. Lo manejamos por separado al principio.
|
||||||
|
If Command = "snapshot" Then
|
||||||
|
Try
|
||||||
|
resp.ContentType = "image/png"
|
||||||
|
Dim robot, toolkit As JavaObject
|
||||||
|
robot.InitializeNewInstance("java.awt.Robot", Null)
|
||||||
|
toolkit.InitializeStatic("java.awt.Toolkit")
|
||||||
|
Dim screenRect As JavaObject
|
||||||
|
screenRect.InitializeNewInstance("java.awt.Rectangle", Array As Object( _
|
||||||
|
toolkit.RunMethodJO("getDefaultToolkit", Null).RunMethod("getScreenSize", Null)))
|
||||||
|
Dim image As JavaObject = robot.RunMethod("createScreenCapture", Array As Object(screenRect))
|
||||||
|
Dim ImageIO As JavaObject
|
||||||
|
ImageIO.InitializeStatic("javax.imageio.ImageIO").RunMethod("write", Array As Object(image, "png", resp.OutputStream))
|
||||||
|
Catch
|
||||||
|
resp.SendError(500, LastException.Message)
|
||||||
|
End Try
|
||||||
|
Return ' Detenemos la ejecución aquí para no enviar más HTML.
|
||||||
|
End If
|
||||||
|
' --- FIN DE MANEJO ESPECIAL ---
|
||||||
|
|
||||||
|
' Para todos los demás comandos, construimos la página HTML
|
||||||
resp.ContentType = "text/html"
|
resp.ContentType = "text/html"
|
||||||
If Command = "reload" Then 'Reload config.properties
|
Dim sb As StringBuilder
|
||||||
' rdcc.Initialize
|
sb.Initialize
|
||||||
|
|
||||||
|
' --- Estilos y JavaScript (igual que antes) ---
|
||||||
|
sb.Append("<html><head><style>")
|
||||||
|
sb.Append("body {font-family: sans-serif; margin: 2em; background-color: #f9f9f9;} ")
|
||||||
|
sb.Append("h1, h2 {color: #333;} hr {margin: 2em 0; border: 0; border-top: 1px solid #ddd;} ")
|
||||||
|
sb.Append("input {display: block; width: 95%; padding: 8px; margin-bottom: 10px; border: 1px solid #ccc; border-radius: 4px;} ")
|
||||||
|
sb.Append("button {padding: 10px 15px; border: none; background-color: #007bff; color: white; cursor: pointer; border-radius: 4px; margin-right: 1em;} ")
|
||||||
|
sb.Append(".nav a, .logout a {text-decoration: none; margin-right: 10px; color: #007bff;} ")
|
||||||
|
sb.Append(".output {background: #fff; padding: 1em; border: 1px solid #eee; border-radius: 8px; font-family: monospace; white-space: pre-wrap; word-wrap: break-word;} ")
|
||||||
|
sb.Append("#changePassForm {background: #f0f0f0; padding: 1.5em; border-radius: 8px; max-width: 400px; margin-top: 1em;} ")
|
||||||
|
sb.Append("</style>")
|
||||||
|
sb.Append("<script>function toggleForm() {var form = document.getElementById('changePassForm'); if (form.style.display === 'none') {form.style.display = 'block';} else {form.style.display = 'none';}}</script>")
|
||||||
|
sb.Append("</head><body>")
|
||||||
|
|
||||||
|
' --- Cabecera, Botón y Formulario Oculto (igual que antes) ---
|
||||||
|
sb.Append("<h1>Panel de Administración jRDC</h1>")
|
||||||
|
sb.Append($"Bienvenido, <b>${req.GetSession.GetAttribute("username")}</b><br>"$)
|
||||||
|
sb.Append("<p class='nav'><a href='/manager?command=test'>Test</a> | <a href='/manager?command=ping'>Ping</a> | <a href='/manager?command=reload'>Reload</a> | <a href='/manager?command=rpm2'>Reiniciar (pm2)</a> | <a href='/manager?command=reviveBow'>Revive Bow</a></p><hr>")
|
||||||
|
' sb.Append("<button onclick='toggleForm()'>Cambiar Contraseña</button>")
|
||||||
|
sb.Append("<div id='changePassForm' style='display:none;'>")
|
||||||
|
sb.Append("<h2>Cambiar Contraseña</h2><form action='/changepass' method='post'>")
|
||||||
|
sb.Append("Contraseña Actual: <input type='password' name='current_password' required><br>")
|
||||||
|
sb.Append("Nueva Contraseña: <input type='password' name='new_password' required><br>")
|
||||||
|
sb.Append("Confirmar Nueva Contraseña: <input type='password' name='confirm_password' required><br>")
|
||||||
|
sb.Append("<button type='submit'>Actualizar Contraseña</button> <button onclick='toggleForm()'>Cancelar</button></form></div>")
|
||||||
|
|
||||||
|
' --- Resultado del Comando ---
|
||||||
|
sb.Append("<h2>Resultado del Comando: '" & Command & "'</h2>")
|
||||||
|
sb.Append("<div class='output'>")
|
||||||
|
|
||||||
|
' =========================================================================
|
||||||
|
' ### INICIO DE TU LÓGICA DE COMANDOS INTEGRADA ###
|
||||||
|
' =========================================================================
|
||||||
|
If Command = "reload" Then
|
||||||
Private estaDB As String = ""
|
Private estaDB As String = ""
|
||||||
' Log(Main.listaDeCP)
|
|
||||||
resp.Write($"<a href="/test">Test</a> | <a href="/manager?command=reload">Reload</a> | <br/>"$)
|
|
||||||
For i = 0 To Main.listaDeCP.Size - 1
|
For i = 0 To Main.listaDeCP.Size - 1
|
||||||
Main.Connectors.Get(Main.listaDeCP.get(i)).As(RDCConnector).Initialize(Main.listaDeCP.get(i))
|
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 = ""
|
If Main.listaDeCP.get(i) <> "DB1" Then estaDB = "." & Main.listaDeCP.get(i) Else estaDB = ""
|
||||||
resp.Write($"Recargando config${estaDB}.properties ($DateTime{DateTime.Now})<br/>"$)
|
sb.Append($"Recargando config${estaDB}.properties ($DateTime{DateTime.Now})<br/>"$)
|
||||||
resp.Write($"Queries en config.properties: <b>${Main.Connectors.Get(Main.listaDeCP.get(i)).As(RDCConnector).commands.Size}</b><br/>"$)
|
sb.Append($"Queries en config.properties: <b>${Main.Connectors.Get(Main.listaDeCP.get(i)).As(RDCConnector).commands.Size}</b><br/>"$)
|
||||||
resp.Write($"<b>JdbcUrl:</b> ${Main.Connectors.Get(Main.listaDeCP.get(i)).As(RDCConnector).config.Get("JdbcUrl")}</b><br/>"$)
|
sb.Append($"<b>JdbcUrl:</b> ${Main.Connectors.Get(Main.listaDeCP.get(i)).As(RDCConnector).config.Get("JdbcUrl")}</b><br/>"$)
|
||||||
resp.Write($"<b>User:</b> ${Main.Connectors.Get(Main.listaDeCP.get(i)).As(RDCConnector).config.Get("User")}</b><br/>"$)
|
sb.Append($"<b>User:</b> ${Main.Connectors.Get(Main.listaDeCP.get(i)).As(RDCConnector).config.Get("User")}</b><br/>"$)
|
||||||
resp.Write($"<b>ServerPort:</b> ${Main.srvr.Port}</b><br/><br/>"$)
|
sb.Append($"<b>ServerPort:</b> ${Main.srvr.Port}</b><br/><br/>"$)
|
||||||
Next
|
Next
|
||||||
' Public shl As Shell
|
Else If Command = "test" Then
|
||||||
' shl.Initialize("shl11","cmd",Array("/c","restart.bat"))
|
Try
|
||||||
' shl.WorkingDirectory = GlobalParameters.WorkingDirectory
|
Dim con As SQL = Main.Connectors.Get("DB1").As(RDCConnector).GetConnection("")
|
||||||
' shl.Run(-1)
|
sb.Append("Connection successful.</br></br>")
|
||||||
else If Command = "stop" Then
|
Private estaDB As String = ""
|
||||||
' Public shl As Shell
|
Log(Main.listaDeCP)
|
||||||
' shl.Initialize("shl","cmd",Array("/c","stop.bat"))
|
For i = 0 To Main.listaDeCP.Size - 1
|
||||||
' shl.WorkingDirectory = GlobalParameters.WorkingDirectory
|
If Main.listaDeCP.get(i) <> "" Then estaDB = "." & Main.listaDeCP.get(i)
|
||||||
' shl.Run(-1)
|
sb.Append($"Using config${estaDB}.properties<br/>"$)
|
||||||
else If Command = "rsx" Then 'Reiniciamos el servidor DBReq
|
Next
|
||||||
resp.Write($"<a href="/test">Test</a> | <a href="/manager?command=reload">Reload</a> | <br/>"$)
|
con.Close
|
||||||
|
Catch
|
||||||
|
resp.Write("Error fetching connection.")
|
||||||
|
End Try
|
||||||
|
Else If Command = "stop" Then
|
||||||
|
' Public shl As Shell...
|
||||||
|
Else If Command = "rsx" Then
|
||||||
Log($"Ejecutamos ${File.DirApp}\start.bat"$)
|
Log($"Ejecutamos ${File.DirApp}\start.bat"$)
|
||||||
resp.Write($"Ejecutamos ${File.DirApp}\start.bat"$)
|
sb.Append($"Ejecutamos ${File.DirApp}\start.bat"$)
|
||||||
Public shl As Shell
|
Public shl As Shell
|
||||||
shl.Initialize("shl","cmd",Array("/c",File.DirApp & "\start.bat " & Main.srvr.Port))
|
shl.Initialize("shl","cmd",Array("/c",File.DirApp & "\start.bat " & Main.srvr.Port))
|
||||||
shl.WorkingDirectory = File.DirApp
|
shl.WorkingDirectory = File.DirApp
|
||||||
shl.Run(-1)
|
shl.Run(-1)
|
||||||
else If Command = "rpm2" Then 'Reiniciamos el proceso DBReq en PM2
|
Else If Command = "rpm2" Then
|
||||||
resp.Write($"<a href="/test">Test</a> | <a href="/manager?command=reload">Reload</a> | <br/>"$)
|
|
||||||
Log($"Ejecutamos ${File.DirApp}\reiniciaProcesoPM2.bat"$)
|
Log($"Ejecutamos ${File.DirApp}\reiniciaProcesoPM2.bat"$)
|
||||||
resp.Write($"Ejecutamos ${File.DirApp}\reiniciaProcesoPM2.bat"$)
|
sb.Append($"Ejecutamos ${File.DirApp}\reiniciaProcesoPM2.bat"$)
|
||||||
Public shl As Shell
|
Public shl As Shell
|
||||||
shl.Initialize("shl","cmd",Array("/c",File.DirApp & "\reiniciaProcesoPM2.bat " & Main.srvr.Port))
|
shl.Initialize("shl","cmd",Array("/c",File.DirApp & "\reiniciaProcesoPM2.bat " & Main.srvr.Port))
|
||||||
shl.WorkingDirectory = File.DirApp
|
shl.WorkingDirectory = File.DirApp
|
||||||
shl.Run(-1)
|
shl.Run(-1)
|
||||||
else If Command = "paused" Then
|
Else If Command = "reviveBow" Then
|
||||||
|
Log($"Ejecutamos ${File.DirApp}\reiniciaProcesoBow.bat"$)
|
||||||
|
sb.Append($"Ejecutamos ${File.DirApp}\reiniciaProcesoBow.bat<br><br>"$)
|
||||||
|
sb.Append($"!!!BOW REINICIANDO!!!"$)
|
||||||
|
Public shl As Shell
|
||||||
|
shl.Initialize("shl","cmd",Array("/c",File.DirApp & "\reiniciaProcesoBow.bat " & Main.srvr.Port))
|
||||||
|
shl.WorkingDirectory = File.DirApp
|
||||||
|
shl.Run(-1)
|
||||||
|
Else If Command = "paused" Then
|
||||||
GlobalParameters.IsPaused = 1
|
GlobalParameters.IsPaused = 1
|
||||||
else If Command = "continue" Then
|
sb.Append("Servidor pausado.")
|
||||||
|
Else If Command = "continue" Then
|
||||||
GlobalParameters.IsPaused = 0
|
GlobalParameters.IsPaused = 0
|
||||||
else If Command = "logs" Then
|
sb.Append("Servidor reanudado.")
|
||||||
|
Else If Command = "logs" Then
|
||||||
If GlobalParameters.mpLogs.IsInitialized Then
|
If GlobalParameters.mpLogs.IsInitialized Then
|
||||||
j.Initialize(GlobalParameters.mpLogs)
|
j.Initialize(GlobalParameters.mpLogs)
|
||||||
j.ToString
|
sb.Append(j.ToString)
|
||||||
resp.Write(j.ToString)
|
|
||||||
End If
|
End If
|
||||||
else If Command = "block" Then
|
Else If Command = "block" Then
|
||||||
Dim BlockedConIP As String = req.GetParameter("IP")
|
Dim BlockedConIP As String = req.GetParameter("IP")
|
||||||
If GlobalParameters.mpBlockConnection.IsInitialized Then
|
If GlobalParameters.mpBlockConnection.IsInitialized Then
|
||||||
GlobalParameters.mpBlockConnection.Put(BlockedConIP,BlockedConIP)
|
GlobalParameters.mpBlockConnection.Put(BlockedConIP, BlockedConIP)
|
||||||
|
sb.Append("IP bloqueada: " & BlockedConIP)
|
||||||
End If
|
End If
|
||||||
else If Command = "unblock" Then
|
Else If Command = "unblock" Then
|
||||||
Dim UnBlockedConIP As String = req.GetParameter("IP")
|
Dim UnBlockedConIP As String = req.GetParameter("IP")
|
||||||
If GlobalParameters.mpBlockConnection.IsInitialized Then
|
If GlobalParameters.mpBlockConnection.IsInitialized Then
|
||||||
GlobalParameters.mpBlockConnection.Remove(UnBlockedConIP)
|
GlobalParameters.mpBlockConnection.Remove(UnBlockedConIP)
|
||||||
|
sb.Append("IP desbloqueada: " & UnBlockedConIP)
|
||||||
End If
|
End If
|
||||||
else if Command = "restartserver" Then
|
Else If Command = "restartserver" Then
|
||||||
Log($"Ejecutamos ${File.DirApp}/restarServer.bat"$)
|
Log($"Ejecutamos ${File.DirApp}/restarServer.bat"$)
|
||||||
' Public shl As Shell
|
sb.Append("Reiniciando servidor...")
|
||||||
' shl.Initialize("shl","cmd",Array("/c","retartserver.bat"))
|
Else If Command = "runatstartup" Then
|
||||||
' shl.WorkingDirectory = GlobalParameters.WorkingDirectory
|
File.Copy("C:\jrdcinterface", "startup.bat", "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp", "startup.bat")
|
||||||
' shl.Run(-1)
|
sb.Append("Script de inicio añadido.")
|
||||||
else if Command = "snapshot" Then
|
Else If Command = "stoprunatstartup" Then
|
||||||
Try
|
File.Delete("C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp", "startup.bat")
|
||||||
resp.ContentType = "image/png"
|
sb.Append("Script de inicio eliminado.")
|
||||||
Dim robot, toolkit, rectangle, ImageIO As JavaObject
|
Else If Command = "totalrequests" Then
|
||||||
robot.InitializeNewInstance("java.awt.Robot", Null)
|
If GlobalParameters.mpTotalRequests.IsInitialized Then
|
||||||
toolkit.InitializeStatic("java.awt.Toolkit")
|
j.Initialize(GlobalParameters.mpTotalRequests)
|
||||||
Dim rectangle As JavaObject
|
sb.Append(j.ToString)
|
||||||
rectangle.InitializeNewInstance("java.awt.Rectangle", Array As Object( _
|
End If
|
||||||
toolkit.RunMethodJO("getDefaultToolkit", Null).RunMethod("getScreenSize", Null)))
|
Else If Command = "totalblocked" Then
|
||||||
Dim image As JavaObject = robot.RunMethod("createScreenCapture", Array As Object(rectangle))
|
If GlobalParameters.mpBlockConnection.IsInitialized Then
|
||||||
ImageIO.InitializeStatic("javax.imageio.ImageIO").RunMethod("write", Array As Object( _
|
' j.Initialize(Global.mpBlockConnection)
|
||||||
image, "png", resp.OutputStream)) 'the image is written to the response
|
sb.Append(j.ToString)
|
||||||
Catch
|
End If
|
||||||
resp.SendError(500, LastException.Message)
|
Else If Command = "totalcon" Then
|
||||||
End Try
|
If GlobalParameters.mpTotalConnections.IsInitialized Then
|
||||||
else if Command = "runatstartup" Then
|
j.Initialize(GlobalParameters.mpTotalConnections)
|
||||||
'----- You Need to go to the folder on the server : C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp
|
sb.Append(j.ToString)
|
||||||
' ------ then right click - Properties - Security - Edit - Add --> "Everyone" then OK -- then check Full Control (Allow) -- OK
|
End If
|
||||||
File.Copy("C:\jrdcinterface","startup.bat","C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp","startup.bat")
|
Else If Command = "ping" Then
|
||||||
else if Command = "stoprunatstartup" Then
|
sb.Append($"Pong ($DateTime{DateTime.Now})"$)
|
||||||
'----- You Need to go to the folder on the server : C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp
|
End If
|
||||||
' ------ 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")
|
' ### FIN DE TU LÓGICA DE COMANDOS ###
|
||||||
|
' =========================================================================
|
||||||
|
|
||||||
|
' --- Cerramos la página y la enviamos ---
|
||||||
|
sb.Append("</div><p class='logout'><a href='/logout'>Cerrar Sesión</a> | <a href=# onclick='toggleForm()'>Cambiar Contraseña</a></p></body></html>")
|
||||||
|
resp.Write(sb.ToString)
|
||||||
|
|
||||||
|
If GlobalParameters.mpLogs.IsInitialized Then GlobalParameters.mpLogs.Put(Command, "Manager : " & Command & " - Time : " & DateTime.Time(DateTime.Now))
|
||||||
|
End Sub
|
||||||
|
|
||||||
|
Sub Handle0(req As ServletRequest, resp As ServletResponse)
|
||||||
|
' 1. --- Bloque de Seguridad (se mantiene igual) ---
|
||||||
|
If req.GetSession.GetAttribute2("user_is_authorized", False) = False Then
|
||||||
|
resp.SendRedirect("/login")
|
||||||
|
Return
|
||||||
|
End If
|
||||||
|
|
||||||
|
Dim Command As String = req.GetParameter("command")
|
||||||
|
If Command = "" Then Command = "ping"
|
||||||
|
Log($"Command: ${Command}"$)
|
||||||
|
resp.ContentType = "text/html"
|
||||||
|
|
||||||
|
' 2. --- Construimos la ESTRUCTURA de la página ---
|
||||||
|
Dim sb As StringBuilder
|
||||||
|
sb.Initialize
|
||||||
|
|
||||||
|
' Estilos para la página
|
||||||
|
sb.Append("<html><head><style>")
|
||||||
|
sb.Append("body {font-family: sans-serif; margin: 2em; background-color: #f9f9f9;} ")
|
||||||
|
sb.Append("h1, h2 {color: #333;} hr {margin: 2em 0; border: 0; border-top: 1px solid #ddd;} ")
|
||||||
|
sb.Append("form {background: #f0f0f0; padding: 1.5em; border-radius: 8px; max-width: 400px; margin-bottom: 2em;} ")
|
||||||
|
sb.Append("input {display: block; width: 95%; padding: 8px; margin-bottom: 10px; border: 1px solid #ccc; border-radius: 4px;} ")
|
||||||
|
sb.Append("button {padding: 10px 15px; border: none; background-color: #007bff; color: white; cursor: pointer; border-radius: 4px;} ")
|
||||||
|
sb.Append(".nav a, .logout a {text-decoration: none; margin-right: 10px; color: #007bff;} ")
|
||||||
|
sb.Append(".output {background: #fff; padding: 1em; border: 1px solid #eee; border-radius: 8px;} ")
|
||||||
|
sb.Append("</style></head><body>")
|
||||||
|
|
||||||
|
' Cabecera y bienvenida
|
||||||
|
sb.Append("<h1>Panel de Administración jRDC</h1>")
|
||||||
|
sb.Append($"Bienvenido, <b>${req.GetSession.GetAttribute("username")}</b><br>"$)
|
||||||
|
|
||||||
|
' Menú de navegación (se define una sola vez)
|
||||||
|
sb.Append("<p class='nav'>")
|
||||||
|
sb.Append($"<a href="/test">Test</a> | <a href="/manager?command=ping">Ping</a> | <a href="/manager?command=reload">Reload</a> | <a href="/manager?command=rpm2">Reiniciar (pm2)</a> | <a href="/manager?command=reviveBow">Revive Bow</a>"$)
|
||||||
|
sb.Append("</p>")
|
||||||
|
|
||||||
|
' Formulario para cambiar contraseña
|
||||||
|
sb.Append("<hr>")
|
||||||
|
sb.Append("<h2>Cambiar Contraseña</h2>")
|
||||||
|
sb.Append("<form action='/changepass' method='post'>")
|
||||||
|
sb.Append("Contraseña Actual: <input type='password' name='current_password' required><br>")
|
||||||
|
sb.Append("Nueva Contraseña: <input type='password' name='new_password' required><br>")
|
||||||
|
sb.Append("Confirmar Nueva Contraseña: <input type='password' name='confirm_password' required><br>")
|
||||||
|
sb.Append("<button type='submit'>Actualizar Contraseña</button>")
|
||||||
|
sb.Append("</form>")
|
||||||
|
|
||||||
|
' Sección para el resultado del comando
|
||||||
|
sb.Append("<hr><h2>Resultado del Comando: '" & Command & "'</h2>")
|
||||||
|
sb.Append("<div class='output'>")
|
||||||
|
|
||||||
|
' 3. --- Lógica de TUS COMANDOS (modificada para usar sb.Append) ---
|
||||||
|
If Command = "reload" Then
|
||||||
|
Private estaDB As String = ""
|
||||||
|
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 = ""
|
||||||
|
sb.Append($"Recargando config${estaDB}.properties ($DateTime{DateTime.Now})<br/>"$)
|
||||||
|
sb.Append($"Queries en config.properties: <b>${Main.Connectors.Get(Main.listaDeCP.get(i)).As(RDCConnector).commands.Size}</b><br/>"$)
|
||||||
|
sb.Append($"<b>JdbcUrl:</b> ${Main.Connectors.Get(Main.listaDeCP.get(i)).As(RDCConnector).config.Get("JdbcUrl")}</b><br/>"$)
|
||||||
|
sb.Append($"<b>User:</b> ${Main.Connectors.Get(Main.listaDeCP.get(i)).As(RDCConnector).config.Get("User")}</b><br/>"$)
|
||||||
|
sb.Append($"<b>ServerPort:</b> ${Main.srvr.Port}</b><br/><br/>"$)
|
||||||
|
Next
|
||||||
|
else If Command = "stop" Then
|
||||||
|
' Tu código para "stop"
|
||||||
|
else If Command = "rsx" Then
|
||||||
|
Log($"Ejecutamos ${File.DirApp}\start.bat"$)
|
||||||
|
sb.Append($"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
|
||||||
|
Log($"Ejecutamos ${File.DirApp}\reiniciaProcesoPM2.bat"$)
|
||||||
|
sb.Append($"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 = "reviveBow" Then
|
||||||
|
Log($"Ejecutamos ${File.DirApp}\reiniciaProcesoBow.bat"$)
|
||||||
|
sb.Append($"Ejecutamos ${File.DirApp}\reiniciaProcesoBow.bat<br><br>"$)
|
||||||
|
sb.Append($"!!!BOW REINICIANDO!!!"$)
|
||||||
|
Public shl As Shell
|
||||||
|
shl.Initialize("shl","cmd",Array("/c",File.DirApp & "\reiniciaProcesoBow.bat " & Main.srvr.Port))
|
||||||
|
shl.WorkingDirectory = File.DirApp
|
||||||
|
shl.Run(-1)
|
||||||
else if Command = "totalrequests" Then
|
else if Command = "totalrequests" Then
|
||||||
If GlobalParameters.mpTotalRequests.IsInitialized Then
|
If GlobalParameters.mpTotalRequests.IsInitialized Then
|
||||||
j.Initialize(GlobalParameters.mpTotalRequests)
|
j.Initialize(GlobalParameters.mpTotalRequests)
|
||||||
j.ToString
|
sb.Append(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
|
||||||
|
else if Command = "ping" Then
|
||||||
|
sb.Append($"Pong ($DateTime{DateTime.Now})"$)
|
||||||
End If
|
End If
|
||||||
|
'...(aquí continuaría el resto de tus Else If)...
|
||||||
|
|
||||||
|
|
||||||
|
' 4. --- Cerramos la página y la enviamos TODA JUNTA ---
|
||||||
|
sb.Append("</div>") ' Cierre de div.output
|
||||||
|
sb.Append("<p class='logout'><a href='/logout'>Cerrar Sesión</a></p>")
|
||||||
|
sb.Append("</body></html>")
|
||||||
|
|
||||||
|
resp.Write(sb.ToString) ' Se envía toda la página de una vez
|
||||||
|
|
||||||
|
' Lógica final de logs (se mantiene igual)
|
||||||
If GlobalParameters.mpLogs.IsInitialized Then GlobalParameters.mpLogs.Put(Command, "Manager : " & Command & " - Time : " & DateTime.Time(DateTime.Now))
|
If GlobalParameters.mpLogs.IsInitialized Then GlobalParameters.mpLogs.Put(Command, "Manager : " & Command & " - Time : " & DateTime.Time(DateTime.Now))
|
||||||
End Sub
|
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
|
|
||||||
|
|||||||
135
README.md
135
README.md
@@ -1,41 +1,136 @@
|
|||||||
# Servidor jRDC2-Multi Modificado (B4J)
|
# **Servidor jRDC2-Multi Mod (B4J)**
|
||||||
|
|
||||||
## 1. Introducción
|
## **1\. Introducción**
|
||||||
|
|
||||||
Este proyecto es una versión modificada del servidor [jRDC2 original](https://www.b4x.com/android/forum/threads/b4x-jrdc2-b4j-implementation-of-rdc-remote-database-connector.61801/#content), diseñada para actuar como un backend robusto y flexible. Su función principal es recibir peticiones HTTP, ejecutar comandos SQL predefinidos contra una base de datos y devolver los resultados en un formato estructurado.
|
Este proyecto es una versión modificada del servidor [jRDC2 original](https://www.b4x.com/android/forum/threads/b4x-jrdc2-b4j-implementation-of-rdc-remote-database-connector.61801/#content), diseñada para actuar como un backend robusto y flexible. Su función principal es recibir peticiones HTTP, ejecutar comandos SQL predefinidos contra una base de datos y devolver los resultados en un formato estructurado.
|
||||||
|
|
||||||
Ha sido adaptado para servir tanto a clientes nativos (B4A/B4i) como a clientes web modernos (JavaScript, a través de frameworks como React, Vue, Angular, etc.).
|
Ha sido adaptado para servir tanto a clientes nativos (`B4A/B4i`) como a clientes web modernos (`JavaScript`, a través de frameworks como `NodeJS, React, Vue, Angular, etc`.).
|
||||||
|
|
||||||
## 2. Características Principales
|
## **2\. Características Principales**
|
||||||
|
|
||||||
* **Soporte para Múltiples Bases de Datos**: Puede cargar y gestionar hasta 4 archivos de configuración (`config.properties`) simultáneamente.
|
- **Soporte para Múltiples Bases de Datos**: Puede cargar y gestionar hasta 4 archivos de configuración (`config.properties`) simultáneamente.
|
||||||
* **Comandos SQL Externalizados**: Las sentencias SQL se definen en los archivos de configuración, permitiendo modificarlas sin recompilar el servidor.
|
- **Comandos SQL Externalizados**: Las sentencias SQL se definen en los archivos de configuración, permitiendo modificarlas sin recompilar el servidor.
|
||||||
* **Doble Handler de Peticiones**: Incluye un handler clásico para clientes B4X y un handler JSON para clientes web.
|
- **Doble Handler de Peticiones**: Incluye un handler clásico para clientes B4X y un handler JSON para clientes web.
|
||||||
* **Validaciones de Seguridad**: Verifica la existencia de comandos y la correspondencia en el número de parámetros.
|
- **Validaciones de Seguridad**: Verifica la existencia de comandos y la correspondencia en el número de parámetros.
|
||||||
* **Administración Remota**: Permite verificar el estado, recargar la configuración y reiniciar el servidor a través de URLs específicas.
|
- **Administración Remota**: Permite verificar el estado, recargar la configuración y reiniciar el servidor a través de URLs específicas.
|
||||||
|
|
||||||
## 3. Configuración
|
## **3\. Configuración**
|
||||||
|
|
||||||
### 3.1. Archivos de Configuración
|
### **3.1. Archivos de Configuración**
|
||||||
|
|
||||||
El sistema está preparado para manejar hasta **cuatro configuraciones de bases de datos** (de `DB1` a `DB4`). No es necesario tener los cuatro archivos; el servidor cargará únicamente los que encuentre.
|
El sistema está preparado para manejar hasta **cuatro configuraciones de bases de datos** (de `DB1` a `DB4`). No es necesario tener los cuatro archivos; el servidor cargará únicamente los que encuentre.
|
||||||
|
|
||||||
La nomenclatura de los archivos es fundamental:
|
La nomenclatura de los archivos es fundamental:
|
||||||
|
|
||||||
* `config.properties` (para `DB1`)
|
- `config.properties` (para `DB1`)
|
||||||
* `config.DB2.properties`
|
- `config.DB2.properties`
|
||||||
* `config.DB3.properties`
|
- `config.DB3.properties`
|
||||||
* `config.DB4.properties`
|
- `config.DB4.properties`
|
||||||
|
|
||||||
**Notas importantes:**
|
**Notas importantes:**
|
||||||
|
|
||||||
* El **puerto** del servidor se toma **únicamente** del archivo principal `config.properties`, sin importar lo que digan los demás.
|
- El **puerto** del servidor se toma **únicamente** del archivo principal `config.properties`, sin importar lo que digan los demás.
|
||||||
* Los datos de conexión (`JdbcUrl`, usuario, contraseña) sí se toman del archivo correspondiente a cada base de datos.
|
- Los datos de conexión (`JdbcUrl`, `usuario`, `contraseña`) sí se toman del archivo correspondiente a cada base de datos.
|
||||||
|
|
||||||
### 3.2. Añadir Drivers de Bases de Datos Adicionales
|
### **3.2. Añadir Drivers de Bases de Datos Adicionales**
|
||||||
|
|
||||||
Si necesitas conectarte a otros tipos de bases de datos (ej. Oracle), debes agregar el archivo del controlador `.jar` al proyecto antes de compilar. En el módulo `Main`, añade una línea como la siguiente:
|
Si necesitas conectarte a otros tipos de bases de datos (ej. Oracle), debes agregar el archivo del controlador .jar al proyecto antes de compilar. En el módulo `Main`, añade una línea como la siguiente:
|
||||||
|
|
||||||
```b4x
|
```b4x
|
||||||
' Este es el nombre del archivo .jar, en este caso "C:\Ruta\Adicional\ojdbc11.jar"
|
' Este es el nombre del archivo .jar, en este caso "C:\\Ruta\\LibsAdicionales\\ojdbc11.jar"
|
||||||
#AdditionalJar: ojdbc11
|
#AdditionalJar: ojdbc11
|
||||||
|
```
|
||||||
|
|
||||||
|
Al compilar, el driver se incluirá en el `.jar` final del servidor, por lo que no será necesario copiarlo por separado al directorio de producción.
|
||||||
|
|
||||||
|
## **4\. Uso del Handler Clásico (Para Clientes B4X)**
|
||||||
|
|
||||||
|
Este handler mantiene la compatibilidad con `DBRequestManager`. La selección de la base de datos se realiza dinámicamente a través de la URL.
|
||||||
|
|
||||||
|
- Para `config.properties` \=\> `http://tu-dominio.com:8090`
|
||||||
|
- Para `config.DB2.properties` \=\> `http://tu-dominio.com:8090/DB2`
|
||||||
|
- Para `config.DB3.properties` \=\> `http://tu-dominio.com:8090/DB3`
|
||||||
|
- Para `config.DB4.properties` \=\> `http://tu-dominio.com:8090/DB4`
|
||||||
|
|
||||||
|
## **5\. Uso del DBHandlerJSON (Para Clientes Web)**
|
||||||
|
|
||||||
|
Este handler está diseñado para clientes que se comunican vía `JSON`, como aplicaciones web JavaScript.
|
||||||
|
|
||||||
|
### **5.1. Endpoint y Métodos de Envío**
|
||||||
|
|
||||||
|
Las peticiones van dirigidas al endpoint `/DBJ`. El handler es flexible y acepta datos de dos maneras:
|
||||||
|
|
||||||
|
**Método Recomendado: POST con Body JSON**
|
||||||
|
|
||||||
|
Esta es la forma más limpia y estándar para las APIs modernas.
|
||||||
|
|
||||||
|
- **Método HTTP**: POST
|
||||||
|
- **URL**: http://tu-dominio.com:8090/DBJ
|
||||||
|
- **Header Requerido**: Content-Type: application/json
|
||||||
|
- **Body (Payload)**: El objeto JSON se envía directamente en el cuerpo de la petición.
|
||||||
|
|
||||||
|
**Ejemplo de Body:**
|
||||||
|
|
||||||
|
```
|
||||||
|
{
|
||||||
|
"dbx": "DB2",
|
||||||
|
"query": "get\_user",
|
||||||
|
"exec": "executeQuery",
|
||||||
|
"params": {
|
||||||
|
"par1": "CDAZA"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Método Legacy: GET con Parámetro `j`**
|
||||||
|
|
||||||
|
Este método se mantiene por retrocompatibilidad.
|
||||||
|
|
||||||
|
- **Método HTTP**: GET (o POST con Content-Type: application/x-www-form-urlencoded)
|
||||||
|
- **URL**: El JSON completo se envía como el valor del parámetro `j` en la URL.
|
||||||
|
|
||||||
|
Ejemplo con GET:
|
||||||
|
http://tu-dominio.com:8090/DBJ?j={"dbx":"DB2","query":"get\_user","exec":"executeQuery","params":{"par1":"CDAZA"}}
|
||||||
|
|
||||||
|
### **5.2. Formato del Payload JSON**
|
||||||
|
|
||||||
|
La estructura del objeto JSON es la misma para ambos métodos:
|
||||||
|
|
||||||
|
```
|
||||||
|
{
|
||||||
|
"exec": "executeQuery",
|
||||||
|
"query": "nombre\_del\_comando\_sql",
|
||||||
|
"dbx": "DB1",
|
||||||
|
"params": {
|
||||||
|
"par1": "valor1",
|
||||||
|
"par2": 123
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- `exec`: `"executeQuery"` (para SELECT) o `"executeCommand"` (para INSERT, UPDATE, DELETE).
|
||||||
|
- `query`: Nombre del comando SQL tal como está definido en el archivo de configuración (ej. `select\_user`).
|
||||||
|
- `dbx` (opcional): La llave de la base de datos (`DB1`, `DB2`, etc.). Si se omite, se usará **DB1** por defecto.
|
||||||
|
- `params` (opcional): Un objeto que contiene los parámetros para la consulta SQL.
|
||||||
|
|
||||||
|
### **5.3. ¡Importante\! Envío de Parámetros**
|
||||||
|
|
||||||
|
El servidor ordena las claves de los parámetros alfabéticamente antes de pasarlos a la consulta SQL. Para asegurar que los valores se asignen al `?` correcto, **debes nombrar las claves de los parámetros de forma secuencial**: `"par1"`, `"par2"`, `"par3"`, etc.
|
||||||
|
|
||||||
|
**Nota para más de 9 parámetros**: Si tienes 10 o más parámetros, usa un cero inicial para mantener el orden alfabético correcto (ej. `"par01"`, `"par02"`, ..., `"par10"`).
|
||||||
|
|
||||||
|
### **5.4. Respuestas JSON**
|
||||||
|
|
||||||
|
Las respuestas del servidor siempre son en formato JSON e incluyen un campo booleano `success`.
|
||||||
|
|
||||||
|
- **Si success es true**, los datos se encontrarán en la llave `result`.
|
||||||
|
- **Si success es false**, el mensaje de error se encontrará en la llave `error`.
|
||||||
|
|
||||||
|
## **6\. Administración del Servidor**
|
||||||
|
|
||||||
|
Se pueden ejecutar comandos de gestión directamente desde un navegador o una herramienta como cURL.
|
||||||
|
|
||||||
|
- **Verificar Estado**: `http://tu-dominio.com:8090/test`
|
||||||
|
- **Recargar Configuración**: `http://tu-dominio.com:8090/manager?command=reload` (Vuelve a leer todos los archivos `config.\*.properties` sin reiniciar el servidor).
|
||||||
|
- **Reiniciar Servidor (Estándar)**: `http://tu-dominio.com:8090/manager?command=rsx` (Ejecuta los scripts `start.bat`, `start2.bat` y `stop.bat`).
|
||||||
|
- **Reiniciar Servidor (con PM2)**: `http://tu-dominio.com:8090/manager?command=rpm2` (Ejecuta `reiniciaProcesoPM2.bat` y asume que el nombre del proceso es "RDC-Multi". Modificar el `.bat` si el nombre es diferente).
|
||||||
|
|||||||
48
README0.md
48
README0.md
@@ -1,48 +0,0 @@
|
|||||||
# jRDC-Multi (B4J)
|
|
||||||
Servidor de DBRequest que puede cargar hasta 4 archivos de config.properties al mismo tiempo.
|
|
||||||
|
|
||||||
Los archivos se deben de llamar:
|
|
||||||
|
|
||||||
- config.propierties
|
|
||||||
- config.DB2.properties
|
|
||||||
- config.DB3.properties
|
|
||||||
- config.DB4.properties
|
|
||||||
|
|
||||||
No es necesario que sean 4 archivos, solo toma en cuenta los archivos existentes en el directorio.
|
|
||||||
|
|
||||||
En la aplicacion movil, al URL del servidor se le agrega al final /DB2, /DB3 o /DB4. (Puerto de ejemplo: 1781)
|
|
||||||
|
|
||||||
- Para usar el config.properties => http://keymon.lat:1781
|
|
||||||
- Para usar el config.DB2.properties => http://keymon.lat:1781/DB2
|
|
||||||
- Para usar el config.DB3.properties => http://keymon.lat:1781/DB3
|
|
||||||
- Para usar el config.DB4.properties => http://keymon.lat:1781/DB4
|
|
||||||
|
|
||||||
El puerto es el mismo para todos los archivos, **sin importar** que diga en cada archivo, solo toma el puerto especificado en el **primer** config.properties.
|
|
||||||
|
|
||||||
El usuario, contraseña y JdbcUrl, **si** los toma del archivo correspondiente.
|
|
||||||
|
|
||||||
Se puede revisar el **estatus** del servidor en el URL:
|
|
||||||
|
|
||||||
- http://keymon.lat:1781/test
|
|
||||||
|
|
||||||
Se puede forzar al servidor (**sin reiniciarlo**) a que **recargue** los archivos config.properties en el URL:
|
|
||||||
|
|
||||||
- http://keymon.lat:1781/manager?command=reload
|
|
||||||
|
|
||||||
Se puede reiniciar el servidor con el URL:
|
|
||||||
|
|
||||||
- http://keymon.lat:1781/manager?command=rsx
|
|
||||||
- Este comando utiliza los archivos start.bat, start2.bat y stop.bat
|
|
||||||
|
|
||||||
Si se esta corriendo el servidor con PM2, se puede reinciar con el URL:
|
|
||||||
|
|
||||||
- http://keymon.lat:1781/manager?command=rpm2
|
|
||||||
- Este comando ejecuta el archivo reiniciaProcesoPM2.bat, y **asume** que el nombre del proceso es "RDC-Multi", si no es asi, hay que **modificar** el archivo .bat
|
|
||||||
|
|
||||||
## Agregar drivers de mas bases de datos
|
|
||||||
|
|
||||||
Si se necesitan agregar mas controladores para conectarse a otras bases de datos, hay que agregar una linea a "Main":
|
|
||||||
|
|
||||||
- #AdditionalJar: ojdbc11 <= este es el nombre del archivo .jar, en este caso "C:\Android\AdditionalLibs\B4J\ojdbc11.jar"
|
|
||||||
|
|
||||||
- Al compilar la aplicación, el archivo del controlador se incluye en el archivo .jar del servidor (jRDC-Multi.jar) y no es necesario copiarlo o agregarlo al directorio del servidor en producción.
|
|
||||||
@@ -16,7 +16,7 @@ End Sub
|
|||||||
Sub Handle(req As ServletRequest, resp As ServletResponse)
|
Sub Handle(req As ServletRequest, resp As ServletResponse)
|
||||||
Log("TEST")
|
Log("TEST")
|
||||||
resp.ContentType = "text/html"
|
resp.ContentType = "text/html"
|
||||||
resp.Write($"<a href="/test">Test</a> | <a href="/manager?command=reload">Reload</a> | <br/>"$)
|
resp.Write($"<a href="/test">Test</a> | <a href="/manager?command=reload">Reload</a> | <a href="/manager?command=rpm2">Reiniciar</a> | <a href="/manager?command=reviveBow">Revive Bow</a> | </br></br>"$)
|
||||||
resp.Write($"RemoteServer is running on port <strong>${Main.srvr.Port}</strong> ($DateTime{DateTime.Now})<br/>"$)
|
resp.Write($"RemoteServer is running on port <strong>${Main.srvr.Port}</strong> ($DateTime{DateTime.Now})<br/>"$)
|
||||||
Try
|
Try
|
||||||
' Dim con As SQL = Main.rdcConnectorDB1.GetConnection("")
|
' Dim con As SQL = Main.rdcConnectorDB1.GetConnection("")
|
||||||
|
|||||||
116
jRDC_Multi.b4j
116
jRDC_Multi.b4j
@@ -1,29 +1,48 @@
|
|||||||
AppType=StandardJava
|
AppType=StandardJava
|
||||||
Build1=Default,b4j.JRDCMulti
|
Build1=Default,b4j.JRDCMulti
|
||||||
File1=config.properties
|
File1=config.DB2.properties
|
||||||
|
File10=stop.bat
|
||||||
|
File2=config.DB3.properties
|
||||||
|
File3=config.DB4.properties
|
||||||
|
File4=config.properties
|
||||||
|
File5=login.html
|
||||||
|
File6=reiniciaProcesoBow.bat
|
||||||
|
File7=reiniciaProcesoPM2.bat
|
||||||
|
File8=start.bat
|
||||||
|
File9=start2.bat
|
||||||
FileGroup1=Default Group
|
FileGroup1=Default Group
|
||||||
|
FileGroup10=Default Group
|
||||||
|
FileGroup2=Default Group
|
||||||
|
FileGroup3=Default Group
|
||||||
|
FileGroup4=Default Group
|
||||||
|
FileGroup5=Default Group
|
||||||
|
FileGroup6=Default Group
|
||||||
|
FileGroup7=Default Group
|
||||||
|
FileGroup8=Default Group
|
||||||
|
FileGroup9=Default Group
|
||||||
Group=Default Group
|
Group=Default Group
|
||||||
Library1=javaobject
|
Library1=byteconverter
|
||||||
Library2=jcore
|
Library2=javaobject
|
||||||
Library3=jrandomaccessfile
|
Library3=jcore
|
||||||
Library4=jserver
|
Library4=jrandomaccessfile
|
||||||
Library5=jshell
|
Library5=jserver
|
||||||
Library6=json
|
Library6=jshell
|
||||||
Library7=jsql
|
Library7=json
|
||||||
Library8=byteconverter
|
Library8=jsql
|
||||||
Module1=DB1Handler
|
Library9=bcrypt
|
||||||
|
Module1=ChangePassHandler
|
||||||
Module10=RDCConnector
|
Module10=RDCConnector
|
||||||
Module11=TestHandler
|
Module11=TestHandler
|
||||||
Module2=DB1JsonHandler
|
Module2=DBHandlerB4X
|
||||||
Module3=DB2Handler
|
Module3=DBHandlerJSON
|
||||||
Module4=DB3Handler
|
Module4=DoLoginHandler
|
||||||
Module5=DB4Handler
|
Module5=GlobalParameters
|
||||||
Module6=DBHandlerGenerico
|
Module6=LoginHandler
|
||||||
Module7=GlobalParameters
|
Module7=LogoutHandler
|
||||||
Module8=Manager
|
Module8=Manager
|
||||||
Module9=ping
|
Module9=ping
|
||||||
NumberOfFiles=1
|
NumberOfFiles=10
|
||||||
NumberOfLibraries=8
|
NumberOfLibraries=9
|
||||||
NumberOfModules=11
|
NumberOfModules=11
|
||||||
Version=10.3
|
Version=10.3
|
||||||
@EndOfDesignText@
|
@EndOfDesignText@
|
||||||
@@ -31,7 +50,7 @@ Version=10.3
|
|||||||
#Region Project Attributes
|
#Region Project Attributes
|
||||||
#CommandLineArgs:
|
#CommandLineArgs:
|
||||||
#MergeLibraries: True
|
#MergeLibraries: True
|
||||||
' VERSION 5.08.30
|
' VERSION 5.09.01
|
||||||
'###########################################################################################################
|
'###########################################################################################################
|
||||||
'###################### PULL #############################################################
|
'###################### PULL #############################################################
|
||||||
'Ctrl + click ide://run?file=%WINDIR%\System32\cmd.exe&Args=/c&Args=git&Args=pull
|
'Ctrl + click ide://run?file=%WINDIR%\System32\cmd.exe&Args=/c&Args=git&Args=pull
|
||||||
@@ -48,6 +67,8 @@ Version=10.3
|
|||||||
'#AdditionalJar: mysql-connector-java-5.1.27-bin
|
'#AdditionalJar: mysql-connector-java-5.1.27-bin
|
||||||
'#AdditionalJar: postgresql-42.7.0
|
'#AdditionalJar: postgresql-42.7.0
|
||||||
#AdditionalJar: ojdbc11
|
#AdditionalJar: ojdbc11
|
||||||
|
' Librería para manejar la base de datos SQLite
|
||||||
|
#AdditionalJar: sqlite-jdbc-3.7.2
|
||||||
|
|
||||||
Sub Process_Globals
|
Sub Process_Globals
|
||||||
Public srvr As Server
|
Public srvr As Server
|
||||||
@@ -57,9 +78,15 @@ Sub Process_Globals
|
|||||||
Dim listaDeCP As List
|
Dim listaDeCP As List
|
||||||
Dim cpFiles As List
|
Dim cpFiles As List
|
||||||
Public Connectors, commandsMap As Map
|
Public Connectors, commandsMap As Map
|
||||||
|
Public SQL1 As SQL ' Objeto SQL para la base de datos de usuarios
|
||||||
|
Private bc As BCrypt
|
||||||
End Sub
|
End Sub
|
||||||
|
|
||||||
Sub AppStart (Args() As String)
|
Sub AppStart (Args() As String)
|
||||||
|
' --- INICIO DE CAMBIOS ---
|
||||||
|
' Inicializamos la base de datos. Se creará si no existe.
|
||||||
|
InitializeSQLiteDatabase
|
||||||
|
' --- FIN DE CAMBIOS ---
|
||||||
listaDeCP.Initialize
|
listaDeCP.Initialize
|
||||||
srvr.Initialize("")
|
srvr.Initialize("")
|
||||||
Dim con As RDCConnector
|
Dim con As RDCConnector
|
||||||
@@ -94,20 +121,22 @@ Sub AppStart (Args() As String)
|
|||||||
End If
|
End If
|
||||||
srvr.AddHandler("/ping", "ping", False) ' Agrega un manejador a la ruta "/test", asignando las solicitudes a la clase TestHandler, el último parámetro indica si el manejador debe ejecutar en un nuevo hilo (False en este caso)
|
srvr.AddHandler("/ping", "ping", False) ' Agrega un manejador a la ruta "/test", asignando las solicitudes a la clase TestHandler, el último parámetro indica si el manejador debe ejecutar en un nuevo hilo (False en este caso)
|
||||||
srvr.AddHandler("/test", "TestHandler", False) ' Agrega un manejador a la ruta "/test", asignando las solicitudes a la clase TestHandler, el último parámetro indica si el manejador debe ejecutar en un nuevo hilo (False en este caso)
|
srvr.AddHandler("/test", "TestHandler", False) ' Agrega un manejador a la ruta "/test", asignando las solicitudes a la clase TestHandler, el último parámetro indica si el manejador debe ejecutar en un nuevo hilo (False en este caso)
|
||||||
|
|
||||||
|
' --- INICIO DE CAMBIOS ---
|
||||||
|
' 1. Rutas para el sistema de Login
|
||||||
|
srvr.AddHandler("/login", "LoginHandler", False) ' Sirve la página de login
|
||||||
|
srvr.AddHandler("/dologin", "DoLoginHandler", False) ' Procesa el intento de login
|
||||||
|
srvr.AddHandler("/logout", "LogoutHandler", False) ' Cierra la sesión
|
||||||
|
srvr.AddHandler("/changepass", "ChangePassHandler", False)
|
||||||
|
' 2. El handler del manager se queda igual, pero ahora estará protegido
|
||||||
srvr.AddHandler("/manager", "Manager", False)
|
srvr.AddHandler("/manager", "Manager", False)
|
||||||
' srvr.AddHandler("/db1", "DB1Handler", False)
|
' --- FIN DE CAMBIOS ---
|
||||||
' srvr.AddHandler("/DB1", "DB1Handler", False)
|
|
||||||
' srvr.AddHandler("/db2", "DB2Handler", False)
|
srvr.AddHandler("/DBJ", "DBHandlerJSON", False)
|
||||||
' srvr.AddHandler("/DB2", "DB2Handler", False)
|
srvr.AddHandler("/dbrquery", "DBHandlerJSON", False)
|
||||||
' srvr.AddHandler("/db3", "DB3Handler", False)
|
|
||||||
' srvr.AddHandler("/DB3", "DB3Handler", False)
|
|
||||||
' srvr.AddHandler("/db4", "DB4Handler", False)
|
|
||||||
' srvr.AddHandler("/DB4", "DB4Handler", False)
|
|
||||||
srvr.AddHandler("/DBJ", "DB1JsonHandler", False)
|
|
||||||
srvr.AddHandler("/dbrquery", "DB1JsonHandler", False)
|
|
||||||
' srvr.AddHandler("/*", "DB1Handler", False) ' Si no se especifica una base de datos, entonces asignamos la solicitud a la DB1.
|
' srvr.AddHandler("/*", "DB1Handler", False) ' Si no se especifica una base de datos, entonces asignamos la solicitud a la DB1.
|
||||||
|
|
||||||
srvr.AddHandler("/*", "DBHandlerGenerico", False)
|
srvr.AddHandler("/*", "DBHandlerB4X", False)
|
||||||
|
|
||||||
srvr.Start
|
srvr.Start
|
||||||
Log("===========================================================")
|
Log("===========================================================")
|
||||||
@@ -115,3 +144,30 @@ Sub AppStart (Args() As String)
|
|||||||
Log("===========================================================")
|
Log("===========================================================")
|
||||||
StartMessageLoop
|
StartMessageLoop
|
||||||
End Sub
|
End Sub
|
||||||
|
|
||||||
|
' Nueva subrutina para crear y configurar la base de datos de usuarios
|
||||||
|
Sub InitializeSQLiteDatabase
|
||||||
|
Dim dbFileName As String = "users.db"
|
||||||
|
' Si la base de datos no existe en la carpeta del .jar, la creamos
|
||||||
|
If File.Exists(File.DirApp, dbFileName) = False Then
|
||||||
|
Log("Creando nueva base de datos de usuarios: " & dbFileName)
|
||||||
|
' Inicializamos la conexión
|
||||||
|
SQL1.InitializeSQLite(File.DirApp, dbFileName, True)
|
||||||
|
' Creamos la tabla de usuarios
|
||||||
|
Dim createUserTable As String = "CREATE TABLE users (username TEXT PRIMARY KEY, password_hash TEXT NOT NULL)"
|
||||||
|
SQL1.ExecNonQuery(createUserTable)
|
||||||
|
|
||||||
|
' Creamos un usuario por defecto para el primer inicio
|
||||||
|
Dim defaultUser As String = "admin"
|
||||||
|
Dim defaultPass As String = "12345"
|
||||||
|
Dim hashedPass As String = bc.hashpw(defaultPass, bc.gensalt) ' bc.HashPassword(defaultPass)
|
||||||
|
|
||||||
|
SQL1.ExecNonQuery2("INSERT INTO users (username, password_hash) VALUES (?, ?)", Array As Object(defaultUser, hashedPass))
|
||||||
|
Log($"Usuario por defecto creado -> user: ${defaultUser}, pass: ${defaultPass}"$)
|
||||||
|
Else
|
||||||
|
' Si ya existe, solo la abrimos
|
||||||
|
SQL1.InitializeSQLite(File.DirApp, dbFileName, True)
|
||||||
|
Log("Base de datos de usuarios cargada.")
|
||||||
|
End If
|
||||||
|
End Sub
|
||||||
|
' --- FIN DE CAMBIOS ---
|
||||||
@@ -27,13 +27,13 @@ ModuleClosedNodes1=
|
|||||||
ModuleClosedNodes10=
|
ModuleClosedNodes10=
|
||||||
ModuleClosedNodes11=
|
ModuleClosedNodes11=
|
||||||
ModuleClosedNodes2=
|
ModuleClosedNodes2=
|
||||||
ModuleClosedNodes3=4,5,6
|
ModuleClosedNodes3=
|
||||||
ModuleClosedNodes4=
|
ModuleClosedNodes4=
|
||||||
ModuleClosedNodes5=
|
ModuleClosedNodes5=
|
||||||
ModuleClosedNodes6=
|
ModuleClosedNodes6=
|
||||||
ModuleClosedNodes7=
|
ModuleClosedNodes7=
|
||||||
ModuleClosedNodes8=
|
ModuleClosedNodes8=
|
||||||
ModuleClosedNodes9=
|
ModuleClosedNodes9=
|
||||||
NavigationStack=DBHandlerGenerico,SendPlainTextError,603,0,DBHandlerGenerico,Initialize,27,0,DB1JsonHandler,Class_Globals,6,0,DB1JsonHandler,Initialize,13,0,DBHandlerGenerico,Class_Globals,15,0,DB1JsonHandler,Handle,197,6,DB1JsonHandler,SendSuccessResponse,238,0,DB1JsonHandler,SendErrorResponse,255,0,Main,AppStart,76,0
|
NavigationStack=DoLoginHandler,Initialize,7,0,Manager,Initialize,98,0,ChangePassHandler,Handle,27,0,DoLoginHandler,Handle,9,0,Manager,Handle0,202,6,TestHandler,Handle,11,0,LoginHandler,Handle,16,1,Manager,Handle,110,6,Main,Process_Globals,24,0,Main,AppStart,85,0
|
||||||
SelectedBuild=0
|
SelectedBuild=0
|
||||||
VisibleModules=6,2,10
|
VisibleModules=2,3,10,8,11,6
|
||||||
|
|||||||
9
reiniciaProcesoBow.bat
Normal file
9
reiniciaProcesoBow.bat
Normal file
@@ -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 restart BotSoporte_4.0
|
||||||
|
|
||||||
|
exit
|
||||||
@@ -4,6 +4,6 @@
|
|||||||
set "params=%*"
|
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 )
|
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
|
pm2 restart jRDC-Multi
|
||||||
|
|
||||||
exit
|
exit
|
||||||
Reference in New Issue
Block a user