Skip to main content

Push Notification for Andriod MAF application via MCS

Part 1 : Configure MCS Backend with Google Project ID

Step #1: Register yourself for Google Cloud Messaging :

There are several tutorials available online to guide you to do this. Some examples :
http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/
https://mixpanel.com/help/reference/android-push-notifications

Once you have registered there are 4 things which are important and will be used in later part of this blog :
Project Number
Browser API Key
Name
Make sure the "Google Cloud Messaging for Android" is enabled for this Project. 





Step #2 : Configure MCS backend with the Step#1 details

Create an Mobile Backend. Then go to your Mobile Backend Settings page. There will be a default Client Application created for you. Click on Edit and do the following.




In the above picture

Application Name and ID = Google Project Name
API Key = Google Browser API Key
Sender ID = Google Project Number

Now your backend is configured and ready to send Push Notifications.
Next step is to configure your MAF application.

Part 2 : MAF application 

For a mobile app to receive push notification, the mobile app should "register" itself with MCS backend first. This is an one time activity. As a developer/designer you need to find a right component to call the register URI. I tried to do this inside LifeCycleListenerImpl, but it didn't work, so I moved it to my datacontrol class and made sure it is being called only once.
This registration process will intern register your app with Google Messaging Service.

Below are the important steps and code snippets for the MAF application.
1. Create a simple MAF application.
2. Create a PushNotificationListener class inside ApplicationController project.

import oracle.adfmf.framework.event.EventListener;

public class PushNotificationListener implements EventListener {
   
    public final static String PUSH_MESSAGE             =   "#{applicationScope.push_message}";
    public final static String MCS_REGISTRATION_STRING  =   "#{applicationScope.mcsregistrationString}";
    public final static String PUSH_ERROR               =   "#{applicationScope.push_errorMessage}";
    public final static String PUSH_DEVICE_TOKEN         =   "#{applicationScope.deviceToken}";  
   
    public PushNotificationListener() {
        super();
    }

    @Override
    public void onOpen(String token) {
        // Clear error in app scope
        AdfmfJavaUtilities.setELValue(PUSH_ERROR, null);       
        // Write the token into app scope       
        AdfmfJavaUtilities.setELValue(PUSH_DEVICE_TOKEN,token);
    }

    @Override
    public void onMessage(Event event) {
        String msg = event.getPayload();               
        //set push message to application scope memory attribute for
        //display in the view.
        AdfmfJavaUtilities.setELValue(PUSH_MESSAGE, msg); 
     }

    @Override
    public void onError(AdfException adfException) {
       
        Utility.ApplicationLogger.logp(Level.WARNING, this.getClass().getSimpleName(), "PushHandler::onError",
                                       "Message = " + adfException.getMessage() + "\nSeverity = " +
                                       adfException.getSeverity() + "\nType = " + adfException.getType());
        AdfmfJavaUtilities.setELValue(PUSH_ERROR, adfException.toString());
    }
}


3. Edit LifeCycleListenerImpl to implement PushNotificationConfig interface. This will require you to override 2 methods. You also need to update start() method of this class.

  public void start()  {
    Utility.ApplicationLogger.logp(Level.FINE, this.getClass().getSimpleName(), "LifeCycleListener::start()","Push is enabled for application");         
    EventSource evtSource = EventSourceFactory.getEventSource(EventSourceFactory.NATIVE_PUSH_NOTIFICATION_REMOTE_EVENT_SOURCE_NAME);
    evtSource.addListener(new PushNotificationListener());    
  }


    @Override
    public long getNotificationStyle() {
        return PushNotificationConfig.NOTIFICATION_STYLE_ALERT | PushNotificationConfig.NOTIFICATION_STYLE_BADGE | PushNotificationConfig.NOTIFICATION_STYLE_SOUND;
    }

    @Override
    public String getSourceAuthorizationId() {       
        String senderId = "<GOOGLE_PROJECT_ID>"; //
Google Project Number        ValueExpression ve = AdfmfJavaUtilities.getValueExpression("#{applicationScope.applicationId}", String.class);
        ve.setValue(AdfmfJavaUtilities.getAdfELContext(), senderId);
        return senderId;
    }


4.  Code snippets to register your app with MCS. (You also need to create a dummy REST connection)

