Wednesday 25 April 2018

A hybrid Android and IOS Mobile Chat app

Project : 
Development of a simple extensible chat 

Technologies and Frameworks
Oracle Mobile Application Framework (MAF)
Oracle Java
RESTful JSON (jersey json)

IDE
Oracle Jdeveloper (still the best Java IDE)

Container
Weblogic (Development and Testing)
TomEE (Production)


Introduction
In one of our organization meeting we decided to embed simple chat module in all our apps developments including IOS, Android and Windows.

For Java lovers oracle MAF have proven to be a complete, stable framework and tools to develop cross platform enterprise mobile application. Its apparently easy to learn without much complications or difficult learning curves. With Oracle MAF you have lots of options to choose from to build a chat system as whatsapp or facebook in days. This is a very basic chat with very few lines of code as shown below. 



Basic Chat


Development


1. Create the ChatSend() action.


package com.softworks.mobile.mola.beans;

import com.softworks.mobile.mola.model.ChatBot;
import com.softworks.mobile.mola.model.UserRegistration;
import com.softworks.mobile.mola.service.HelperClass;
import com.softworks.mobile.mola.service.MolaRestService;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import oracle.adfmf.bindings.iterator.BasicIterator;
import oracle.adfmf.framework.api.AdfmfJavaUtilities;
import oracle.adfmf.java.beans.PropertyChangeListener;
import oracle.adfmf.java.beans.PropertyChangeSupport;
import oracle.maf.api.dc.ws.rest.RestServiceAdapter;

public class ChatBotBean implements Serializable, Runnable {
    @SuppressWarnings("compatibility:-5925689949074430979")
    private static final long serialVersionUID = 1L;
    private String chatsendtext, _chatsendtext;
    private List chatreadlist, chatServList, chatServSummaryList;
    UserRegistration ur = new UserRegistration();
    private PropertyChangeSupport _propertyChangeSupport = new PropertyChangeSupport(this);
    ChatBot cbot = new ChatBot();
    private int chatInit = 0;
    private String chatdate;
    private String currentToken;

    public ChatBotBean() {
        super();
        chatServList = new ArrayList<>();
        chatServSummaryList = new ArrayList<>();
        currentToken = HelperClass.ReadFromJson("deviceToken");
    }

    public void ChatSend() throws InterruptedException {

        if (chatsendtext != null) {
            cbot.setChatDateTime(new SimpleDateFormat("h:mm a").format(new Date()));
            _chatsendtext = chatsendtext;
            setChatsendtext(null);
            chatServList.add(new ChatBot(_chatsendtext, "sent", cbot.getChatDateTime(),
                                         HelperClass.ReadFromJson("username"), cbot.getReceiverUsername()));
            AdfmfJavaUtilities.setELValue("#{applicationScope.chatreadlist}", chatServList);

            Thread s = new Thread(this);

            s.start();       
       }
    }
    private void ChatBotSend() {
        //For each send compare the current device id to the received one to decide what address to send...


        if (chatInit == 0) {
            cbot.setDeviceToken(cbot.getReceiverToken());
           
        }
        if (chatInit == 1 & AdfmfJavaUtilities.getELValue("#{applicationScope.senderTk}") == null) {
            cbot.setDeviceToken(cbot.getReceiverToken());
            
        }

        if (AdfmfJavaUtilities.getELValue("#{applicationScope.senderTk}") != null) {
            if (currentToken.equalsIgnoreCase((String) AdfmfJavaUtilities.getELValue("#{applicationScope.senderTk}"))) { //I am the once sending
                cbot.setDeviceToken(cbot.getReceiverToken());
                
            }
            if (!currentToken.equalsIgnoreCase((String) AdfmfJavaUtilities.getELValue("#{applicationScope.senderTk}"))) {
                cbot.setDeviceToken(cbot.getSenderToken());
                
            }

        }
        chatInit = 1;
  
        try {
            //Users must be signed in to obtained the listing below.
            //cbot.setSenderToken(HelperClass.ReadFromJson("deviceToken"));
            cbot.setUsername(HelperClass.ReadFromJson("username"));
            cbot.setFirstname(HelperClass.ReadFromJson("firstname"));
            cbot.setLastname(HelperClass.ReadFromJson("lastname"));
            cbot.setMessagetext(_chatsendtext);
            cbot.setMessagedate(new Date());
        } catch (NullPointerException npe) {

        }


        String queryString = "cbot";
        String response = MolaRestService.invokeRestService(RestServiceAdapter.REQUEST_TYPE_PUT, queryString, cbot);
        String pushMessage = (String) AdfmfJavaUtilities.getELValue("#{applicationScope.pushMessage}");
        if (response.equalsIgnoreCase("success") & pushMessage != "") {
            if (AdfmfJavaUtilities.getELValue("#{applicationScope.pushMessage}") != null) {
                chatServList.add(new ChatBot((String) AdfmfJavaUtilities.getELValue("#{applicationScope.pushMessage}"),
                                             "received", cbot.getChatDateTime(), cbot.getUsername(),
                                             cbot.getReceiverUsername()));
                AdfmfJavaUtilities.setELValue("#{applicationScope.chatreadlist}", chatServList);
                
            }

        }

    }

