B4J Tutorial Pakai framework v6

Part #1: Get Started

Introduction

This tutorial is based on [Project Template] Pakai Server v6.

Installation
  1. Download and put the following files to Additional Libraries folder
    B4J
    - Pakai Server (6.00) starter b4xtemplate (28KB)
    - EndsMeet (v1.70) b4xlib (5KB)
    B4X
    - MiniHtml (v0.60) b4xlib (37KB)
    - MiniJs (v0.20) b4xlib (3KB)
    - MiniORMUtils (v3.90) b4xlib (14KB)
Create a Project
  1. Start B4J IDE
  2. Select New from File menu and click on Pakai Server (6.00) starter
    1762847613502.png
  3. Confirm the Project Folder
  4. Enter the Project Name as you desired then click OK button.
    1762847790267.png
  5. A project is created and ready to run under the default settings.
Running the Project
  1. Click Compile & Run (F5) from the Project menu or click the play button on the toolbar.
  2. When the project has finished to compile for the first time, you will see a message in the Logs saying "Database is created successfully!".
    1762848161210.png
  3. You can click on the AppStart macro on the IDE window title and hover you mouse pointer to the AppStart sub.
  4. Click on the highlighted link to open the app on your web browser.
    1762848445229.png
  5. The index page will be loaded. It shows a web application with CRUD functionality.
    1762849041784.png
  6. You can add a new product (Create)
  7. You can search for a product (Read)
  8. You can edit an existing product (Update) and
    1762850433714.png
  9. You can delete a product (Delete).
    1762849831110.png
  10. You can navigate to the Categories page.
  11. If your page width is small and you don't see the Categories menu, you can click the hamburger menu on top right corner to toggle the menu list.
    1762849321271.png
  12. A toast message will appear at the bottom right after you made changes to the database.
    1762850064400.png
  13. If you try to delete a Category with associated Products, an error message will be showed.
    1762850772698.png
  14. If you try to add a Product without providing the required fields, a pop up dialog will showed indicated the fields are required.
    1762851365146.png
 
Last edited:

aeric

Expert
Licensed User
Longtime User
Part #2: Server Configuration

The server configuration is handled by EndsMeet library.
  1. The server is initialized with some default settings.
  2. The server settings can be modified by calling:
    B4X:
    App.LoadConfig
  3. This will create a config.ini file inside the Objects folder when the server starts.
  4. You can open the file using any text editor and update the settings.
  5. Line begins with # is disabled.
    B4X:
    #API_VERSIONING=True
  6. All the key-values in config.ini file are read into a global map object name ctx in Main module.
  7. By default, some of these keys such as port and ssl settings are no longer required and removed when the server starts.
  8. Please note that not all settings can be changed using the config.ini

App constants
  • APP_TITLE
    Set the title for the browser tab
  • APP_TRADEMARK
    Set the name beside the logo on navigation bar
  • APP_COPYRIGHT
    Set the copyright text at the footer
  • HOME_TITLE
    Set the title appearing on home page
  • ROOT_URL
    default: http://127.0.0.1
    Set the server URL appears in html especially for loading asset files. Use a domain name during production.
  • ROOT_PATH
    default: <empty>
    You can set to the value to other name e.g /web
Server settings
  • PORT
    default: 8080
    Set the server port. Make sure the port number is not used by another service or blocked by the firewall.
  • REDIRECT_TO_HTTPS
    default: False
    Force the server redirect to SSL port and use HTTPS protocol
SSL settings
  1. During development, you can use CMD to call keytool in the JDK path to generate a self signed keystore file.
  2. Put this file in Objects folder and leave the SSL_KEYSTORE_DIR setting as <empty>.
  3. During production, you can use a real certificate or generate one using LetsEncrypt.
  • SSL_ENABLED
    default: False
  • SSL_PORT
    default: 0
    Set SSL port to use HTTPS protocol. This is recommended in production.
  • SSL_KEYSTORE_DIR
    default: <empty>
    Set directory where the SSL keystore is located
  • SSL_KEYSTORE_FILE
    default: <empty>
    Set the keystore file name
  • SSL_KEYSTORE_PASSWORD
    default: <empty>
    Set the keystore password
API settings
  1. API is now optional in Pakai framework v6.00
  2. If you want to integrate API into your server, you need to add WebApiUtils library into your project.
  • API_NAME
    default: api
  • API_VERSIONING
    default: False
    If set to True, you need to handle the uri elements in Api handlers.
  • API_VERBOSE_MODE
    default: True
    Set the API response in verbose format
  • API_ORDERED_KEYS
    default: True
    Set whether the generated API response keys follow specified order

