Chilkat Examples

ChilkatHOME.NET Core C#Android™AutoItCC#C++Chilkat2-PythonCkPythonClassic ASPDataFlexDelphi ActiveXDelphi DLLGoJavaLianjaMono C#Node.jsObjective-CPHP ActiveXPHP ExtensionPerlPowerBuilderPowerShellPureBasicRubySQL ServerSwift 2Swift 3,4,5...TclUnicode CUnicode C++VB.NETVBScriptVisual Basic 6.0Visual FoxProXojo Plugin

DataFlex Examples

Web API Categories

ASN.1
AWS KMS
AWS Misc
Amazon EC2
Amazon Glacier
Amazon S3
Amazon S3 (new)
Amazon SES
Amazon SNS
Amazon SQS
Async
Azure Cloud Storage
Azure Key Vault
Azure Service Bus
Azure Table Service
Base64
Bounced Email
Box
CAdES
CSR
CSV
Certificates
Cloud Signature CSC
Code Signing
Compression
DKIM / DomainKey
DNS
DSA
Diffie-Hellman
Digital Signatures
Dropbox
Dynamics CRM
EBICS
ECC
Ed25519
Email Object
Encryption
FTP
FileAccess
Firebase
GMail REST API
GMail SMTP/IMAP/POP
Geolocation
Google APIs
Google Calendar
Google Cloud SQL
Google Cloud Storage
Google Drive
Google Photos
Google Sheets
Google Tasks
Gzip
HTML-to-XML/Text
HTTP

HTTP Misc
IMAP
JSON
JSON Web Encryption (JWE)
JSON Web Signatures (JWS)
JSON Web Token (JWT)
Java KeyStore (JKS)
MHT / HTML Email
MIME
MS Storage Providers
Microsoft Graph
Misc
NTLM
OAuth1
OAuth2
OIDC
Office365
OneDrive
OpenSSL
Outlook
Outlook Calendar
Outlook Contact
PDF Signatures
PEM
PFX/P12
PKCS11
POP3
PRNG
REST
REST Misc
RSA
SCP
SCard
SFTP
SMTP
SSH
SSH Key
SSH Tunnel
ScMinidriver
Secrets
SharePoint
SharePoint Online
Signing in the Cloud
Socket/SSL/TLS
Spider
Stream
Tar Archive
ULID/UUID
Upload
WebSocket
XAdES
XML
XML Digital Signatures
XMP
Zip
curl
uncategorized

 

 

 

(DataFlex) Firebase Receive Server-Sent Events (text/event-stream)

Demonstrates how to start receiving server-sent events and update your JSON database with each event.

Chilkat ActiveX Downloads

ActiveX for 32-bit and 64-bit Windows

Use ChilkatAx-win32.pkg

