Package org.jivesoftware.smack

Examples of org.jivesoftware.smack.XMPPConnection


            ConnectionConfiguration("localhost", 61222);
        // config.setDebuggerEnabled(true);

        try {
            // SmackConfiguration.setPacketReplyTimeout(1000);
            XMPPConnection con = new XMPPConnection(config);
            con.connect();
            con.login("amq-user", "amq-pwd");
            ChatManager chatManager = con.getChatManager();
            Chat chat = chatManager.createChat("test@localhost", new MessageListener() {
                public void processMessage(Chat chat, Message message) {
                    System.out.println("Got XMPP message from chat " + chat.getParticipant() + " message - " + message.getBody());
                }
            });
            for (int i = 0; i < 10; i++) {
                System.out.println("Sending message: " + i);
                chat.sendMessage("Hello from Message: " + i);
            }
            System.out.println("Sent all messages!");
            con.disconnect();
        } catch (XMPPException e) {
            if (block) {
                System.out.println("Caught: " + e);
                e.printStackTrace();
            } else {
View Full Code Here


    public void testChat() throws Exception {
        ConnectionConfiguration config = new ConnectionConfiguration("localhost", 61222);
        //config.setDebuggerEnabled(true);

        XMPPConnection consumerCon = new XMPPConnection(config);
        consumerCon.connect();
        consumerCon.login("consumer", "consumer");
        consumerCon.addPacketListener(new XmppLogger("CONSUMER INBOUND"), new PacketFilter() {
            public boolean accept(Packet packet) {
                return true;
            }
        });
        consumerCon.addPacketWriterListener(new XmppLogger("CONSUMER OUTBOUND"), new PacketFilter() {
            public boolean accept(Packet packet) {
                return true;
            }
        });
        final ConsumerMessageListener listener = new ConsumerMessageListener();

        consumerCon.getChatManager().addChatListener(new ChatManagerListener() {
            public void chatCreated(Chat chat, boolean createdLocally) {
                chat.addMessageListener(listener);
            }
        });


        XMPPConnection producerCon = new XMPPConnection(config);
        producerCon.connect();
        producerCon.login("producer", "producer");
        producerCon.addPacketListener(new XmppLogger("PRODUCER INBOUND"), new PacketFilter() {
            public boolean accept(Packet packet) {
                return true;
            }
        });
        producerCon.addPacketWriterListener(new XmppLogger("PRODUCER OUTBOUND"), new PacketFilter() {
            public boolean accept(Packet packet) {
                return true;
            }
        });

        Chat chat = producerCon.getChatManager().createChat("consumer", new MessageListener() {
            public void processMessage(Chat chat, Message message) {
                System.out.println("Got XMPP message from chat " + chat.getParticipant() + " message - " + message.getBody());
            }
        });
View Full Code Here

    public void testMultiUserChat() throws Exception {
        System.out.println("\n\n\n\n\n\n");
        ConnectionConfiguration config = new ConnectionConfiguration("localhost", 61222);
        //config.setDebuggerEnabled(true);
        //
        XMPPConnection consumerCon = new XMPPConnection(config);
        consumerCon.connect();
        consumerCon.login("consumer", "consumer");
        MultiUserChat consumerMuc = new MultiUserChat(consumerCon, "muc-test");
        consumerMuc.join("consumer");

        ConsumerMUCMessageListener listener = new ConsumerMUCMessageListener();
        consumerMuc.addMessageListener(listener);

        XMPPConnection producerCon = new XMPPConnection(config);
        producerCon.connect();
        producerCon.login("producer", "producer");
        MultiUserChat producerMuc = new MultiUserChat(producerCon, "muc-test");
        producerMuc.join("producer");

        for (int i = 0; i < 10; i++) {
            System.out.println("Sending message: " + i);
View Full Code Here

        System.out.println("\n\n\n\n\n\n");
        ConnectionConfiguration config = new ConnectionConfiguration("localhost", 61222);
        //config.setDebuggerEnabled(true);

        //create the consumer first...
        XMPPConnection consumerCon = new XMPPConnection(config);
        consumerCon.connect();
        addLoggingListeners("CONSUMER", consumerCon);
        consumerCon.login("consumer", "consumer");

        final ConsumerMessageListener listener1 = new ConsumerMessageListener();
        consumerCon.getChatManager().addChatListener(new ChatManagerListener() {
            public void chatCreated(Chat chat, boolean createdLocally) {
                chat.addMessageListener(listener1);
            }
        });
       
        //now create the producer
        XMPPConnection producerCon = new XMPPConnection(config);
        System.out.println("Connecting producer and consumer");
        producerCon.connect();
        addLoggingListeners("PRODUCER", producerCon);
        producerCon.login("producer", "producer");

        //create the chat and send some messages
        Chat chat = producerCon.getChatManager().createChat("consumer", new MessageListener() {
            public void processMessage(Chat chat, Message message) {
                System.out.println("Got XMPP message from chat " + chat.getParticipant() + " message - " + message.getBody());
            }
        });
       
        for (int i = 0; i < 10; i++) {
            System.out.println("Sending message: " + i);
            Message message = new Message("consumer");
            message.setType(Message.Type.chat);
            message.setBody("Hello from producer, message # " + i);
            chat.sendMessage(message);
        }
      
        //make sure the consumer has time to receive all the messages...
        Thread.sleep(sleepTime);

        //create an identical 2nd consumer
        XMPPConnection lastguyCon = new XMPPConnection(config);
        lastguyCon.connect();
        addLoggingListeners("LASTGUY", consumerCon);
        lastguyCon.login("consumer", "consumer");
        final ConsumerMessageListener listener2 = new ConsumerMessageListener();
        lastguyCon.getChatManager().addChatListener(new ChatManagerListener() {
            public void chatCreated(Chat chat, boolean createdLocally) {
                chat.addMessageListener(listener2);
            }
        });
View Full Code Here

            return connection;
        }

        if (port > 0) {
            if (getServiceName() == null) {
                connection = new XMPPConnection(new ConnectionConfiguration(host, port));
            } else {
                connection = new XMPPConnection(new ConnectionConfiguration(host, port, serviceName));
            }
        } else {
            connection = new XMPPConnection(host);
        }

        connection.connect();

        connection.addPacketListener(new XmppLogger("INBOUND"), new PacketFilter() {
View Full Code Here

     * @param msgCtx the axis2 message context
     * @throws AxisFault on error
     */
    public void sendMessage(MessageContext msgCtx, String targetAddress,
        OutTransportInfo outTransportInfo) throws AxisFault {
    XMPPConnection xmppConnection = null;
    XMPPOutTransportInfo xmppOutTransportInfo = null;
   
    //if on client side,create connection to xmpp server
    if(!msgCtx.isServerSide()){
      connectUsingClientOptions(msgCtx);
    }
   
    Message message = new Message();
    Options options = msgCtx.getOptions();     
      String serviceName = XMPPUtils.getServiceName(targetAddress);     
     
    if (targetAddress != null) {
      xmppOutTransportInfo = new XMPPOutTransportInfo(targetAddress);
      xmppOutTransportInfo.setConnectionFactory(connectionFactory);
    } else if (msgCtx.getTo() != null &&
        !msgCtx.getTo().hasAnonymousAddress()) {
      //TODO
    } else if (msgCtx.isServerSide()) {
      xmppOutTransportInfo = (XMPPOutTransportInfo)
      msgCtx.getProperty(Constants.OUT_TRANSPORT_INFO);
    }
     
    xmppConnection = xmppOutTransportInfo.getConnectionFactory().getXmppConnection();   
   
    if(msgCtx.isServerSide()){
      message.setProperty(XMPPConstants.IS_SERVER_SIDE, new Boolean(false));
      message.setProperty(XMPPConstants.IN_REPLY_TO, xmppOutTransportInfo.getInReplyTo());
    }else{
      //message is going to be processed on server side
      message.setProperty(XMPPConstants.IS_SERVER_SIDE,new Boolean(true));
      //we are sending a soap envelope as a message
      message.setProperty(XMPPConstants.CONTAINS_SOAP_ENVELOPE, new Boolean(true));
      message.setProperty(XMPPConstants.SERVICE_NAME, serviceName);
      String action = options.getAction();
      if (action == null) {
        AxisOperation axisOperation = msgCtx.getAxisOperation();
        if (axisOperation != null) {
          action = axisOperation.getSoapAction();
        }
      }
      if (action != null) {
        message.setProperty(XMPPConstants.ACTION, action);
      }
    }   
      if(xmppConnection == null){
        handleException("Connection to XMPP Server is not established.");       
      }
   
    //initialize the chat manager using connection
    ChatManager chatManager = xmppConnection.getChatManager();
    Chat chat = chatManager.createChat(xmppOutTransportInfo.getDestinationAccount(), null);   
   
    try
    {
      boolean waitForResponse =
        msgCtx.getOperationContext() != null &&
        WSDL2Constants.MEP_URI_OUT_IN.equals(
            msgCtx.getOperationContext().getAxisOperation().getMessageExchangePattern());
     
      //int endOfXMLDeclaration = soapMessage.indexOf("?>");
      //String modifiedSOAPMessage = soapMessage.substring(endOfXMLDeclaration+2);

      OMElement msgElement;     
      String messageToBeSent = "";
     
      //TODO : need to read from a constant
      if("xmpp/text".equals(xmppOutTransportInfo.getContentType())){
        //if request is received from a chat client, whole soap envelope
        //should not be sent.
        OMElement soapBodyEle = msgCtx.getEnvelope().getBody();
        OMElement responseEle = soapBodyEle.getFirstElement();
        if(responseEle != null){
          msgElement = responseEle.getFirstElement();         
        }else{
          msgElement = responseEle;
        }
      }else{
        //if request received from a ws client whole soap envelope
        //must be sent.
        msgElement = msgCtx.getEnvelope();
     
      messageToBeSent = msgElement.toString();
      message.setBody(messageToBeSent);
     
     
      XMPPClientSidePacketListener xmppClientSidePacketListener = null;
      if(waitForResponse && !msgCtx.isServerSide()){
        PacketFilter filter = new PacketTypeFilter(message.getClass());       
        xmppClientSidePacketListener = new XMPPClientSidePacketListener(msgCtx);
        xmppConnection.addPacketListener(xmppClientSidePacketListener,filter);
      }     

      chat.sendMessage(message);
      log.debug("Sent message :"+message.toXML());

      //If this is on client side, wait for the response from server.
      //Is this the best way to do this?
      if(waitForResponse && !msgCtx.isServerSide()){
        //TODO : need to add a timeout
        while(! xmppClientSidePacketListener.isResponseReceived()){
          try {
            Thread.sleep(1000);
          } catch (InterruptedException e) {
            log.debug("Sleep interrupted",e);
          }   
        }
        xmppConnection.disconnect();
      }

    } catch (XMPPException e) {
      log.error("Error occurred while sending the message : "+message.toXML(),e);
      handleException("Error occurred while sending the message : "+message.toXML(),e);
    }finally{
      if(!msgCtx.isServerSide()){
        xmppConnection.disconnect();
      }
    }
    } 
View Full Code Here

    public boolean isSingleton() {
        return true;
    }

    public XMPPConnection createConnection() throws XMPPException {
        XMPPConnection connection;

        if (port > 0) {
            if (getServiceName() == null) {
                connection = new XMPPConnection(new ConnectionConfiguration(host, port));
            } else {
                connection = new XMPPConnection(new ConnectionConfiguration(host, port, getServiceName()));
            }
        } else {
            connection = new XMPPConnection(host);
        }

        connection.connect();

        if (login && !connection.isAuthenticated()) {
            if (user != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Logging in to XMPP as user: " + user + " on connection: " + getConnectionMessage(connection));
                }
                if (password == null) {
                    LOG.warn("No password configured for user: " + user + " on connection: " + getConnectionMessage(connection));
                }

                if (createAccount) {
                    AccountManager accountManager = new AccountManager(connection);
                    accountManager.createAccount(user, password);
                }
                if (resource != null) {
                    connection.login(user, password, resource);
                } else {
                    connection.login(user, password);
                }
            } else {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Logging in anonymously to XMPP on connection: "  + getConnectionMessage(connection));
                }
                connection.loginAnonymously();
            }

            // presence is not needed to be sent after login
        }
View Full Code Here

     * @param msgCtx
     * @param responseMsg
     * @throws AxisFault
     */
    private static void sendChatMessage(MessageContext msgCtx,String responseMsg) throws AxisFault {
        XMPPConnection xmppConnection = null;
        XMPPOutTransportInfo xmppOutTransportInfo = null;       
        Message message = new Message();
         
         xmppOutTransportInfo = (XMPPOutTransportInfo)msgCtx.getProperty(Constants.OUT_TRANSPORT_INFO);
         if(xmppOutTransportInfo != null){
           message.setProperty(XMPPConstants.IN_REPLY_TO, xmppOutTransportInfo.getInReplyTo());
             xmppConnection = xmppOutTransportInfo.getConnectionFactory().getXmppConnection();
               if(xmppConnection == null){
                 handleException("Connection to XMPP Server is not established.");       
               }            
         }else{
           handleException("Could not find message sender details.");
         }        
       
        //initialize the chat manager using connection
        ChatManager chatManager = xmppConnection.getChatManager();
        Chat chat = chatManager.createChat(xmppOutTransportInfo.getDestinationAccount(), null);       
        try{        
           message.setBody(responseMsg);   
          chat.sendMessage(message);
          log.debug("Sent message :"+message.toXML());
View Full Code Here

   * @throws XMPPException
   */
  public void connect(final XMPPServerCredentials serverCredentials) throws AxisFault {
    //XMPPConnection.DEBUG_ENABLED = true;   
    if(XMPPConstants.XMPP_SERVER_TYPE_JABBER.equals(serverCredentials.getServerType())){
      xmppConnection = new XMPPConnection(serverCredentials.getServerUrl());
      try {
        xmppConnection.connect();
      } catch (XMPPException e) {
        log.error("Failed to connect to server :"+serverCredentials.getServerUrl(), e);
        throw new AxisFault("Failed to connect to server :"+serverCredentials.getServerUrl());
      }
      //Pause for a small time before trying to login.
      //This prevents random ssl exception from Smack API
      try {
        Thread.sleep(100);
      } catch (InterruptedException e5) {
        log.debug("Sleep interrupted ",e5);
      }

      if(xmppConnection.isConnected()){
        if(! xmppConnection.isAuthenticated()){
          try {
            xmppConnection.login(serverCredentials.getAccountName()+"@"+
                serverCredentials.getServerUrl(),
                serverCredentials.getPassword(),
                serverCredentials.getResource(),
                true);
          } catch (XMPPException e) {
            try {
              log.error("Login failed for "
                  +serverCredentials.getAccountName()
                  +"@"+serverCredentials.getServerUrl()
                  +".Retrying in 2 secs",e);
              Thread.sleep(2000);
              xmppConnection.login(serverCredentials.getAccountName()+"@"+
                  serverCredentials.getServerUrl(),
                  serverCredentials.getPassword(),
                  serverCredentials.getResource(),
                  true);
            } catch (InterruptedException e1) {
              log.error("Sleep interrupted.",e1);
            } catch (XMPPException e2) {
              log.error("Login failed for : "+serverCredentials.getAccountName()
                  +"@"+serverCredentials.getServerUrl(),e2);
              throw new AxisFault("Login failed for : "+serverCredentials.getAccountName()
                  +"@"+serverCredentials.getServerUrl());
            }
          }
          //Listen for Message type packets from specified server url
          //packetFilter = new AndFilter(new PacketTypeFilter(Message.class),
          //    new FromContainsFilter(serverCredentials.getServerUrl()));
          packetFilter = new FromContainsFilter(serverCredentials.getServerUrl());         
        }
      }   
     
    }else if(XMPPConstants.XMPP_SERVER_TYPE_GOOGLETALK.equals(serverCredentials.getServerType())){
      ConnectionConfiguration connectionConfiguration =
        new ConnectionConfiguration(XMPPConstants.GOOGLETALK_URL
          ,XMPPConstants.GOOGLETALK_PORT
          ,XMPPConstants.GOOGLETALK_SERVICE_NAME);       
      xmppConnection = new XMPPConnection(connectionConfiguration);
      try {
        xmppConnection.connect();
        xmppConnection.login(serverCredentials.getAccountName()
            , serverCredentials.getPassword()
            ,serverCredentials.getResource(),
View Full Code Here

    }

    // Implementation methods
    // -------------------------------------------------------------------------
    protected XMPPConnection createConnection() throws XMPPException {
        XMPPConnection connection;
        if (port > 0) {
            connection = new XMPPConnection(host, port);
        } else {
            connection = new XMPPConnection(host);
        }
        if (login && !connection.isAuthenticated()) {
            if (user != null) {
                LOG.info("Logging in to XMPP as user: " + user + " on connection: " + connection);
                if (password == null) {
                    LOG.warn("No password configured for user: " + user);
                }

                if (createAccount) {
                    AccountManager accountManager = new AccountManager(connection);
                    accountManager.createAccount(user, password);
                }
                if (resource != null) {
                    connection.login(user, password, resource);
                } else {
                    connection.login(user, password);
                }
            } else {
                LOG.info("Logging in anonymously to XMPP on connection: " + connection);
                connection.loginAnonymously();
            }

            // now lets send a presence
            connection.sendPacket(new Presence(Presence.Type.AVAILABLE));
        }
        return connection;
    }
View Full Code Here

TOP

Related Classes of org.jivesoftware.smack.XMPPConnection

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.