Develop an Oracle JET Hybrid Application for Oracle Mobile Hub

You can create hybrid mobile applications using Oracle JET and integrate them with Oracle PaaS solutions like Oracle Mobile Hub.

Before You Begin

Before you begin developing a JET application, you need to meet the following prerequisites:
  • Make sure you have configured your Hybrid Mobile Development Environment.
  • Make sure you have access to an Oracle Mobile Hub instance.

About the Architecture of Oracle JET Hybrid Mobile Applications

An Oracle JET hybrid mobile application is a single page application (SPA) served from a single HTML page or view. This means that multiple views can exist on separate files, but the application will always render them as a single web page. This behavior is very similar to a native application (an application developed with native OS APIs), thus providing a fluid user experience.

Apache Cordova is an open-source mobile development framework that supports standard web technologies like HTML5, CSS3 and JavaScript for cross-platform development. Oracle JET hybrid mobile applications execute within Cordova wrappers targeted to different mobile platforms like iOS, Android and Windows.

The following image depicts the typical architecture of a Cordova hybrid application:

Description of cordova_arch.png follows
Description of the illustration cordova_arch.png

cordova_arch-oracle.zip

In a Cordova Architecture, the application view (typically composed of HTML, JS and CSS files) is displayed on a native Operating System wrapper that internally works as a web browser. The Cordova API also provides plugins to communicate with mobile operating systems through Core OS APIs, these APIs allow you to access mobile operating system components like contacts, address list, localization, notifications, and more.

Configure Your Oracle JET Hybrid Mobile Application

Before writing the code for your hybrid mobile application, you must configure your hybrid mobile application. For that purpose, use the ojet create command to scaffold the folder structure and the overall template for your application.

