B4A Class QuickBlox

I created this class to be able to connect to quickblox:

http://quickblox.com/?utm_expid=523...KALMqWuQ.0&utm_referrer=http://quickblox.com/

QuickBlox is similar to Parse. However, their free plan offers unlimited api calls and 10gigs of storage space. They have modules for CustomObjects (tables), Authentication, Push Notifications and more. I only wrapped the CustomObjects and a little bit of Authentication for use in my app. Feel free to use this as a base. It is free for you to use, but i am not going to support it.

To be able to use this class, you have to add the following methods to httpjob in httputils2:
B4X:
'Submits a HTTP GET request.
'Encodes illegal parameter characters.
'<code>Example:
'job.Download3("http://www.example.com", _
'    params as string)</code>
Public Sub Download3(Link As String, params As String)
    req.InitializeGet(params)
    CallSubDelayed2(HttpUtils2Service, "SubmitJob", Me)       
End Sub

'Submits a HTTP PUT request.
Public Sub PutString(Link As String, Text As String)
   PutBytes(Link, Text.GetBytes("UTF8"))
End Sub

'Sends a PUT request with the given string as the put data
Public Sub PutBytes(Link As String, Data() As Byte)
    req.InitializePut2(Link, Data)
    CallSubDelayed2(HttpUtils2Service, "SubmitJob", Me)
End Sub

'Submits a HTTP DELETE request.
Public Sub Delete(Link As String)
    req.InitializeDelete(Link)
    CallSubDelayed2(HttpUtils2Service, "SubmitJob", Me)
End Sub

Code for the Class:
B4X:
'Class module
Sub Class_Globals
    Private ApplicationID As String
    Private AuthorizationKey As String
    Private AuthorizationSecret As String
    Private Username As String
    Private Password As String
    Private Act As Object
    Type TokenResponse(Token As String, RawResponse As String)
    Type DefaultResponse(RawResponse As String)
    Type CreateResponse(RecordID As String, RawResponse As String)
    Type RetrievalParam(Key As String, Operator As String, Value As String)
End Sub


Public Sub Initialize(caller As Object, uname As String, pwd As String, appid As String, secret As String, key As String)
    ApplicationID = appid
    AuthorizationKey = key
    AuthorizationSecret = secret
    Username = uname
    Password = pwd
    Act = caller
End Sub

'Date: 12/2/2013
'Author: Michael Hartwig
'Purpose: Encryps the SHA1 Hash for use in 
'generating the QuickBlox signature.
Private Sub EncryptHMACSHA(Target As String, Key As String) As String
    Dim m As Mac
    Dim k As KeyGenerator
    k.Initialize("HMACSHA1")
    k.KeyFromBytes(Key.GetBytes("UTF8"))
    m.Initialise("HMACSHA1", k.Key)
    m.Update(Target.GetBytes("UTF8"))
    Dim b() As Byte
    b = m.Sign
    Dim bc As ByteConverter
   
    Return bc.HexFromBytes(b)
End Sub

'Date: 12/2/2013
'Author: Michael Hartwig
'Purpose: Generates a signature for use in 
'generating a QuickBlox token.
Private Sub GenerateSignature(nonce As Int, timestamp As Long) As String
    Dim signatureParams As String
       
    signatureParams = "application_id=[appid]&auth_key=[authkey]&nonce=[nonce]&timestamp=[time]&user[login]=[uname]&user[password]=[pass]".Replace( _
        "[appid]", ApplicationID).Replace("[authkey]", AuthorizationKey).Replace("[nonce]", nonce).Replace( _
        "[time]", timestamp).Replace("[uname]", Username).Replace("[pass]", Password)
   
    Dim sig As String : sig = EncryptHMACSHA(signatureParams, AuthorizationSecret)

    Log("Generated Signature for Token: " & sig.ToLowerCase)
   
    Return sig.ToLowerCase
End Sub

