B4J Tutorial Firebase Service (Server) Example

Alexander Stolte

Well-Known Member
Licensed User
Hey,

this is an example/tutorial of a Server that manages Firebase Subscribtions, Unsubscribtions and SendMessages2Topics with the Power of B4J Server!

The advantage is, requests are processed very quickly (barely waiting period), I do not have to start a script, save resources of the VPS or Server.

On average, I had a waiting time between 4-6 milliseconds until a message was sent with this service. if i start a script and send a message over it then 4-5 seconds.

This Example is very basic
for me it is sufficient, however, since my requests to the server are automated and follow a scheme, therefore, I can work with the URL without converting my arguments to bytes.

Links:
Building web servers with B4J
B4X Subscribe and Unsubscribe Topic
Firebase Notifications SendMessages

we need this libraries:
jOkHttpUtils2_NONUI
jServer
Json
OkHttp

Now i will start:

1.
-We create a new B4J non UI Project.

2. go to the main module and put this in it:

B4X:
Sub Process_Globals
    Private srvr As Server
    Public const API_KEY As String = "ABAANxxxw64:ARA91bHS8IjWNSGXXXXXXXXXXXXXXXXXXXXXXXXXXX" 'the API Key from your Firebase
End Sub

Sub AppStart (Args() As String)
   
    srvr.Initialize("srvr")
    srvr.Port = 9654 'our port to access the server

    'i use 3 Handler so every handler can do his job in peace
    srvr.AddHandler("/send2topic", "Send2Topic", False)
    srvr.AddHandler("/sub", "Subscribe", False)
    srvr.AddHandler("/unsub", "unsubscribe", False)
   
    srvr.Start
    Log("Server started")
    StartMessageLoop
   
End Sub

3.
-Add a new ClassModule as Handler named "Send2Topic"
-Add this to it:
B4X:
Sub Handle(req As ServletRequest, resp As ServletResponse)
    Dim start As Long = DateTime.Now
   
    SendMessage(req.GetParameter("topic"),req.GetParameter("title"),req.GetParameter("body"))
    StartMessageLoop 'we need this here, for the wait for
   
    resp.Write($"took: ${DateTime.Now - start}ms"$)
    Log($"took: ${DateTime.Now - start}ms"$)
   
End Sub

Private Sub SendMessage(Topic As String, Title As String, Body As String)
    Dim Job As HttpJob
    Job.Initialize("fcm", Me)
    Dim m As Map = CreateMap("to": $"/topics/${Topic}"$)
   
    Dim data As Map = CreateMap("title": Title , "body": Body)
    m.Put("priority", 10)

    m.Put("data", data)
    Dim jg As JSONGenerator
    jg.Initialize(m)
    Job.PostString("https://fcm.googleapis.com/fcm/send", jg.ToString)
    Job.GetRequest.SetContentType("application/json;charset=UTF-8")
    Job.GetRequest.SetHeader("Authorization", "key=" & Main.API_KEY)

    Wait For (Job) JobDone(Job As HttpJob)
   
    If Job.Success Then
        Log(Job.GetString)
    End If
    Job.Release
   
    StopMessageLoop 'we need this here, for the wait for
End Sub

4.
-Create a new ClassModule as Handler
-Add this to it:
B4X:
Sub Handle(req As ServletRequest, resp As ServletResponse)
   
    Dim start As Long = DateTime.Now
   
    SubscribeToTopic(Array As String (req.GetParameter("token")),req.GetParameter("topic"))
    StartMessageLoop
   
    resp.Write($"took: ${DateTime.Now - start}ms"$)
    Log($"took: ${DateTime.Now - start}ms"$)
   
End Sub

Private Sub SubscribeToTopic(Token() As String, TopicName As String)
   
    Dim Job As HttpJob
    Job.Initialize("fcm", Me)
    Dim m As Map = CreateMap("to": $"/topics/${TopicName}"$, "registration_tokens":Token)
 
    Dim jg As JSONGenerator
    jg.Initialize(m)
 
    Job.PostString("https://iid.googleapis.com/iid/v1:batchAdd", jg.ToString)
    Job.GetRequest.SetContentType("application/json")
    Job.GetRequest.SetHeader("Authorization", "key=" & Main.API_KEY)
   
    Wait For (Job) JobDone(Job As HttpJob)
   
    If Job.Success Then
        Log(Job.GetString)
    End If
    Job.Release
   
    StopMessageLoop
 
End Sub

5.
-Create a new ClassModule as Handler
-Add this to it:
B4X:
Sub Handle(req As ServletRequest, resp As ServletResponse)
   
    Dim start As Long = DateTime.Now
   
    UnsubscribeTopic(Array As String (req.GetParameter("token")),req.GetParameter("topic"))
    StartMessageLoop
   
    resp.Write($"took: ${DateTime.Now - start}ms"$)
    Log($"took: ${DateTime.Now - start}ms"$)
   
End Sub

Private Sub UnsubscribeTopic(Token() As String, TopicName As String)
   
    Dim Job As HttpJob
    Job.Initialize("fcm", Me)
    Dim m As Map = CreateMap("to": $"/topics/${TopicName}"$, "registration_tokens":Token)

    Dim jg As JSONGenerator
    jg.Initialize(m)
 
    Job.PostString("https://iid.googleapis.com/iid/v1:batchRemove", jg.ToString)
    Job.GetRequest.SetContentType("application/json")
    Job.GetRequest.SetHeader("Authorization", "key=" & Main.API_KEY)
 
    Wait For (Job) JobDone(Job As HttpJob)
   
    If Job.Success Then
        Log(Job.GetString)
    End If
    Job.Release
   
    StopMessageLoop
 
End Sub

Now we can Start this Server and can access to it.

the request must look like this for example:
Send2Topic: http://localhost:9654/send2topic?topic=general&title=the_title&body=the_body

Subscribe: http://localhost:9654/sub?token=fjfjjsxxx:dajasasdjasAAASsxxxxxxx&topic=general

UnSubscribe: http://localhost:9654/unsub?token=fjfjjsxxx:dajasasdjasAAASsxxxxxxx&topic=general

thats all, i upload the example project and you can modify it,if you have tweaks then you can post it here.

Have a nice Day.
 

Attachments

Top