To configure your hybrid mobile application:
  1. Make sure you have installed Oracle JET tooling framework.
  2. Scaffold the application by running the ojet create [directory] --hybrid command in your Node.js console to generate a hybrid application template for Android, iOS and Windows:
    ojet create [directory] --hybrid
                [--appid=<application-id>] [--appname=<application-name>]
                [--template={<template-name>:[web|hybrid]|<template-url>|<template-file>}]
                [--platforms=android,ios,windows|--platform=android|ios|windows]

    This example shows how to generate a hybrid application template for Android, iOS and Windows :

    ojet create myApp --hybrid
                --appid=org.oraclejet.MyApp --appname="mySampleApp"
                --template="C:\Users\SomeUser\app.zip"
                --platforms=android,ios,windows
  3. Add the Cordova plugins:
    To integrate your hybrid mobile application with Oracle Mobile Hub, you need to add the following plugins:
    • oracle-mobile-cloud-cookies: A plugin for authenticating with Oracle Mobile Hub via SSO

    • cordova-plugin-inappbrowser: A plugin to provide a web browser view, required for displaying the SSO login page

    To add these plugins:

    1. Log in to Oracle Mobile Hub.
    2. Click Applications.
    3. Click SDK Downloads. This takes you to the SDK Downloads page.
    4. Click on Download Cordova SDK.
    5. Unzip the package.
    6. In the extracted package, look for the oracle_mobile_js_sdk_cookies_cordova_plugin[VERSION].zip, where you can find the oracle-mobile-cloud-cookies plugin.
    7. To install the oracle-mobile-cloud-cookies plugin, unzip oracle_mobile_js_sdk_cookies_cordova_plugin[VERSION].zip, and run the following cordova command:
      cordova plugin add <PLUGIN_FOLDER>

      Where <PLUGIN_FOLDER> is the path to the unpacked plugin.

    8. To install the cordova-plugin-inappbrowser plugin, run the following cordova command to add it to your project:
      cordova plugin add cordova-plugin-inappbrowser –save
  4. Add the Oracle Mobile Hub Cordova SDK to your application, copy msc.js, msc.min.js, and oracle_mobile_cloud_config.js in a directory where you will keep your JavaScript files.
  5. Update the path mappings for mcs and mcs_cloud_config in the requirejs.config section of your Oracle JET path_mappings.json file.
    
    requirejs.config({
        baseUrl: 'js',
        // Path mappings for the logical module names
        paths:
        //injector:mainReleasePaths
        {
            'knockout': 'libs/knockout/knockout-3.4.0.debug',
            'jquery': 'libs/jquery/jquery-2.1.3',
            'jqueryui-amd': 'libs/jquery/jqueryui-amd-1.11.4',
            'promise': 'libs/es6-promise/promise-1.0.0',
            'hammerjs': 'libs/hammer/hammer-2.0.4',
            'ojdnd': 'libs/dnd-polyfill/dnd-polyfill-1.0.0',
            'ojs': 'libs/oj/v2.0.2/debug',
            'ojL10n': 'libs/oj/v2.0.2/ojL10n',
            'ojtranslations': 'libs/oj/v2.0.2/resources',
            'text': 'libs/require/text',
            'signals': 'libs/js-signals/signals',
               'mcs': 'libs/mcs/mcs',
               'mcsconf': 'libs/mcs/oracle_mobile_cloud_config'
        }
        //endinjector
        ,
        // Shim configurations for modules that do not expose AMD
        shim: {
            'jquery': {
                exports: ['jQuery', '$']
            }
        }
    });
  6. Update oracle_mobile_cloud_config.js with your mobile backend details:
    var mcs_config = {
      "logLevel": 3,
      "mobileBackends": {
        "RDXTESTSSO": {
          "default": true,
          "baseUrl": "<YOUR_BASE_URL>",
          "applicationKey": "<YOUR_BACKEND_APPLICATION_KEY>",
          "synchronization": {
            "periodicRefreshPolicy": "PERIODIC_REFRESH_POLICY_REFRESH_NONE",
            "policies": [{
              "path": '/mobile/custom/taskApi/*',
              "fetchPolicy": 'FETCH_FROM_SERVICE_ON_CACHE_MISS_OR_EXPIRY',
              "expiryPolicy": 'EXPIRE_ON_RESTART',
              "evictionPolicy": 'EVICT_ON_EXPIRY_AT_STARTUP',
              "updatePolicy": 'QUEUE_IF_OFFLINE',
              "noCache": false
            }, {
              "path": '/mobile/custom/firstApi/tasks',
              "fetchPolicy": 'FETCH_FROM_SERVICE_ON_CACHE_MISS'
            }, {
              "path": '/mobile/custom/secondApi/tasks',
            }],
            "default": {
              "fetchPolicy": 'FETCH_FROM_SERVICE_IF_ONLINE',
              "expiryPolicy": 'EXPIRE_ON_RESTART'
            }
          },
          "authorization": {
            "basicAuth": {
                "backendId": "<YOUR_BACKEND_ID>",
                "anonymousToken": "<YOUR_BACKEND_ANONYMOUS_TOKEN>"
            },
            "oAuth": {
               "clientId": "<YOUR_CLIENT_ID>",
                  "clientSecret": "<YOUR_CLIENT_SECRET>",
                  "tokenEndpoint": "<YOUR_TOKEN_ENDPOINT>"
            },
            "facebookAuth": {
               "facebookAppId": "<YOUR_FACEBOOK_APP_ID>",
                  "backendId": "<YOUR_BACKEND_ID>",
                  "anonymousToken": "<YOUR_BACKEND_ANONYMOUS_TOKEN>"
            },
            "ssoAuth": {
               "clientId": "<YOUR_CLIENT_ID>",
                  "clientSecret": "<YOUR_ClIENT_SECRET>",
                  "tokenEndpoint": "<YOUR_SSOAUTH_TOKEN_ENDPOINT>"
            }
          }
        }
      }
    };

Integrate Your Oracle JET Hybrid Mobile Application with Oracle Mobile Hub

You can integrate your Oracle JET hybrid application with a backend mobile service like Oracle Mobile Hub to fetch REST data from federated Oracle SaaS applications like Oracle Fusion Cloud Sales Automation.

