Establish xmpp connection listener using spring integration

Viewed 252

i want to establish xmpp connection between android and app server in spring boot. android send message to app server, then app server bring some data from firebase realtime database depending on the message received from android, finally, app server send back response to android. the problem is that xmpp connection established but listener does not work. any help please?`

@Configuration
public class XmppConfig  implements org.jivesoftware.smack.ConnectionListener {

    @Value("${fcm.sender_id}")
    private String senderId;
    @Value("${fcm.server_key}")
    private String server_key;
    @Value("${fcm.host}")
    private String host;
    @Value("${fcm.port}")
    private int port;

     /*   @Autowired
    private XmppService xmppService;*/

    private Logger logger = LoggerFactory.getLogger(XmppConfig.class);
    private volatile boolean xmppConnected;
    private XMPPTCPConnection xmppConnection;

    public XMPPTCPConnection getXmppConnection() {
        return xmppConnection;
    }

     /*   @PostConstruct
    public void postConstruct() throws Exception {
        new Thread(() -> prepareXmppConnection()).start();
    }*/

     @Bean
    public XMPPConnection prepareXmppConnection() {

        logger.info("preparing TO FCM XMPP");
        XMPPTCPConnectionConfiguration conf = null;
        try {
            conf = XMPPTCPConnectionConfiguration.builder()
                    .setHost(host)
                    .setPort(port)
                    .setSendPresence(false)
                    .setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
                    .setSocketFactory(SSLSocketFactory.getDefault())
                    .setUsernameAndPassword(senderId, server_key)
                    .setXmppDomain(host)
                    .enableDefaultDebugger()
                    .build();
        } catch (XmppStringprepException e) {
            logger.info("prepareXmppConnection error", e);
        }
        xmppConnection = new XMPPTCPConnection(conf);

        establishXmppConnection();

        xmppConnection.addConnectionListener(this);

        xmppConnection.addAsyncStanzaListener(xmppService, xmppService);

        Roster.getInstanceFor(xmppConnection).setRosterLoadedAtLogin(false);
        logger.info("finish preparing TO FCM XMPP");

        return xmppConnection;
    }

    private void establishXmppConnection() {
        try {
            logger.info("establish XMPP connection ");
            xmppConnection.connect();
            xmppConnection.login();
        } catch (Exception e) {
            logger.info("XMPP establishXmppConnection error", e);
        }
    }


    @Override
    public void connected(XMPPConnection connection) {
          logger.info("CONNECTED TO FCM XMPP");

    }

    @Override
    public void authenticated(XMPPConnection connection, boolean resumed) {
        logger.info("AUTHENTICATED TO FCM XMPP");

    }

    @Override
    public void connectionClosed() {
         logger.info("LOST CONNECTION TO FCM XMPP");
         // Utils.sleep(5000);
         establishXmppConnection();

    }

    @Override
    public void connectionClosedOnError(Exception e) {
        logger.info("LOST CONNECTION TO FCM XMPP ON ERROR", e);
        //Utils.sleep(5000);
        establishXmppConnection();

    }



     @Value("https://fcmapplication-9181f.firebaseio.com")
        private String databaseUrl;

    @Bean   
    public DatabaseReference firebaseDatabse() throws IOException {

        InputStream inputStream = this.getClass()
                                      .getClassLoader()
                                      .getResourceAsStream("fcmapplication-9181f-firebase-adminsdk-mbpkv- 
      b742eac500.json");


        FirebaseOptions options = new FirebaseOptions.Builder()
                                                    // .setServiceAccount(inputStream)

    .setCredentials(GoogleCredentials.fromStream(inputStream))
                                                     .setDatabaseUrl(databaseUrl)
                                                     .build();

      // FirebaseApp.initializeApp(options); 

      if (FirebaseApp.getApps().isEmpty()) {

           FirebaseApp.initializeApp(options); 
      }
      else {
        FirebaseDatabase.getInstance().setPersistenceEnabled(false);
      }

      DatabaseReference firebase = FirebaseDatabase.getInstance().getReference("eye_case");

        System.out.println("firebase ");

        return firebase;

    }
    }

     @Service
      public class XmppService implements StanzaListener , StanzaFilter {

     private Logger logger = LoggerFactory.getLogger(XmppService.class);

     @Autowired
     private XmppConfig xmppConfig;


    @Override
    public void processStanza(Stanza packet) throws NotConnectedException, InterruptedException, NotLoggedInException {

        JSONObject stanza;

        try {

            stanza = XML.toJSONObject(packet.toXML(null).toString());
            if (!stanza.has("message")) return;
            JSONObject message = stanza.getJSONObject("message");

            if (message.has("type")) {
                normalMessage(message);
            } else {
                otherMessage(message);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

     private void normalMessage(JSONObject message)  {
            JSONObject gcm;
            JSONObject content=null;
            String message_id="";
            String from="";
            try {
                gcm = message.getJSONObject("gcm");
                String contentString = gcm.getString("content");
                content = new JSONObject(contentString);
                message_id = content.getString("message_id");
                from = content.getString("from");

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

            if (content.has("message_type")) {
                logger.info("NOT FROM DEVICE:\n" + message.toString());
            } else {
                processMessage(content);
                sendAck(message_id, from);
            }
        }

     private void processMessage(JSONObject content) {

         try {
            String action=content.getString("action");
            if (action == "REGISTER")  {
                logger.info("Register Message");
            }
            else if (action == "ECHO") {
                logger.info("Echo Message");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

     }


        private void sendAck(String message_id, String regId) {
            try {
                JSONObject json = new JSONObject();
                json.put("to", regId);
                json.put("message_id", message_id);
                json.put("message_type", "ack");
                String messageString = String.format("<message><gcm xmlns=\"google:mobile:data\">%s</gcm></message>", json.toString());
                Stanza stanza = PacketParserUtils.parseStanza(messageString);
               // xmppConfig.xmppConnectionFactoryBean().getObject().sendStanza(stanza);
              //  xmppConfig.getXmppConnection().sendStanza(generateStanza(message_id,json));
            } catch (Exception e) {
                logger.info("fcm sending ack error", e);
            }
        }

        private void otherMessage(JSONObject message) {
            JSONObject gcm;

            try {
                gcm = message.getJSONObject("gcm");
                String contentString = gcm.getString("content");
                 JSONObject content = new JSONObject(contentString);
                if (content.getString("message_type").equals("ack")) {
                    logger.info("RECEIVED ACK");
                } else if (content.getString("message_type").equals("nack")) {
                    logger.info("RECEIVED NACK: \n" + content.toString(2));
                } else {
                    logger.info("RECEIVED UNKNOWN: \n" + content.toString());
                }
            } catch (JSONException e) {
                e.printStackTrace();
            } 
        }

        private Stanza generateStanza(String messageId, JSONObject json) {
            String messageString = String.format("<message id=\"%s\"><gcm xmlns=\"google:mobile:data\">%s</gcm></message>", messageId, json.toString());
            try {
                return PacketParserUtils.parseStanza(messageString);
            } catch (Exception e) {
                logger.info("generateStanza error", e);
                return null;
            }
        }

        @Override
        public boolean accept(Stanza stanza) {

            return true;
        }
       }

:: Spring Boot ::        (v2.2.6.RELEASE)

2020-05-13 13:20:50.733  INFO 3700 --- [           main] c.p.t.phdProject.PhdProjectApplication   : 
Starting PhdProjectApplication on DESKTOP-HAHBAOS with PID 3700 
 (D:\MarsWorkSpace\phdProject\target\classes started by lenovo in D:\MarsWorkSpace\phdProject)
 2020-05-13 13:20:50.736  INFO 3700 --- [           main] c.p.t.phdProject.PhdProjectApplication   : 
 No active profile set, falling back to default profiles: default
 2020-05-13 13:20:51.260  INFO 3700 --- [           main] faultConfiguringBeanFactoryPostProcessor : 
  No 
  bean named 'errorChannel' has been explicitly defined. Therefore, a default PublishSubscribeChannel 
  will be created.
  2020-05-13 13:20:51.268  INFO 3700 --- [           main] faultConfiguringBeanFactoryPostProcessor : 
  No bean named 'taskScheduler' has been explicitly defined. Therefore, a default 
  ThreadPoolTaskScheduler will be created.
  2020-05-13 13:20:51.271  INFO 3700 --- [           main] faultConfiguringBeanFactoryPostProcessor : 
 No bean named 'integrationHeaderChannelRegistry' has been explicitly defined. Therefore, a default 
 DefaultHeaderChannelRegistry will be created.
 2020-05-13 13:20:51.305  INFO 3700 --- [           main] trationDelegate$BeanPostProcessorChecker : 
 Bean 'org.springframework.integration.config.IntegrationManagementConfiguration' of type 
 [org.springframework.integration.config.IntegrationManagementConfiguration] is not eligible for 
 getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
 2020-05-13 13:20:51.316  INFO 3700 --- [           main] trationDelegate$BeanPostProcessorChecker : 
 Bean 'integrationChannelResolver' of type 
 [org.springframework.integration.support.channel.BeanFactoryChannelResolver] is not eligible for 
 getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
 2020-05-13 13:20:51.318  INFO 3700 --- [           main] trationDelegate$BeanPostProcessorChecker : 
 Bean 'integrationDisposableAutoCreatedBeans' of type 
 [org.springframework.integration.config.annotation.Disposables] is not eligible for getting 
 processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
 2020-05-13 13:20:51.381  INFO 3700 --- [           main] c.p.t.phdProject.Config.XmppConfig       : 
 preparing TO FCM XMPP
 2020-05-13 13:20:51.725  INFO 3700 --- [           main] c.p.t.phdProject.Config.XmppConfig       : 
 establish XMPP connection 
 13:20:52 SENT (0): <stream:stream xmlns='jabber:client' to='fcm-xmpp.googleapis.com' 
 xmlns:stream='http://etherx.jabber.org/streams' version='1.0' 
 from='225392295170@gcm.googleapis.com@fcm-xmpp.googleapis.com' xml:lang='en'>
 13:20:52 RECV (0): <stream:stream from="fcm-xmpp.googleapis.com" id="1682A44DC61D4116" version="1.0" 
 xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client">
 13:20:52 RECV (0): <stream:features><mechanisms xmlns="urn:ietf:params:xml:ns:xmpp-sasl"> 
 <mechanism>X-OAUTH2</mechanism><mechanism>X-GOOGLE-TOKEN</mechanism><mechanism>PLAIN</mechanism> 
 </mechanisms> 
 </stream:features>
 13:20:52 SENT (0): <auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>
 ADIyNTM5MjI5NTE3MEBnY20uZ29vZ2xlYXBpcy5jb20AQUl6YVN5QzBuTjdvX0NaWnZFdkRtUkMzVGJHem5ZUVd 
 zTEFmSVNN</auth>
 13:20:53 RECV (0): <success xmlns="urn:ietf:params:xml:ns:xmpp-sasl"/>
 13:20:53 SENT (0): <stream:stream xmlns='jabber:client' to='fcm-xmpp.googleapis.com' 
 xmlns:stream='http://etherx.jabber.org/streams' version='1.0' 
 from='225392295170@gcm.googleapis.com@fcm-xmpp.googleapis.com' id='1682A44DC61D4116' xml:lang='en'>
 13:20:53 RECV (0): <stream:stream from="fcm-xmpp.googleapis.com" id="7467168502A88D0E" version="1.0" 
 xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client">
 13:20:53 RECV (0): <stream:features><bind xmlns="urn:ietf:params:xml:ns:xmpp-bind"/><session 
 xmlns="urn:ietf:params:xml:ns:xmpp-session"/></stream:features>
 13:20:53 SENT (0): <iq id='o2A3D-3' type='set'><bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'> 
 </bind> 
 </iq>
 13:20:53 RECV (0): <iq id="o2A3D-3" type="result"><bind xmlns="urn:ietf:params:xml:ns:xmpp-bind"> 
 <jid>225392295170@gcm.googleapis.com/79295C1E</jid></bind></iq>
 13:20:53 SENT (0): <iq id='o2A3D-5' type='set'><session xmlns='urn:ietf:params:xml:ns:xmpp- 
 session'/> 
 </iq>
 13:20:53 RECV (0):  
 13:20:53 RECV (0): <iq type="result" id="o2A3D-5"/>
 13:20:53 User logged (0): 225392295170@gcm.googleapis.com:5235/79295C1E
 13:20:53 SENT (0): <iq id='o2A3D-7' type='get'><query xmlns='jabber:iq:roster'></query></iq>
 13:20:53 XMPPConnection authenticated (XMPPTCPConnection[225392295170@gcm.googleapis.com/79295C1E] 
 (0))
 2020-05-13 13:20:53.720  INFO 3700 --- [           main] c.p.t.phdProject.Config.XmppConfig       : 
 finish preparing TO FCM XMPP
 firebase 
 2020-05-13 13:20:54.159  INFO 3700 --- [           main] o.s.s.c.ThreadPoolTaskScheduler          : 
 Initializing ExecutorService 'taskScheduler'
 2020-05-13 13:20:54.203  INFO 3700 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : 
 Adding {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 
 'errorChannel' channel
  2020-05-13 13:20:54.204  INFO 3700 --- [           main] o.s.i.channel.PublishSubscribeChannel    : 
  Channel 'application.errorChannel' has 1 subscriber(s).
  2020-05-13 13:20:54.204  INFO 3700 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : 
  started bean '_org.springframework.integration.errorLogger'
  2020-05-13 13:20:54.211  INFO 3700 --- [           main] c.p.t.phdProject.PhdProjectApplication   : 
  Started PhdProjectApplication in 3.813 seconds (JVM running for 4.452)
  2020-05-13 13:20:54.215  INFO 3700 --- [extShutdownHook] o.s.i.endpoint.EventDrivenConsumer       : 
  Removing {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to 
  the 'errorChannel' channel
  2020-05-13 13:20:54.215  INFO 3700 --- [extShutdownHook] o.s.i.channel.PublishSubscribeChannel    : 
 Channel 'application.errorChannel' has 0 subscriber(s).
 2020-05-13 13:20:54.216  INFO 3700 --- [extShutdownHook] o.s.i.endpoint.EventDrivenConsumer       : 
 stopped bean '_org.springframework.integration.errorLogger'
 2020-05-13 13:20:54.216  INFO 3700 --- [extShutdownHook] o.s.s.c.ThreadPoolTaskScheduler          : 
 Shutting down ExecutorService 'taskScheduler'

 '
0 Answers
Related