    public String InitializeSending() {
        BasicIterator urIterator =
            (BasicIterator) AdfmfJavaUtilities.getELValue("#{bindings.userinformationIterator.iterator}");
        ur = (UserRegistration) urIterator.getDataProvider();
        cbot.setReceiverSurname(ur.getDreg().getSurname());
        cbot.setReceiverFirstname(ur.getDreg().getFirstname());
        cbot.setStateId(ur.getState_id());
        cbot.setUsername(HelperClass.ReadFromJson("username"));
        cbot.setReceiverUsername(ur.getDreg().getRegId());

        //Open communication channel between 2 nodes using address tokens
        cbot.setReceiverToken(ur.getDreg().getDevicetoken());
        cbot.setSenderToken(HelperClass.ReadFromJson("deviceToken"));


        try {
            List _chatHistorySize = new ArrayList<>();

            List _chatHistory =
                (List) AdfmfJavaUtilities.getELValue("#{applicationScope.chatreadlist}");

            AdfmfJavaUtilities.setELValue("#{applicationScope.chatreadlist}", null);


            if (_chatHistory.size() > 0) { //existing chat
                chatInit = 1;


                for (ChatBot cb : _chatHistory) {
                    try {

                        if (cbot.getReceiverUsername().equalsIgnoreCase(cb.getReceiverUsername())) {
                            _chatHistorySize.add(cb);

                        }

                    } catch (NullPointerException npe) {

                        continue;
                    }

                }


                AdfmfJavaUtilities.setELValue("#{applicationScope.chatreadlist}", _chatHistorySize);


            }
        } catch (NullPointerException npe) {


        }

        return "ChatBotFC";
    }


    @Override
    public void run() {
        try {
            Thread.sleep(2000);
            ChatBotSend();
        } catch (InterruptedException e) {
        }

    }

    //setters and getters


    public void setChatdate(String chatdate) {
        this.chatdate = chatdate;
    }

    public String getChatdate() {
        return chatdate;
    }

    public void setChatsendtext(String chatsendtext) {
        String oldChatsendtext = this.chatsendtext;
        this.chatsendtext = chatsendtext;
        _propertyChangeSupport.firePropertyChange("chatsendtext", oldChatsendtext, chatsendtext);
    }

    public String getChatsendtext() {
        return chatsendtext;
    }


    public void setCbot(ChatBot cbot) {
        ChatBot oldCbot = this.cbot;
        this.cbot = cbot;
        _propertyChangeSupport.firePropertyChange("cbot", oldCbot, cbot);
    }

    public ChatBot getCbot() {
        return cbot;
    }

    public void setChatServList(List chatServList) {
        List oldChatServList = this.chatServList;
        this.chatServList = chatServList;
        _propertyChangeSupport.firePropertyChange("chatServList", oldChatServList, chatServList);
    }

    public List getChatServList() {
        return chatServList;
    }