'Date: 12/2/2013
'Author: Michael Hartwig
'Purpose: JobDone event for HTTPUtils2.
Sub JobDone (Job As HttpJob)
   If Job.Success = True Then
      Select Job.JobName
        Case "GetToken"
            Dim ret As String : ret = Job.GetString
           
            'replace the old garbage with a top level object
            ret = "{~results~:".Replace("~", Chr(34)) & ret & "}"
           
            Dim json As JSONParser
            Dim m As Map 'helper object used for navigating
            Dim root As Map
           
            json.Initialize(ret)
           
            root = json.NextObject
           
            root = root.Get("results")
            m = root.Get("session")
           
            Dim token As String
           
            For Each key As String In m.Keys
                If key = "token" Then
                    token = m.Get(key)
                End If
            Next
           
            Log("Recieved Token for Session: " & token)
           
            Dim token_response As TokenResponse 
            token_response.Initialize
            token_response.token = token
            token_response.RawResponse = ret
           
            CallSubDelayed2(Act, "GetToken_Complete", token_response)
        Case "CreateRecord"
            Dim ret As String : ret = Job.GetString
           
            Dim mat As Matcher
            mat = Regex.Matcher("<_id>(.*?)</_id>", ret)
           
            Dim i As String : i = ""
            Do While mat.Find
                i = mat.Group(1)
            Loop
           
            If i = "" Then
                Log("Failed to Create Record.")
                Exit
            Else
                Log("Created Record with ID: " & i)
            End If
           
            Dim create_response As CreateResponse 
            create_response.Initialize
            create_response.RecordID = i
            create_response.RawResponse = ret
           
            CallSubDelayed2(Act, "CreateCustomObject_Complete", create_response)
        Case "DeleteRecord"
            Dim ret As String : ret = Job.GetString
           
            If ret = "" Then
                CallSubDelayed2(Act, "DeleteCustomObject_Complete", True)
            Else
                CallSubDelayed2(Act, "DeleteCustomObject_Complete", False)
            End If
        Case "RetrieveRecords"
            Dim ret As String : ret = Job.GetString
           
            Log(ret)
     End Select
   Else
      Log("Error: " & Job.ErrorMessage)
   End If
   
   Job.Release
End Sub

'Date: 12/2/2013
'Author: Michael Hartwig
'Purpose: Gets an authentication session token
'for use in all QuickBlox calls. Tokens are good
'for 2 hours.
Public Sub GetSessionToken()
    Dim job As HttpJob
    job.Initialize("GetToken", Me)
   
    Dim timestamp As Long : timestamp = DateTime.Now / 1000
    Dim nonce As Int : nonce = Rnd(1, 1000)
   
    Dim json As JSONGenerator
    Dim m As Map
    m.Initialize

    m.Put("application_id", ApplicationID)
    m.Put("auth_key", AuthorizationKey)
    m.put("timestamp", timestamp)
    m.Put("nonce", nonce)
    m.Put("signature", GenerateSignature(nonce, timestamp))
   
    Dim mUser As Map
    mUser.Initialize
    mUser.Put("login", Username)
    mUser.Put("password", Password)
   
    m.Put("user", mUser)
   
    json.Initialize(m)
   
    Dim strJSON As String : strJSON = json.ToString

    job.PostString("https://api.quickblox.com/session.json", strJSON)
    job.GetRequest.SetHeader("QuickBlox-REST-API-Version", "0.1.0")
    job.GetRequest.SetContentType("application/json")
End Sub

'Date: 12/2/2013
'Author: Michael Hartwig
'Purpose: Retrieve records from QuickBlox
Public Sub RetrieveRecords(Parameters As String, ClassName As String, Token As String)
    Dim Job As HttpJob
    Job.Initialize("RetrieveRecords", Me)
   
    Dim url As String
    url = "https://api.quickblox.com/data/[classname]".Replace("[classname]", ClassName)
   
    If Parameters = "" Then
        Job.Download(url)
    Else
        Job.Download3(url, Parameters)
    End If
   
    Job.GetRequest.SetHeader("QB-Token", Token)
End Sub

'Date: 12/2/2013
'Author: Michael Hartwig
'Purpose: Deletes a record from QuickBlox given
'the record id.
Public Sub DeleteRecord(ClassName As String, RecordID As String, Token As String)
    Dim Job As HttpJob
    Job.Initialize("DeleteRecord", Me)
               
    Dim url As String
    url = "https://api.quickblox.com/data/[classname]/[id].json".Replace("[id]", RecordID).Replace("[classname]", ClassName)

    Job.Delete(url)
    Job.GetRequest.SetHeader("QB-Token", Token)
End Sub