// Step 1 : connect to MCS backend
        String mobileBackendUrl = "<URL_MCS>";
        //clear
        AdfmfJavaUtilities.clearSecurityConfigOverrides("<NAME_OF_DUMMY_CONN>");
        //override
        AdfmfJavaUtilities.overrideConnectionProperty("
<NAME_OF_DUMMY_CONN>", "restconnection", "url", mobileBackendUrl);
        String mobileBackendId =  "<MCS_BACKEND_ID>";
        String mbeAnonymousKey =  "<MBE_ANONYMOUS_KEY>";
        String appKey =    "<APP_KEY_FROM_MCS>";

        MBEConfiguration mbeConfiguration = new MBEConfiguration("
<NAME_OF_DUMMY_CONN>", mobileBackendId, mbeAnonymousKey, appKey,
                                                                 MBEConfiguration.AuthenticationType.BASIC_AUTH);

        mbeConfiguration.setEnableAnalytics(true);
        mbeConfiguration.setLoggingEnabled(true);

        mbeConfiguration.setMobileDeviceId(DeviceManagerFactory.getDeviceManager().getName());
        MBE mobileBackend = MBEManager.getManager().createOrRenewMobileBackend(mobileBackendId, mbeConfiguration);
       
        mobileBackend.getMbeConfiguration().getLogger().logFine("Anonymous authentication invoked from DC", this.getClass().getSimpleName(), "anonymousLogin"); 

// Step 2 : login to MCS backend
        Authorization authorization = mobileBackend.getAuthorizationProvider();
        try {
            authorization.authenticateAsAnonymous();
        } catch (ServiceProxyException e) {           
                Utility.ApplicationLogger.log(Level.SEVERE, e.getMessage());
        }

// Step 3 : configure MBE with device id
        String _token = (String) AdfmfJavaUtilities.getELValue("#{applicationScope.deviceToken}");
        mobileBackend.getMbeConfiguration().setDeviceToken(_token);
        String packageName = "<GOOGLE_PROJECT_NAME>"; // com.company.BookMyRoom
        mobileBackend.getMbeConfiguration().setGooglePackageName(packageName);

// Step 4 : call register in a thread
        Runnable mcsJob = new Runnable(){

          public void run(){                                              
             try {
                 Notifications notification = mobileBackend.getServiceProxyNotifications();
                 String registrationInfo = notification.registerDeviceToMCS();
                 AdfmfJavaUtilities.setELValue("#{applicationScope.mcsregistrationString}", registrationInfo);
               } catch (ServiceProxyException e) {
                     Utility.ApplicationLogger.log(Level.SEVERE, e.getMessage());
               }
              //ensure main thread is synchronized with result
              AdfmfJavaUtilities.flushDataChangeEvent();
          }
        };
       
        ExecutorService executor = Executors.newFixedThreadPool(2);
        executor.execute(mcsJob);
        executor.shutdown();

5. Make sure the above code snippet gets called while you open the app for the first time. What I did was. created a simple app with 1 feature, with a taskFlow. Taskflow does a method call which executes the above snippet and then opens a simple AMX page. 

Part 3 : Send a Push Notification using JQuery

I have used a simple HTML page to test my push notification setup. But you can also test your setup from MCS itself. (In Mobile Backend > Notifications)

In my HTML I have button which call the below function to send a pre-defined message.

In below javascript :
ENCODED_USER_NAME_AND_PASSWORD : is the encoded user name and password in base64. I used www.base64encode.org to encode. Your encode string should be: username:password, i.e., xyz:abc. If xyz is your username and abc is your password to login to MCS.

    function SendPushNotification() {
    var dataInput = {
        "message": "Test Message",
    };
    $.ajax({
        url: "<URL_OF_MCS>/mobile/system/notifications/notifications",
        headers:
            {
                'Authorization' : 'Basic <ENCODED_USER_NAME_AND_PASSWORD>',
                'oracle-mobile-backend-id' : '<MCS_BACKEND_ID>'
            },
        method: "POST",
        contentType: "application/json; charset=UTF-8",
        dataType: "json",
        data: JSON.stringify(dataInput),
        processData: true,
        error: function (xhr) {
            alert("error: " + xhr);
        }
    });
    }


Acknowledgements :
Special Thanks for Arjan Kramer(@arjankramer) for the contribution on JQuery part. 
Many thanks to Frank Nimphius (@fnimphiu) for MCSSampleAndUtilities.


Comments

  1. Is this above example for Oracle MCS and Oracle MAF?Would you know if Oracle provides any demo access to MCS?

    ReplyDelete
    Replies
    1. Hi Deepika,

      Oracle does provide demo access to MCS for partners. You need to ask your Oracle contact for more details, it may vary country to country and partner to partner.
      Hope this helps.

      - Soham

      Delete

Post a Comment

Popular posts from this blog

Exception Handling in ADF

This blog will give you an overview on how you can successfully deal with unhandled Runtime exceptions in an ADF application.

This will give you an idea of:
How to catch the unhandled exceptions.Write a separate log file with stacktrace and thread dumps.Redirect the user to an static error page
#1. Catch unhandled exceptions : 

Create a class "MyExceptionHandler" which extends : oracle.adf.view.rich.context.ExceptionHandler. Override handleException() method.

public void handleException(FacesContext facesContext, Throwable throwable, PhaseId phaseId) throws Throwable {
        // this method is going to create a separate file with stacktrace and thread dumps
        writeException(throwable);
        // redirect to error page
        redirectToErrorPage(facesContext);
    }

 Create a folder "services" inside : ViewController\src\META-INF and then create a file named "oracle.adf.view.rich.context.ExceptionHandler".
In the file, add the absolute name of your custom e…

Bean Based ADF Table with List View in detailStamp facet

One of our projects, we had to display a "tree type" table with different datamodel for children. To solve this, I choose a normal af:table with a detailStamp facet with a List view inside it.
But pretty soon, I ran into an issue of correctly identifying the "disclosed" rows. Since my table's datasource is a bean, not ADF managed datacontrol.

So I solved it using a discloseListener on the af:table.

Full Application is on GitHub : https://github.com/sohamda/Row-Disclose-Example/


Classes invloved :

1. POJO.java : dataProvider class for af:table
2. SubPOJO.java : dataProvider for the list view inside detailStamp of the table.
3. TableBean.java : provides the methods for populating af:table and af:listView. Also has a discloseListener method to correctly populate the listView datasource.

af:table definition :

Chatbots and Oracle Cloud Services

Thanks to Oracle A-Team, I had a chance to work with Chatbots.
3 pure NodeJS applications, on couple of Oracle Cloud platforms and Facebook messenger, and my chatbot was running.

Let me explain, the architecture a bit. To start with, following is the simple representation of how it works.