Set Configuration Programmatically
  1. There are other settings available in EndsMeet class that can be set without using config file.
  2. You can set their values after initialized the App object.
  3. Here are the available settings in EndsMeet class that can be overridden:
ApiSettings (api)
- Name​
- Versioning​
- PayloadType​
- ContentType​
- EnableHelp​
- VerboseMode​
- OrderedKeys​
SslSettings (ssl)
- Enabled​
- Port​
- KeystoreDir​
- KeystoreFile​
- KeystorePassword​
CorsSettings (cors)
- Enabled​
- Path​
- Settings​
EmailSettings (email)
- SmtpUserName​
- SmtpPassword​
- SmtpServer​
- SmtpUseSsl​
- SmtpPort​
StaticFilesSettings (staticfiles)
- Folder​
- Browsable​

By default, Payload and ContentType are set to application/json for API settings
This is how to set the values:
B4X:
App.api.ContentType = "application/xml"
' or use WebApiUtils constants
App.api.ContentType = WebApiUtils.MIME_TYPE_XML
 
Last edited:

aeric

Expert
Licensed User
Longtime User
Part #3: Database Configuration

The database configuration is handled by Database class.
  1. In Pakai framework, we use MiniORMUtils to simplify connectivity between database backend.
  2. MiniORMUtils is currently supporting SQLite, MariaDB and MySQL database.
  3. The server settings is set by selecting the Build Configurations from B4J IDE dropdown menu.
  4. By default, SQLite is used especially during development.
  5. A config file with the database type is generated when you compile the project.
  6. For example, the config file for SQLite will look like this:
    sqlite.ini:
    ## SQLite configuration:
    
    DbType=SQLite
    DbDir=
    DbFile=pakai.db
  7. You can change the DbFile as you like e.g app.sqlite
  8. You can leave DbDir as <empty> to store the file inside Objects directory.
  9. During production, if you leave the value as empty, it means same location of the jar file.
  10. If you want to save the file in a different location, you need to set it using forward slash or escape character e.g C:/app/db or C:\\app\\db
SQLite
  • DbType
    Indicate the type of database
  • DbFile
    Set the database file name
  • DbDir
    Default: <empty>
    Set the directory of database
MariaDB / MySQL
  • DbType
    Indicate the type of database
  • DbName
    Set the name of database
  • DbHost
    Set the server name or IP of database
  • DbPort
    default: 3306
    Set the server port of database
  • DriverClass
    Set the driver class of database
  • JdbcUrl
    Set the jdbc url of database
  • User
    Set the user name of database
  • Password
    Set the user password of database
  • MaxPoolSize
    Set the server maximum pool size
 

aeric

Expert
Licensed User
Longtime User
Part #4: Routing Server Handler

EndsMeet has 4 http methods available:
  • Get
  • Post
  • Put
  • Delete
  1. Each route needs to match the handler class correctly.
    B4X:
    App.Get("", "ProductsHandler")
    App.Get("/categories", "CategoriesHandler")
  2. In version 1.60, Rest sub is added to consolidate all 4 http methods into one.
    B4X:
    App.Rest("/api/products/*", "ProductsHandler")
    App.Rest("/api/categories/*", "CategoriesHandler")
  3. If we are not building an API server, we can write a simple If-Else to check and call the sub to output the html back to HTMX on the frontend.
  4. We don't need to separate Web and API handlers. Hence, no need to follow conventions like in previous versions.
  5. Here is what our server handler looks like in Pakai v6.00
    B4X:
    Sub Handle (req As ServletRequest, resp As ServletResponse)
        Request = req
        Response = resp
        Method = req.Method
        Log($"${Request.Method}: ${Request.RequestURI}"$)
        Dim path As String = req.RequestURI
        If path = "/categories" Then
            RenderPage
        Else If path = "/api/categories/table" Then
            HandleTable
        Else If path = "/api/categories/add" Then
            HandleAddModal
        Else If path.StartsWith("/api/categories/edit/") Then
            HandleEditModal
        Else If path.StartsWith("/api/categories/delete/") Then
            HandleDeleteModal
        Else
            HandleCategories
        End If
    End Sub
 

aeric

Expert
Licensed User
Longtime User
I will write separate tutorials for using MiniHtml and MiniORMUtils on Pakai framework v6
 
Top