'Date: 12/2/2013
'Author: Michael Hartwig
'Purpose: Deletes multiple records from QuickBlox
'given a list of record id's in string format
Public Sub DeleteMultipleRecords(ClassName As String, RecordID As List, Token As String)
    Dim Job As HttpJob
    Job.Initialize("DeleteRecords", Me)

    Dim Records As String : Records = ""
    For i = 0 To RecordID.Size - 1
       If Records = "" Then
          Records = Records & RecordID.Get(i)
       Else
          Records = "," & Records & RecordID.Get(i)
       End If
    Next

    Dim url As String
    url = "https://api.quickblox.com/data/[classname]/[id].json".Replace("[id]", Records).Replace("[classname]", ClassName)

    Job.Delete(url)
    Job.GetRequest.SetHeader("QB-Token", Token)
End Sub

'Date: 12/2/2013
'Author: Michael Hartwig
'Purpose: Creates a single record in a QuickBlox
'class.
Public Sub CreateRecord(ClassName As String, Record As Map, Token As String)
    Dim job As HttpJob
    job.Initialize("CreateRecord", Me)
   
    Dim strJSON As String : strJSON = ""
    For i = 0 To Record.Size - 1
        Dim strTemp As String
        If strJSON = "" Then
            strTemp = Record.GetKeyAt(i) & "=" & Record.GetValueAt(i)
        Else
            strTemp = "&" & Record.GetKeyAt(i) & "=" & Record.GetValueAt(i)
        End If
       
        strJSON = strJSON & strTemp
    Next

    job.PostString("https://api.quickblox.com/data/[classname]".Replace("[classname]", ClassName), strJSON)
    job.GetRequest.SetHeader("QB-Token", Token)
End Sub
 

billzhan

Active Member
Licensed User
Longtime User
mhartwig,

It's really nice server,more flexible than parse.com. Could you figure out how to upload and download files?

I tried it,and found error:

CreateRecord works OK
B4X:
    Dim m As Map
    m.Initialize
    m.Put("t11",count)
    m.Put("t22",count)
    m.Put("int",count*2)
    qb.CreateRecord("test1",m,tok)

RetrieveRecords without parameter:works
B4X:
qb.RetrieveRecords("","test1",tok)

RetrieveRecords with parameter:get errors:
B4X:
qb.RetrieveRecords("t11=2","test1",tok)

Logs:
Recieved Token for Session: cc77f6ab1b588f94686e20fd32b3422d110ed4b0
Error: java.lang.IllegalStateException: Target host must not be null, or set in parameters.
 
Last edited:

peacemaker

Expert
Licensed User
Longtime User
Thanks for this thread !
I'm trying and can add my addintion to the class code:
B4X:
'Date: 5/2/2014
'Author: Vlad Pomelov
'Purpose: Update a single record in a QuickBlox
'class.
Public Sub UpdateRecord(ClassName As String, Record As Map, RecordID As String, Token As String)
    Dim job As HttpJob
    job.Initialize("UpdateRecord", Me)
 
    Dim strJSON As String : strJSON = ""
    For i = 0 To Record.Size - 1
        Dim strTemp As String
        If strJSON = "" Then
            strTemp = Record.GetKeyAt(i) & "=" & Record.GetValueAt(i)
        Else
            strTemp = "&" & Record.GetKeyAt(i) & "=" & Record.GetValueAt(i)
        End If
     
        strJSON = strJSON & strTemp
    Next

    job.PutString("https://api.quickblox.com/data/[classname]/[id]".Replace("[classname]", ClassName).Replace("[id]", RecordID), strJSON)
    job.GetRequest.SetHeader("QB-Token", Token)
End Sub
 

peacemaker

Expert
Licensed User
Longtime User
RetrieveRecords with parameter:get errors:
qb.RetrieveRecords("t11=2","test1",tok)

Rechecked - needs to use Download2 with Array of parameters:
B4X:
'Date: 12/2/2013
'Author: Michael Hartwig & Vlad pomelov (5/2/2014)
'Purpose: Retrieve records from QuickBlox
Public Sub RetrieveRecords(Parameters () As String, ClassName As String, Token As String)
    Dim Job As HttpJob
    Job.Initialize("RetrieveRecords", Me)

    Dim url As String
    url = "https://api.quickblox.com/data/[classname]".Replace("[classname]", ClassName)

    If Parameters.Length = 0 Then
        Job.Download(url)
    Else
        Job.Download2(url, Parameters)
    End If

    Job.GetRequest.SetHeader("QB-Token", Token)
End Sub
 
Top