    public void addPropertyChangeListener(PropertyChangeListener l) {
        _propertyChangeSupport.addPropertyChangeListener(l);
    }

    public void removePropertyChangeListener(PropertyChangeListener l) {
        _propertyChangeSupport.removePropertyChangeListener(l);
    }
}


2. Invoke REST Service

      public static String invokeRestService(String requestType, String requestURI, Object postData) {
      
        RestServiceAdapterFactory factory = RestServiceAdapterFactory.newFactory();
        RestServiceAdapter rs = factory.createRestServiceAdapter();
        rs.clearRequestProperties();
        rs.setConnectionName("MolaRESTService");
        rs.addRequestProperty("Content-Type", "application/json");
        rs.addRequestProperty("Accept", "application/json;charset=UTF-8");
        rs.setRequestMethod(requestType);
        rs.setRequestURI(requestURI);
        rs.setRetryLimit(0);
        rs.addRequestProperty("Authorization", "Basic "+HelperClass.TomcatAuthorization());
        
      String response = "";
      String postDataStr = "";

      try {
        if (postData != null) {
          JSONObject jsonObj = (JSONObject) JSONBeanSerializationHelper.toJSON(postData);
        postDataStr = jsonObj.toString();
        }

        response = rs.send(postDataStr);

      } catch (AdfInvocationException ex) {
        if (AdfInvocationException.CATEGORY_WEBSERVICE.compareTo(ex.getErrorCategory()) == 0) {
          throw new RuntimeException("Error with the server. Please try later.");
        }
      } catch (Exception e) {
       // throw new AdfException(e.getLocalizedMessage(), AdfException.ERROR);
        e.printStackTrace();
      }

      return response;
    }


3. Message is received from the server and received on the app through the onMessage

    public void onMessage(Event event) {
        String servermsg = event.getPayload();
        

        HashMap payload = null;
        String pushMsg = "No message received";
        String pushDeviceType="os";
        String senderId ="damilola";
        String senderTk ="xx";
        String receiverTk ="nn";
        try
        {
          payload = (HashMap)JSONBeanSerializationHelper.fromJSON(HashMap.class, msg);
          pushMsg = (String)payload.get("alert");
          pushDeviceType = (String)payload.get("deviceToken");
          senderId = (String)payload.get("senderId");
          senderTk = (String)payload.get("senderTk");
          receiverTk = (String)payload.get("receiverTk");
         
            // Write the push message to app scope to display to the user        
            AdfmfJavaUtilities.setELValue("#{applicationScope.pushMessage}", pushMsg);
            AdfmfJavaUtilities.setELValue("#{applicationScope.pushDeviceType}", pushDeviceType);
            AdfmfJavaUtilities.setELValue("#{applicationScope.senderId}", senderId);
            AdfmfJavaUtilities.setELValue("#{applicationScope.senderTk}", senderTk);
            AdfmfJavaUtilities.setELValue("#{applicationScope.receiverTk}", receiverTk);
            
            
        }
        catch(Exception e) {
            e.printStackTrace();
        }
       
    }



4. ChatBot Entity

public class ChatBot {
    private String deviceToken;
    private String messagetext;
    private Date messagedate;
    private String deviceid = DeviceManagerFactory.getDeviceManager().getOs().toLowerCase();
    private String username;
    private String lastname;
    private String firstname;
    private String messagestatus;
    private String senderToken;
    private String receiverToken;
    private String receiverSurname;
    private String receiverFirstname;
    private String receiverUsername;
    private String jobId;
    private String stateId;
    private String chatDateTime;
    private PropertyChangeSupport _propertyChangeSupport = new PropertyChangeSupport(this);
 
    public ChatBot() {
        super();
    }
    
    public ChatBot(String messagetext) {
        this.messagetext = messagetext;
    }
    public ChatBot(String messagetext,String messagestatus,String chatDateTime,String username,String receiverUsername) {
        this.messagetext = messagetext;
        this.messagestatus = messagestatus;
        this.chatDateTime =chatDateTime;
        this.username = username;
        this.receiverUsername = receiverUsername;
    }