To integrate your Oracle JET hybrid mobile application with Oracle Mobile Hub:
  1. Make sure you have 'mcs', 'mcsconf' configured in the path_mappings.json file configuration. For example, these modules can be loaded from a require statement:
    require(['ojs/ojcore', 'knockout', 'jquery', 'mcs', 'mcsconf', 'ojs/ojknockout', 'ojs/ojfilmstrip', 'ojs/ojpagingcontrol', 'ojs/ojbutton']

    Where mcs and mcsconf are the path names you declared under requires.config object in your main.js file.

  2. Load the Oracle Mobile Hub configuration into your application:
    mcs.MobileBackendManager.platform = new mcs.CordovaPlatform();
    mcs.MobileBackendManager.setConfig(mcs_config);
    backend = mcs.MobileBackendManager.getMobileBackend("[YOUR_MOBILE_HUB_BACKEND]");
    if (backend != null) {
      backend.setAuthenticationType("ssoAuth");
      //other code to login to Mobile Hub or function call
    }

    Where msc_config is the configuration object you defined when you configured your Oracle JET hybrid mobile application.

  3. Authenticate using the Authorization object. For example, to authenticate using the “backend” variable used in the previous step:
    backend.Authorization.authenticate(
      function(statusCode, data) {
        console.log(data);
        console.log(statusCode);
        alert("SSO Login success, status:" + statusCode);
        fetchSalesCloudData(data.access_token);
      },
      function(statusCode, data) {
        console.log(statusCode + " with message:  " + data);
        alert("SSO Login failed, statusCode" + statusCode);
      });

    The backend’s Authorization.authenticate method takes two functions as parameters. The first function executes if the authentication is successful, while the second one executes if the authentication fails.

  4. Call the Oracle Mobile Hub API by including the authorization header. You have to include the given token in the authorization header within a settings object passed to the jQuery AJAX call. For example, if you want to fetch data from an Oracle Fusion Cloud Sales Automation custom REST API created within Oracle Mobile Hub:
    function fetchSalesCloudData(ssoToken) {
        var mcsbackendURL = mcs_config.mobileBackends.RDXTESTSSO.baseUrl + "/mobile/custom/RDHSalesApplAPI/opportunities"; //custom API URL
        console.log(mcsbackendURL);
        var token = "Bearer " + ssoToken;
        //console.log(token);
        var settings = {
            "async": true,
            "crossDomain": true,
            "url": mcsbackendURL,
            "method": "GET",
            "headers": {
                "authorization": token
            }
        };
        $.ajax(settings).done(function(response) {
            console.log(response);
            $.each(response, function() {
                self.data.push({
                    Name: this.Name,
                    OptyId: this.OptyId,
                    OptyNumber: this.OptyNumber,
                    SalesStage: this.SalesStage,
                    Revenue: this.Revenue
                });
            });
            self.dataReady = true;
            displaySalesCloudData();
        });
    }

    In the previous example, the settings variable is passed to the jQuery AJAX REST call. The settings variable contains a headers parameter in which the authorization parameter contains the access token. Also note that there is a crossDomain parameter that is used to indicate that cross-domain communication will happen.

    At this point, you have made an AJAX call. However as an alternative option, you can also call custom APIs from custom code.

  5. Display the data fetched from the REST call. For example, you can use an Oracle JET filmstrip object:
        function displaySalesCloudData() {
    
          console.log("inside displayFilmStrip");
          self.pagingModel = null;
          getItemInitialDisplay = function(index) {
              return index < 1 ? '' : 'none';
          };
          getPagingModel = function() {
              if (!self.pagingModel) {
                  var filmstrip = document.getElementById('<element id>');
                  filmstrip.getPagingModel;              
                  self.pagingModel = pagingModel;
              }
              return self.pagingModel;
          };
      }

    Where <element id> is the HTML element where the data will be displayed.

Build and Test Your Oracle JET Hybrid Mobile Application

Before executing your Oracle JET hybrid mobile application for the first time, you need to run a build targeted for a mobile platform.

Run the ojet build os command to automate the build and testing process. Execute the following command in your Node.js command prompt:

ojet build [android|ios|windows]
           [--build-config=path/buildConfig.json --destination=device|emulator
            --theme=themename[:android|ios|web|windows] --themes=theme1,theme2,... 
            --sass
            --platform-options="string"]

Where [android|ios|windows] is the platform on which you want to test your application. For example, if you’re testing on an Android emulator, the command is:

ojet build android

Once the build is complete, run the application by using the ojet serve os command:

ojet serve [android|ios|windows]
           [--build-config=path/buildConfig.json
            --server-port=server-port-number --livereload-port=live-reload-port-number
            --destination=emulator[:emulator-name]|browser[:browser-name]|device[:device-name]|server-only
            --livereload --build
            --theme=theme_name[:android|ios|windows|web]] --themes=theme1,theme2,... 
            --sass
            --platform-options="string"]
Where [android|ios|windows] is the platform on which you want to test your application. For example, if you’re testing on an Android emulator, the command is:
ojet serve android