Procedure Test
    Handle hoFac
    String sAccessToken
    Handle hoRest
    Boolean iSuccess
    Variant vAuthGoogle
    Handle hoAuthGoogle
    String sResponseBody
    Variant vUrl
    Handle hoUrl
    Handle hoRest2
    Integer iResponseStatusCode
    Handle hoJsonDb
    Variant vEventStream
    Handle hoEventStream
    Handle hoSse
    Variant vTask
    Handle hoTask
    Integer iCount
    String sEventStr
    String sTemp1
    String sTemp2
    Integer iTemp1
    Boolean bTemp1

    // Demonstrates how to begin receiving server-sent events, and to update
    // your JSON database for each event.

    // This example requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    // This example assumes a JWT authentication token, if required, has been previously obtained.
    // See Get Firebase Access Token from JSON Service Account Private Key for sample code.

    // Load the previously obtained Firebase access token into a string.
    Get Create (RefClass(cComCkFileAccess)) To hoFac
    If (Not(IsComObjectCreated(hoFac))) Begin
        Send CreateComObject of hoFac
    End
    Get ComReadEntireTextFile Of hoFac "qa_data/tokens/firebaseToken.txt" "utf-8" To sAccessToken
    Get ComLastMethodSuccess Of hoFac To bTemp1
    If (bTemp1 <> True) Begin
        Get ComLastErrorText Of hoFac To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatRest)) To hoRest
    If (Not(IsComObjectCreated(hoRest))) Begin
        Send CreateComObject of hoRest
    End

    // Make the initial connection (without sending a request yet).
    // Once connected, any number of requests may be sent.  It is not necessary to explicitly
    // call Connect before each request.  
    Get ComConnect Of hoRest "chilkat.firebaseio.com" 443 True True To iSuccess
    If (iSuccess <> True) Begin
        Get ComLastErrorText Of hoRest To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatAuthGoogle)) To hoAuthGoogle
    If (Not(IsComObjectCreated(hoAuthGoogle))) Begin
        Send CreateComObject of hoAuthGoogle
    End
    Set ComAccessToken Of hoAuthGoogle To sAccessToken
    Get pvComObject of hoAuthGoogle to vAuthGoogle
    Get ComSetAuthGoogle Of hoRest vAuthGoogle To iSuccess

    Get ComAddHeader Of hoRest "Accept" "text/event-stream" To iSuccess
    Get ComAddHeader Of hoRest "Cache-Control" "no-cache" To iSuccess

    Get ComFullRequestNoBody Of hoRest "GET" "/.json" To sResponseBody

    // A 307 redirect response is expected.
    Get ComResponseStatusCode Of hoRest To iTemp1
    If (iTemp1 <> 307) Begin
        Get ComResponseStatusCode Of hoRest To iTemp1
        Showln "Unexpected response code: " iTemp1
        Showln sResponseBody
        Showln "Failed."
        Procedure_Return
    End

    // Get the redirect URL
    Get ComRedirectUrl Of hoRest To vUrl
    If (IsComObject(vUrl)) Begin
        Get Create (RefClass(cComChilkatUrl)) To hoUrl
        Set pvComObject Of hoUrl To vUrl
    End
    Get ComLastMethodSuccess Of hoRest To bTemp1
    If (bTemp1 <> True) Begin
        Get ComLastErrorText Of hoRest To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Get ComHost Of hoUrl To sTemp1
    Showln "redirect URL domain: " sTemp1
    Get ComPath Of hoUrl To sTemp1
    Showln "redirect URL path: " sTemp1
    Get ComQuery Of hoUrl To sTemp1
    Showln "redirect URL query params: " sTemp1
    Get ComPathWithQueryParams Of hoUrl To sTemp1
    Showln "redirect URL path with query params: " sTemp1

    // Our text/event-stream will be obtained from the redirect URL...
    Get Create (RefClass(cComChilkatRest)) To hoRest2
    If (Not(IsComObjectCreated(hoRest2))) Begin
        Send CreateComObject of hoRest2
    End

    Get ComHost Of hoUrl To sTemp1
    Get ComConnect Of hoRest2 sTemp1 443 True True To iSuccess
    If (iSuccess <> True) Begin
        Get ComLastErrorText Of hoRest2 To sTemp1
        Showln sTemp1
        Send Destroy of hoUrl
        Procedure_Return
    End

    Get ComAddHeader Of hoRest2 "Accept" "text/event-stream" To iSuccess
    Get ComAddHeader Of hoRest2 "Cache-Control" "no-cache" To iSuccess

    // Add the redirect query params to the request
    Get ComQuery Of hoUrl To sTemp1
    Get ComAddQueryParams Of hoRest2 sTemp1 To iSuccess

    // In our case, we don't actually need the auth query param,
    // so remove it.
    Get ComRemoveQueryParam Of hoRest2 "auth" To iSuccess

    // Send the request.  (We are only sending the request here.
    // We are not yet getting the response because the response
    // will be a text/event-stream.)
    Get ComPath Of hoUrl To sTemp1
    Get ComSendReqNoBody Of hoRest2 "GET" sTemp1 To iSuccess
    If (iSuccess <> True) Begin
        Get ComLastErrorText Of hoRest2 To sTemp1
        Showln sTemp1
        Send Destroy of hoUrl
        Procedure_Return
    End

    Send Destroy of hoUrl

    // Read the response header.  
    // We want to first get the response header to see if it's a successful
    // response status code.  If not, then the response will not be a text/event-stream
    // and we should read the response body normally.
    Get ComReadResponseHeader Of hoRest2 To iResponseStatusCode
    If (iResponseStatusCode < 0) Begin
        Get ComLastErrorText Of hoRest2 To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    // If successful, a 200 response code is expected.
    // If the reponse code is not 200, then read the response body and fail..
    If (iResponseStatusCode <> 200) Begin
        Showln "Response Code: " iResponseStatusCode
        Get ComResponseStatusText Of hoRest2 To sTemp1
        Showln "Response Status Text: " sTemp1
        Get ComResponseHeader Of hoRest2 To sTemp1
        Showln "Response Header: " sTemp1
        Get ComReadRespBodyString Of hoRest2 To sResponseBody
        Get ComLastMethodSuccess Of hoRest2 To bTemp1
        If (bTemp1 = True) Begin
            Showln "Error Response Body: " sResponseBody
        End

        Showln "Failed."
        Procedure_Return
    End

    // For this example, our JSON database will be empty at the beginning.
    // The incoming events (put and patch) will be applied to this database.
    Get Create (RefClass(cComChilkatJsonObject)) To hoJsonDb
    If (Not(IsComObjectCreated(hoJsonDb))) Begin
        Send CreateComObject of hoJsonDb
    End

    // Make sure to set the JSON path delimiter to "/".  The default is "." and this
    // is not compatible with Firebase paths.
    Set ComDelimiterChar Of hoJsonDb To "/"

    // At this point, we've received the response header.  Now it's time to begin
    // receiving the event stream.  We'll start a background thread to read the 
    // stream.  (Our main application (foreground) thread can cancel it at any time.)  
    // While receiving in the background thread, our foreground thread can read the stream
    // as it desires..
    Get Create (RefClass(cComChilkatStream)) To hoEventStream
    If (Not(IsComObjectCreated(hoEventStream))) Begin
        Send CreateComObject of hoEventStream
    End

    // This sse object will be used as a helper to parse the server-sent event stream.
    Get Create (RefClass(cComChilkatServerSentEvent)) To hoSse
    If (Not(IsComObjectCreated(hoSse))) Begin
        Send CreateComObject of hoSse
    End

    Get pvComObject of hoEventStream to vEventStream
    Get ComReadRespBodyStreamAsync Of hoRest2 vEventStream True To vTask
    If (IsComObject(vTask)) Begin
        Get Create (RefClass(cComChilkatTask)) To hoTask
        Set pvComObject Of hoTask To vTask
    End
    Get ComRun Of hoTask To iSuccess

    // For this example, we'll just read a few events, and then cancel the
    // async task.
    Move 0 To iCount
    While ((iCount < 3) And ((ComFinished(hoTask)) = False))

        // Get the next event, which is a series of text lines ending with
        // a blank line. 
        // Note: This method blocks the calling thread until a message arrives.
        // a program might instead periodically check the availability of
        // data via the stream's DataAvailable property, and then do the read.

        // An alternative to writing a while loop to read the event stream
        // would be to setup some sort of timer event in your program (using whatever timer functionality
        // is provided in a programming language/environment), to periodically check the eventStream's
        // DataAvailable property and consume the incoming event.
        Get ComReadUntilMatch Of hoEventStream (character(13)) + (character(10)) + (character(13)) + (character(10)) To sEventStr
        Get ComLastMethodSuccess Of hoEventStream To bTemp1
        If (bTemp1 <> True) Begin
            Get ComLastErrorText Of hoEventStream To sTemp1
            Showln sTemp1
            // Force the loop to exit by setting the count to a high number.
            Move 99999 To iCount
        End
        Else Begin
            Showln "Event: [" sEventStr "]"

            // We have an event. Let's update our local copy of the JSON database.
            Get ComLoadEvent Of hoSse sEventStr To iSuccess
            If (iSuccess <> True) Begin
                Showln "Failed to load sse event: " sEventStr
            End
            Else Begin
                // Now we can easily access the event name and data, and apply it to our JSON database:
                Get ComEventName Of hoSse To sTemp1
                Get ComData Of hoSse To sTemp2
                Get ComFirebaseApplyEvent Of hoJsonDb sTemp1 sTemp2 To iSuccess
                If (iSuccess <> True) Begin
                    Get ComEventName Of hoSse To sTemp1
                    Get ComData Of hoSse To sTemp2
                    Showln "Failed to apply event: " sTemp1 ": " sTemp2
                End
                Else Begin
                    Get ComEventName Of hoSse To sTemp1
                    Get ComData Of hoSse To sTemp2
                    Showln "Successfully applied event: " sTemp1 ": " sTemp2
                End

            End

        End

        Move (iCount + 1) To iCount
    Loop

    // Make sure the background task is cancelled if still running.
    Get ComCancel Of hoTask To iSuccess

    Send Destroy of hoTask

    // Examine the JSON database after applying events..
    Set ComEmitCompact Of hoJsonDb To False
    Showln "----"
    Get ComEmit Of hoJsonDb To sTemp1
    Showln sTemp1


End_Procedure

 

© 2000-2024 Chilkat Software, Inc. All Rights Reserved.