    public void setDeviceToken(String deviceToken) {
        this.deviceToken = deviceToken;
    }

    public String getDeviceToken() {
        return deviceToken;
    }

    public void setMessagetext(String messagetext) {
        this.messagetext = messagetext;
    }

    public String getMessagetext() {
        return messagetext;
    }

    public void setMessagedate(Date messagedate) {
        this.messagedate = messagedate;
    }

    public Date getMessagedate() {
        return messagedate;
    }

    public void setDeviceid(String deviceid) {
        this.deviceid = deviceid;
    }

    public String getDeviceid() {
        return deviceid;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getUsername() {
        return username;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getFirstname() {
        return firstname;
    }


    


    public void setSenderToken(String senderToken) {
        this.senderToken = senderToken;
    }

    public String getSenderToken() {
        return senderToken;
    }

    public void setReceiverSurname(String receiverSurname) {
        this.receiverSurname = receiverSurname;
    }

    public String getReceiverSurname() {
        return receiverSurname;
    }

    public void setReceiverFirstname(String receiverFirstname) {
        this.receiverFirstname = receiverFirstname;
    }

    public String getReceiverFirstname() {
        return receiverFirstname;
    }

    public void setJobId(String jobId) {
        this.jobId = jobId;
    }

    public String getJobId() {
        return jobId;
    }

    public void setStateId(String stateId) {
        this.stateId = stateId;
    }

    public String getStateId() {
        return stateId;
    }

    public void setChatDateTime(String chatDateTime) {
        this.chatDateTime = chatDateTime;
    }

    public String getChatDateTime() {
        return chatDateTime;
    }


    public void setReceiverToken(String receiverToken) {
        this.receiverToken = receiverToken;
    }

    public String getReceiverToken() {
        return receiverToken;
    }

    public void setReceiverUsername(String receiverUsername) {
        this.receiverUsername = receiverUsername;
    }

    public String getReceiverUsername() {
        return receiverUsername;
    }

    public void setMessagestatus(String messagestatus) {
        String oldMessagestatus = this.messagestatus;
        this.messagestatus = messagestatus;
        _propertyChangeSupport.firePropertyChange("messagestatus", oldMessagestatus, messagestatus);
    }

    public String getMessagestatus() {
        return messagestatus;
    }

    public void addPropertyChangeListener(PropertyChangeListener l) {
        _propertyChangeSupport.addPropertyChangeListener(l);
    }

    public void removePropertyChangeListener(PropertyChangeListener l) {
        _propertyChangeSupport.removePropertyChangeListener(l);
    }
}


5. UI using MAF full javascript/CSS compatible
 
<?xml version="1.0" encoding="UTF-8" ?>
<amx:view xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:amx="http://xmlns.oracle.com/adf/mf/amx"
          xmlns:dvtm="http://xmlns.oracle.com/adf/mf/amx/dvt">
    <amx:systemActionBehavior type="back" id="sab1" action="#{HealthProgramsBean.goDashboard}"/>
    <amx:panelPage id="pp1">
        <amx:facet name="header">
            <amx:outputText value="#{ChatBotBean.cbot.receiverSurname} #{ChatBotBean.cbot.receiverFirstname} - #{ChatBotBean.cbot.stateId}"
                            id="ot1"/>
        </amx:facet>
        <amx:facet name="primary">
            <amx:commandButton id="cb1" action="__back" text="Back"/>
        </amx:facet>
        <amx:facet name="secondary">
            <amx:commandButton id="cb2"/>
        </amx:facet>
        <amx:facet name="footer">
            <amx:panelGroupLayout layout="horizontal" halign="center" inlineStyle="width: 100%">
                <amx:inputText id="it1" value="#{ChatBotBean.chatsendtext}" hintText="Write a message"
                               inlineStyle="word-wrap:break-word;" rows="2"/>
                <amx:commandButton text="Send" action="#{ChatBotBean.ChatSend()}"
                                   styleClass="adfmf-commandButton-small"></amx:commandButton>
            </amx:panelGroupLayout>
        </amx:facet>
        <amx:panelStretchLayout id="psl1" >
            <amx:facet name="top"/>
            <amx:facet name="center">
                <amx:panelStretchLayout id="Tab1" xmlns:amx="http://xmlns.oracle.com/adf/mf/amx">
                    <amx:facet name="center">
                        
                    </amx:facet>
                </amx:panelStretchLayout>
            </amx:facet>
            <amx:facet name="bottom">
                <amx:panelStretchLayout id="psl2" xmlns:amx="http://xmlns.oracle.com/adf/mf/amx" scrollPolicy="scroll"
                                        inlineStyle="overflow:auto;display:flex;flex-direction: column-reverse">
                    <amx:facet name="bottom">
                        <amx:iterator id="i1" value="#{applicationScope.chatreadlist}" var="row">
                            <amx:tableLayout id="tl1" width="100%">
                                <amx:rowLayout id="rl1">
                                    <amx:cellFormat id="cf1"
                                                    rendered="#{row.messagestatus != 'sent'}"
                                                    width="20%">
                                        <amx:outputText id="ot2"
                                                        value="#{applicationScope.badge eq null ? 'DA' : applicationScope.badge}"
                                                        inlineStyle="background-color:grey"
                                                        styleClass="profileNameAvatar"/>
                                    </amx:cellFormat>
                                    <amx:cellFormat id="cf2"  halign="start" width="70%">
                                        
                                            <amx:panelGroupLayout layout="horizontal" valign="bottom" rendered="#{row.messagetext != null}"
                                                    styleClass="#{row.messagestatus == 'sent' ? 'right' : 'left'}" >
                                                <amx:outputText value="#{row.messagetext}" id="ot3" inlineStyle="width:50%;color:#{row.messagestatus == 'sent' ? 'white' : 'black'}"/>
                                                <amx:spacer width="4"/>
                                                <amx:outputText value="#{row.chatDateTime}" 
                                                                inlineStyle="width:20%;font-size:10px;font-style:italic;position:relative"/>
                                                                
                                            <amx:panelGroupLayout halign="end" valign="bottom">
                                                <amx:image rendered="#{row.messagestatus == 'sent'}"
                                                           source="/images/sent.png" inlineStyle="width:15px;height:15px;position:right"/>
                                                <amx:image rendered="#{row.messagestatus == 'delivered'}"
                                                           source="/images/delivered.png"
                                                           inlineStyle="width:15px;height:15px;position:right"/>
                                                <amx:image rendered="#{row.messagestatus == 'read'}"
                                                           source="/images/read.png" inlineStyle="width:15px;height:15px;position:right"/>
                                            </amx:panelGroupLayout>
                                            
                                            </amx:panelGroupLayout>
                                            
                                            
                                        
                                    </amx:cellFormat>
                                </amx:rowLayout>
                            </amx:tableLayout>
                        </amx:iterator>
                    </amx:facet>
                </amx:panelStretchLayout>
            </amx:facet>
        </amx:panelStretchLayout>
    </amx:panelPage>
</amx:view>




6. CSS bubbles for the chat
 
@charset "UTF-8";
/*Start of chat bubble css*/
.right {
  position: relative;
  padding: 10px 20px;
  color: white;
  background: #0B93F6;
  border-radius: 10px;
  float: right;
  max-width: 80%;
    word-wrap: break-word;
    margin-bottom: 20px;
    line-height: 24px;
}
  .right::before {
    content: "";
    position: absolute;
    z-index: -1;
    bottom: -2px;
    right: -7px;
    height: 20px;
    border-right: 20px solid #0B93F6;
    border-bottom-left-radius: 16px 14px;
    -webkit-transform: translate(0, -2px);
  }
  .right::after {
    content: "";
    position: absolute;
    z-index: 1;
    bottom: -2px;
    right: -56px;
    width: 26px;
    height: 20px;
    background: white;
    border-bottom-left-radius: 10px;
    -webkit-transform: translate(-30px, -2px);
  }


.left {
  position: relative;
  padding: 10px 20px;
  background: #E5E5EA;
  border-radius: 10px;
  color: black;
  float: left;
  max-width: 80%;
    word-wrap: break-word;
    margin-bottom: 20px;
    line-height: 24px;
}
  .left::before {
    content: "";
    position: absolute;
    z-index: 2;
    bottom: -2px;
    left: -7px;
    height: 20px;
    border-left: 20px solid #E5E5EA;
    border-bottom-right-radius: 16px 14px;
    -webkit-transform: translate(0, -2px);
  }
  .left::after {
    content: "";
    position: absolute;
    z-index: 3;
    bottom: -2px;
    left: 4px;
    width: 26px;
    height: 20px;
    background: white;
    border-bottom-right-radius: 10px;
    -webkit-transform: translate(-30px, -2px);
  }


@keyframes loud {
  20% {
    transform: rotate3d(0, 0, 1, 5deg) scale3d(1.5, 1.5, 1.5);
  }
  25% {
    transform: rotate3d(0, 0, 1, -5deg) scale3d(1.5, 1.5, 1.5);
  }
  30% {
    transform: rotate3d(0, 0, 1, 5deg) scale3d(1.5, 1.5, 1.5);
  }
  35% {
    transform: rotate3d(0, 0, 1, -5deg) scale3d(1.5, 1.5, 1.5);
  }
  40% {
    transform: rotate3d(0, 0, 1, 5deg) scale3d(1.5, 1.5, 1.5);
  }
  45% {
    transform: rotate3d(0, 0, 1, -5deg) scale3d(1.5, 1.5, 1.5);
  }
  50% {
    transform: rotate3d(0, 0, 1, 5deg) scale3d(1.5, 1.5, 1.5);
  }
  60% {
    transform: rotate3d(0, 0, 1, 5deg) scale3d(1.5, 1.5, 1.5);
  }
  to {
    transform: rotate3d(0, 0, 1, 0deg);
  }
}

.loud {
  animation-duration: 1.5s;
  animation-fill-mode: both;
  animation-timing-function: ease-in-out;
  transform-origin: center center;
  animation-name: loud;
}

@keyframes slam {
  0% {
    transform: rotate3d(0, 0, 1, 5deg) scale3d(3, 3, 3) translate3d(-50px, -10px, 0);
    box-shadow: 0px 0px 0px 0px rgba(0, 0, 0, 0.2);
  }
  18% {
    transform: rotate3d(0, 0, 1, 0deg) scale3d(1, 1, 1) translate3d(0, 0, 0);
    box-shadow: 0px 0px 0px 0px rgba(0, 0, 0, 0.45);
  }
  40% {
    transform: rotate3d(0, 0, 1, 1deg) scale3d(1.1, 1.1, 1.1) translate3d(-1px, -1px, 0);
    box-shadow: 0px 0px 100px 2px rgba(0, 0, 0, 0.25);
  }
  55% {
    transform: rotate3d(0, 0, 1, 0deg) scale3d(1.0, 1.0, 1.0) translate3d(0px, 0px, 0);
  }
  to {
    transform: rotate3d(0, 0, 1, 0deg);
    box-shadow: 0px 0px 125px 5px rgba(0, 0, 0, 0);
  }
}

.slam {
  animation-duration: 1.5s;
  animation-fill-mode: both;
  animation-timing-function: cubic-bezier(.87, .58, .25, 1.29);
  transform-origin: center center;
  animation-name: slam;
}

@keyframes gentle {
  0%,
  50% {
    transform: scale3d(1.5, 1.5, 1.5);
  }
  to {
    transform: rotate3d(0, 0, 1, 0deg);
  }
}

@keyframes gentle-text {
  0%,
  50% {
    transform: scale3d(0.5, 0.5, 0.5);
  }
  to {
    transform: rotate3d(0, 0, 1, 0deg);
  }
}

.gentle {
  animation-duration: 4s;
  animation-fill-mode: both;
  animation-timing-function: ease-out;
  transform-origin: bottom right;
  animation-name: gentle;
}
  p {
    animation-duration: 4s;
    animation-fill-mode: both;
    animation-timing-function: ease-out;
    transform-origin: center center;
    animation-name: gentle-text;
  }
/*End of chat bubble css*/




ServerSide Implementation to receive and forward messages as notifications

7a. Create a PushNotification Server using Jersey JSON Rest Implementation.
    You can deploy this on any of the container mentioned above
 
       @PUT
    @Path("cbot/")
    // @Produces(MediaType.APPLICATION_JSON)
    // @Consumes(MediaType.APPLICATION_JSON)
    public Response ChatBot(ChatBot cb) {
        if(WSPackages.ws_chatbotrelay(cb)) {
             return Response.ok(200)
                           .entity("Success")
                           .build();
      
        }
        else{
            return Response.status(401)
                           .entity("You cant go further..")
                           .build();
        }

    }
    


7b. Method ws_chatbotrelay
 
          protected static final Boolean ws_chatbotrelay(ChatBot chatbot) {
        try {
            final MessagingController mctrl = new MessagingController();

            mctrl.pushChatBotMessage(chatbot);
//You may persist the conversation in the database here
            return true;


        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;

    }


7c. Method pushChatBotMessage
 
             public final void pushChatBotMessage(ChatBot chatbot) {
        try {
            if (chatbot.getDeviceid().equals("android")) {
               pushChatBotAndroid(chatbot);
            } else if("ios".equals(chatbot.getDeviceid())) {
               pushMessageIOS();
            }
        } catch (Exception e) {
            e.printStackTrace();
            FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_WARN, e.getMessage(), "");
            FacesContext fctx = FacesContext.getCurrentInstance();
            fctx.addMessage(null, fm);
        }
    }
    
    private void pushMessageAndroid(Messaging messaging) throws Exception {
        Sender sender = new Sender(HelperClass.GOOGLE_APIKEY);
        Message message = new Message.Builder()
            .addData("alert", messaging.getMessage())
            .addData("deviceType", "android")
            .addData("deviceTk", messaging.getDeviceToken())
            .addData("sound", "default")
            .addData("featureid", "Login")
            .addData("badge", "1").build();
        System.out.println("Got regId as "+messaging.getDeviceToken() +" and message as "+messaging.getMessage());
        String regId = messaging.getDeviceToken();
        try {
            Result res = sender.send(message, regId, 5);
            String id = res.getMessageId();
            String cregId = res.getCanonicalRegistrationId();
            String errorCode = res.getErrorCodeName();
            String retMsg = "Message pushed : Id : " + id + "; CRegId: " + cregId + "; ErrorCode : " + errorCode;
            System.out.println(retMsg);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    }


7d.
 
package com.centrifugegroup.molaappws.entity;

import java.util.Date;

public class ChatBot {
    private String deviceToken;
    private String messagetext;
    private Date messagedate;
    private String deviceid;
    private String username;
    private String lastname;
    private String firstname;
    private String senderToken;
    private String receiverToken;
    
    public ChatBot() {
        super();
    }


    public void setDeviceToken(String deviceToken) {
        this.deviceToken = deviceToken;
    }

    public String getDeviceToken() {
        return deviceToken;
    }

    public void setMessagetext(String messagetext) {
        this.messagetext = messagetext;
    }

    public String getMessagetext() {
        return messagetext;
    }

    public void setMessagedate(Date messagedate) {
        this.messagedate = messagedate;
    }

    public Date getMessagedate() {
        return messagedate;
    }

    public void setDeviceid(String deviceid) {
        this.deviceid = deviceid;
    }

    public String getDeviceid() {
        return deviceid;
    }


    public void setUsername(String username) {
        this.username = username;
    }

    public String getUsername() {
        return username;
    }


    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setSenderToken(String senderToken) {
        this.senderToken = senderToken;
    }

    public String getSenderToken() {
        return senderToken;
    }


    public void setReceiverToken(String receiverToken) {
        this.receiverToken = receiverToken;
    }

    public String getReceiverToken() {
        return receiverToken;
    }
}



A hybrid Android and IOS Mobile Chat app

Project :   Development of a simple extensible chat  Technologies and Frameworks Oracle Mobile Application Framework (MAF) Oracle Java ...