@Override public void run() { Log.i(LOGTAG, "ConnectTask.run()..."); XmppManager xmppManager = getXmppManager(); if (!xmppManager.isConnected()) { ConnectionConfiguration connCfg = new ConnectionConfiguration(xmppManager.getXmppHost(), xmppManager.getXmppPort()); connCfg.setSecurityMode(SecurityMode.required); connCfg.setSASLAuthenticationEnabled(false); connCfg.setCompressionEnabled(false); XMPPConnection connection = new XMPPConnection(connCfg); xmppManager.setConnection(connection); try { connection.connect(); ProviderManager.getInstance() .addIQProvider( "notification", Constants.NOTIFICATION_NAMESPACE, new NotificationIQProvider()); Log.i(LOGTAG, "XMPP connected successfully"); xmppManager.getContext().sendBroadcast(new Intent(Constants.ACTION_CONNECT_SUCCESS)); } catch (XMPPException e) { Log.e(LOGTAG, "XMPP connection failed", e); xmppManager.getContext().sendBroadcast(new Intent(Constants.ACTION_CONNECT_FAIL)); } xmppManager.runTask(); } else { Log.i(LOGTAG, "XMPP connected already"); xmppManager.runTask(); } }
private void connectUsingConfiguration(ConnectionConfiguration config) throws XMPPException { String host = config.getHost(); int port = config.getPort(); try { if (config.getSocketFactory() == null) { this.socket = new Socket(host, port); } else { this.socket = config.getSocketFactory().createSocket(host, port); } if (ConnectionConfiguration.SecurityMode.legacy == config.getSecurityMode()) { try { enableEncryption(false); } catch (Exception e) { String errorMessage = "Could not enable SSL encryption while connecting to " + host + ":" + port + "."; throw new XMPPException( errorMessage, new XMPPError(XMPPError.Condition.remote_server_error, errorMessage), e); } usingSSL = true; } } catch (UnknownHostException uhe) { String errorMessage = "Could not connect to " + host + ":" + port + "."; throw new XMPPException( errorMessage, new XMPPError(XMPPError.Condition.remote_server_timeout, errorMessage), uhe); } catch (IOException ioe) { String errorMessage = "XMPPError connecting to " + host + ":" + port + "."; throw new XMPPException( errorMessage, new XMPPError(XMPPError.Condition.remote_server_error, errorMessage), ioe); } initConnection(); }
public void prepareSession(String domain) { System.out.printf("Initializing connection to server %1$s:%2$d\n", domain, port); SmackConfiguration.setPacketReplyTimeout(PACKET_REPLY_TIMEOUT); config = new ConnectionConfiguration(domain, port); config.setSASLAuthenticationEnabled(true); config.setSecurityMode(SecurityMode.disabled); }
/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final EditText et = (EditText) findViewById(R.id.editText1); final TextView tv = (TextView) findViewById(R.id.textView1); tv.setMovementMethod(new ScrollingMovementMethod()); Button startButton = (Button) findViewById(R.id.button1); startButton.setOnClickListener( new OnClickListener() { public void onClick(View v) { tv.append("ME: " + et.getText().toString() + "\n"); Message msg = new Message(); // msg.setTo("*****@*****.**"); // msg.setTo("*****@*****.**"); msg.setTo("*****@*****.**"); msg.setBody(et.getText().toString()); ((XMPPConnection) connection).sendPacket(msg); } }); try { // ConnectionConfiguration config = new ConnectionConfiguration("chat.facebook.com", 5222); // ConnectionConfiguration config = new ConnectionConfiguration("chatme.im", 5222); ConnectionConfiguration config = new ConnectionConfiguration("ppl.eln.uniroma2.it", 5222); config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled); connection = (Connection) new XMPPConnection(config); ((XMPPConnection) connection).connect(); // ((org.jivesoftware.smack.Connection) connection).login("mattiapan","totti10"); // ((org.jivesoftware.smack.Connection) connection).login("admin5551","admin5551"); ((org.jivesoftware.smack.Connection) connection).login("panattoni", "mattia"); } catch (XMPPException e) { // Log.e("paolo", "try catch error connection"); e.printStackTrace(); } ((org.jivesoftware.smack.Connection) connection) .addPacketListener( new PacketListener() { @Override public void processPacket(Packet pkt) { Message msg = (Message) pkt; String from = msg.getFrom(); String body = msg.getBody(); tv.append(from + " : " + body + "\n"); } }, new MessageTypeFilter(Message.Type.normal)); }
/** * Represents a single connection to a League of Legends chatserver. * * @param server The chatserver of the region you want to connect to * @param friendRequestPolicy Determines how new Friend requests are treated. * @param riotApiKey Your apiKey used to convert summonerId's to name. You can get your key here * <a href="https://developer.riotgames.com/">developer .riotgames.com</a> * @see LolChat#setFriendRequestPolicy(FriendRequestPolicy) * @see LolChat#setFriendRequestListener(FriendRequestListener) */ public LolChat( ChatServer server, FriendRequestPolicy friendRequestPolicy, RiotApiKey riotApiKey) { this.friendRequestPolicy = friendRequestPolicy; this.server = server; if (riotApiKey != null && server.api != null) { this.riotApi = RiotApi.build(riotApiKey, server); } Roster.setDefaultSubscriptionMode(SubscriptionMode.manual); final ConnectionConfiguration config = new ConnectionConfiguration(server.host, 5223, "pvp.net"); config.setSecurityMode(ConnectionConfiguration.SecurityMode.enabled); config.setSocketFactory(SSLSocketFactory.getDefault()); config.setCompressionEnabled(true); connection = new XMPPTCPConnection(config); addListeners(); }
public void onClick(View v) { host = getText(R.id.host); port = getText(R.id.port); service = getText(R.id.service); username = getText(R.id.userid); password = getText(R.id.password); // Log.i("FYI", host+port+service+username+password); // Create connection connectionConfig = new ConnectionConfiguration(host, Integer.parseInt(port), service); connectionConfig.setSecurityMode( ConnectionConfiguration.SecurityMode.enabled); // -\__ Required for OpenFire login connectionConfig.setSocketFactory(new DummySSLSocketFactory()); // _/ // connectionConfig.setSASLAuthenticationEnabled(false); // required for talk.google.com // connectionConfig.setTruststoreType("BKS"); // required for talk.google.com connection = new XMPPConnection(connectionConfig); new ConnectToXmpp().execute(); }
@Override public synchronized void connect(String username, String password) throws RemoteException { if (isConnected()) { notifyLogin(1, "already connected"); return; } ConnectionConfiguration config = new ConnectionConfiguration(serveraddress, serverPort); config.setCompressionEnabled(true); config.setSASLAuthenticationEnabled(true); try { connection = new XMPPConnection(config); connection.connect(); connection.login(username, password, "smack"); assert connection.isSecureConnection(); notifyLogin(0, "login succeeded"); } catch (XMPPException e) { notifyLogin(-1, "login failed, reason : " + e.getMessage()); } }
/** * Initialize the {@link #debugger}. You can specify a customized {@link SmackDebugger} by setup * the system property <code>smack.debuggerClass</code> to the implementation. * * @throws IllegalStateException if the reader or writer isn't yet initialized. * @throws IllegalArgumentException if the SmackDebugger can't be loaded. */ protected void initDebugger() { if (reader == null || writer == null) { throw new NullPointerException("Reader or writer isn't initialized."); } // If debugging is enabled, we open a window and write out all network traffic. if (config.isDebuggerEnabled()) { if (debugger == null) { // Detect the debugger class to use. String className = null; // Use try block since we may not have permission to get a system // property (for example, when an applet). try { className = System.getProperty("smack.debuggerClass"); } catch (Throwable t) { // Ignore. } Class<?> debuggerClass = null; if (className != null) { try { debuggerClass = Class.forName(className); } catch (Exception e) { e.printStackTrace(); } } if (debuggerClass == null) { try { debuggerClass = Class.forName("org.jivesoftware.smackx.debugger.EnhancedDebugger"); } catch (Exception ex) { try { debuggerClass = Class.forName("org.jivesoftware.smack.debugger.LiteDebugger"); } catch (Exception ex2) { ex2.printStackTrace(); } } } // Create a new debugger instance. If an exception occurs then disable the debugging // option try { Constructor<?> constructor = debuggerClass.getConstructor(Connection.class, Writer.class, Reader.class); debugger = (SmackDebugger) constructor.newInstance(this, writer, reader); reader = debugger.getReader(); writer = debugger.getWriter(); } catch (Exception e) { throw new IllegalArgumentException("Can't initialize the configured debugger!", e); } } else { // Obtain new reader and writer from the existing debugger reader = debugger.newConnectionReader(reader); writer = debugger.newConnectionWriter(writer); } } }
@SuppressLint("TrulyRandom") private XMPPConnection createConnection() { ConnectionConfiguration config = new ConnectionConfiguration(PreferenceUtils.getServerHost(context), PORT); SSLContext sc = null; MemorizingTrustManager mtm = null; try { mtm = new MemorizingTrustManager(context); sc = SSLContext.getInstance("TLS"); sc.init(null, new X509TrustManager[] {mtm}, new SecureRandom()); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } catch (KeyManagementException e) { throw new IllegalStateException(e); } config.setCustomSSLContext(sc); config.setHostnameVerifier( mtm.wrapHostnameVerifier(new org.apache.http.conn.ssl.StrictHostnameVerifier())); config.setSecurityMode(SecurityMode.required); config.setReconnectionAllowed(false); config.setSendPresence(false); return new XMPPTCPConnection(config); }
@Override public void run() { if (!xmppManager.isConnected() && !xmppManager.isRunning()) { try { xmppManager.setRunning(true); // Create the configuration for this new connection ConnectionConfiguration connConfig = new ConnectionConfiguration(xmppManager.getXmppHost(), xmppManager.getXmppPort()); connConfig.setSecurityMode(SecurityMode.disabled); // connConfig.setSecurityMode(SecurityMode.required); connConfig.setSASLAuthenticationEnabled(false); connConfig.setCompressionEnabled(false); XMPPConnection connection = new XMPPConnection(connConfig); xmppManager.setConnection(connection); // Connect to the server connection.connect(); // packet provider connection.addConnectionListener(xmppManager.getConnectionListener()); ProviderManager.getInstance() .addIQProvider( "notification", "androidpn:iq:notification", xmppManager.getNotificationIQProvider()); Log.i(LOG_TAG, "XMPP connected successfully"); callback.onSuccess(); } catch (Exception e) { Log.e(LOG_TAG, "XMPP connection failed", e); callback.onFailed("XMPP connection failed"); } finally { xmppManager.setRunning(false); } } else { Log.w(LOG_TAG, "XMPP is connected or is running"); callback.onFailed("XMPP is connected or is running"); } }
private void connectUsingFactory(ConnectionConfigurationFactory factory) throws FriendException { ConnectionConfigurationFactory.RequestContext requestContext = new ConnectionConfigurationFactory.RequestContext(); while (factory.hasMore(configuration, requestContext)) { ConnectionConfiguration connectionConfig = factory.getConnectionConfiguration(configuration, requestContext); connection = new XMPPConnection(connectionConfig); connection.addRosterListener(new RosterListenerImpl()); LOG.infof( "connecting to {0} at {1}:{2} ...", connectionConfig.getServiceName(), connectionConfig.getHost(), connectionConfig.getPort()); try { connection.connect(); return; } catch (org.jivesoftware.smack.XMPPException e) { LOG.debug(e.getMessage(), e); requestContext.incrementRequests(); } } throw new FriendException("couldn't connect using " + factory); }
public void connectXMPPServer() throws XMPPException { org.jivesoftware.smackx.ConfigureProviderManager.configureProviderManager(); init(); ConnectionConfiguration config = new ConnectionConfiguration(xmppServer, port); config.setTruststoreType("BKS"); config.setTruststorePath("/system/etc/security/cacerts.bks"); mXMPPConnection = new XMPPConnection(config); mXMPPConnection.connect(); mXMPPConnection.login(userName, password); if (mXMPPConnection.isAuthenticated()) { System.out.println("JID authenticated successfully!"); } Roster.setDefaultSubscriptionMode(SubscriptionMode.manual); mPubSubManager = new PubSubManager(mXMPPConnection, "pubsub." + mXMPPConnection.getServiceName()); }
// this code runs a DNS resolver, might be blocking private synchronized void initXMPPConnection() { // allow custom server / custom port to override SRV record if (mConfig.customServer.length() > 0) mXMPPConfig = new ConnectionConfiguration(mConfig.customServer, mConfig.port, mConfig.server); else mXMPPConfig = new ConnectionConfiguration(mConfig.server); // use SRV mXMPPConfig.setReconnectionAllowed(false); mXMPPConfig.setSendPresence(false); mXMPPConfig.setCompressionEnabled(false); // disable for now mXMPPConfig.setDebuggerEnabled(mConfig.smackdebug); if (mConfig.require_ssl) this.mXMPPConfig.setSecurityMode(ConnectionConfiguration.SecurityMode.required); // register MemorizingTrustManager for HTTPS try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init( null, new X509TrustManager[] {YaximApplication.getApp(mService).mMTM}, new java.security.SecureRandom()); this.mXMPPConfig.setCustomSSLContext(sc); } catch (java.security.GeneralSecurityException e) { debugLog("initialize MemorizingTrustManager: " + e); } this.mXMPPConnection = new XmppStreamHandler.ExtXMPPConnection(mXMPPConfig); this.mStreamHandler = new XmppStreamHandler(mXMPPConnection, mConfig.smackdebug); mStreamHandler.addAckReceivedListener( new XmppStreamHandler.AckReceivedListener() { public void ackReceived(long handled, long total) { gotServerPong("" + handled); } }); mConfig.reconnect_required = false; initServiceDiscovery(); }
// this code runs a DNS resolver, might be blocking private synchronized void initXMPPConnection() { // allow custom server / custom port to override SRV record if (configuration.customServer.length() > 0) connectionConfiguration = new ConnectionConfiguration( configuration.customServer, configuration.port, configuration.server); else connectionConfiguration = new ConnectionConfiguration(configuration.server); // use SRV connectionConfiguration.setReconnectionAllowed(false); connectionConfiguration.setSendPresence(false); connectionConfiguration.setCompressionEnabled(false); // disable for now connectionConfiguration.setDebuggerEnabled(configuration.smackdebug); if (configuration.require_ssl) this.connectionConfiguration.setSecurityMode(ConnectionConfiguration.SecurityMode.required); try { SSLContext sc = SSLContext.getInstance(Constant.TLS); MemorizingTrustManager mtm = JApplication.getApp(service).memorizingTrustManager; sc.init(null, new X509TrustManager[] {mtm}, new java.security.SecureRandom()); this.connectionConfiguration.setCustomSSLContext(sc); this.connectionConfiguration.setHostnameVerifier( mtm.wrapHostnameVerifier(new org.apache.http.conn.ssl.StrictHostnameVerifier())); } catch (java.security.GeneralSecurityException e) { Log.d(TAG, "initialize MemorizingTrustManager: " + e); } this.extXMPPConnection = new StreamHandler.ExtXMPPConnection(connectionConfiguration); this.streamHandler = new StreamHandler(extXMPPConnection, configuration.smackdebug); streamHandler.addAckReceivedListener( new StreamHandler.AckReceivedListener() { public void ackReceived(long handled, long total) { gotServerPong("" + handled); } }); configuration.reconnect_required = false; initServiceDiscovery(); }
/** * Initialize the XMPP connection. * * @param jid the jid to use * @param server the server to use (not using dns srv) may be null * @param port the port * @return the XMPPConnection prepared to connect */ private Connection prepareConnection(String jid, String server, int port) { boolean useProxy = settings.getBoolean(BeemApplication.PROXY_USE_KEY, false); ProxyInfo proxyinfo = ProxyInfo.forNoProxy(); if (useProxy) { String stype = settings.getString(BeemApplication.PROXY_TYPE_KEY, "HTTP"); String phost = settings.getString(BeemApplication.PROXY_SERVER_KEY, ""); String puser = settings.getString(BeemApplication.PROXY_USERNAME_KEY, ""); String ppass = settings.getString(BeemApplication.PROXY_PASSWORD_KEY, ""); int pport = Integer.parseInt(settings.getString(BeemApplication.PROXY_PORT_KEY, "1080")); ProxyInfo.ProxyType type = ProxyType.valueOf(stype); proxyinfo = new ProxyInfo(type, phost, pport, puser, ppass); } String serviceName = StringUtils.parseServer(jid); if (port != -1 || !TextUtils.isEmpty(server)) { if (port == -1) port = 5222; if (TextUtils.isEmpty(server)) server = serviceName; config = new ConnectionConfiguration(server, port, serviceName, proxyinfo); } else { config = new ConnectionConfiguration(serviceName, proxyinfo); } if (settings.getBoolean(BeemApplication.SMACK_DEBUG_KEY, false)) config.setDebuggerEnabled(true); return new XMPPConnection(config); }
/** * Returns the name of the service provided by the XMPP server for this connection. This is also * called XMPP domain of the connected server. After authenticating with the server the returned * value may be different. * * @return the name of the service provided by the XMPP server. */ public String getServiceName() { return config.getServiceName(); }
public boolean isSendPresence() { return config.isSendPresence(); }
/** * Creates a new XMPP connection using the specified connection configuration. * * <p> * * <p>Manually specifying connection configuration information is suitable for advanced users of * the API. In many cases, using the {@link #XMPPConnection(String)} constructor is a better * approach. * * <p> * * <p>Note that XMPPConnection constructors do not establish a connection to the server and you * must call {@link #connect()}. * * <p> * * <p>The CallbackHandler will only be used if the connection requires the client provide an SSL * certificate to the server. The CallbackHandler must handle the PasswordCallback to prompt for a * password to unlock the keystore containing the SSL certificate. * * @param config the connection configuration. * @param callbackHandler the CallbackHandler used to prompt for the password to the keystore. */ public XMPPConnection(ConnectionConfiguration config, CallbackHandler callbackHandler) { super(config); config.setCallbackHandler(callbackHandler); }
/** Constructor for XMPPNotificationManager. */ protected XMPPNotificationManager() { Map<String, String> mdc = Logging.getCopyOfContextMap(); try { mdc.put(Logging.PREFIX_KEY, LOG4J_CATEGORY); // Load up some properties File config = null; try { config = ConfigFileConstants.getFile(ConfigFileConstants.XMPP_CONFIG_FILE_NAME); } catch (IOException e) { LOG.warn("{} not readable", ConfigFileConstants.XMPP_CONFIG_FILE_NAME, e); } if (Boolean.getBoolean("useSystemXMPPConfig") || !config.canRead()) { this.props.putAll(System.getProperties()); } else { FileInputStream fis = null; try { fis = new FileInputStream(config); this.props.load(fis); } catch (FileNotFoundException e) { LOG.warn("unable to load {}", config, e); } catch (IOException e) { LOG.warn("unable to load {}", config, e); } finally { IOUtils.closeQuietly(fis); } } xmppServer = this.props.getProperty("xmpp.server"); String xmppServiceName = this.props.getProperty("xmpp.servicename", xmppServer); xmppUser = this.props.getProperty("xmpp.user"); xmppPassword = this.props.getProperty("xmpp.pass"); xmppPort = Integer.valueOf(this.props.getProperty("xmpp.port", XMPP_PORT)); ConnectionConfiguration xmppConfig = new ConnectionConfiguration(xmppServer, xmppPort, xmppServiceName); boolean debuggerEnabled = Boolean.parseBoolean(props.getProperty("xmpp.debuggerEnabled")); xmppConfig.setDebuggerEnabled(debuggerEnabled); xmppConfig.setSASLAuthenticationEnabled( Boolean.parseBoolean(props.getProperty("xmpp.SASLEnabled", "true"))); xmppConfig.setSelfSignedCertificateEnabled( Boolean.parseBoolean(props.getProperty("xmpp.selfSignedCertificateEnabled"))); if (Boolean.parseBoolean(props.getProperty("xmpp.TLSEnabled"))) { xmppConfig.setSecurityMode(SecurityMode.enabled); } else { xmppConfig.setSecurityMode(SecurityMode.disabled); } if (this.props.containsKey("xmpp.truststorePassword")) { xmppConfig.setTruststorePassword(this.props.getProperty("xmpp.truststorePassword")); } else { xmppConfig.setTruststorePassword(TRUST_STORE_PASSWORD); } LOG.debug("XMPP Manager connection config: {}", xmppConfig.toString()); xmpp = new XMPPConnection(xmppConfig); // Connect to xmpp server connectToServer(); } finally { Logging.setContextMap(mdc); } }
public String getJid() { try { System.out.println("getJid method executed"); ConnectionConfiguration config = new ConnectionConfiguration(DOMAIN, PORT); config.setSASLAuthenticationEnabled(true); XMPPConnection con = new XMPPConnection(config); con.connect(); System.out.println("Connection ok"); con.login("searchuser", "search"); System.out.println("Logged in"); UserSearchManager search = new UserSearchManager(con); System.out.println("User Search created"); Collection services = search.getSearchServices(); System.out.println("Search Services found:"); Iterator it = services.iterator(); while (it.hasNext()) { System.out.println(it.next()); } Form searchForm = search.getSearchForm("search." + "cuopencomm"); System.out.println("Available search fields:"); Iterator<FormField> fields = searchForm.getFields(); while (fields.hasNext()) { FormField field = fields.next(); System.out.println(field.getVariable() + " : " + field.getType()); } Form answerForm = searchForm.createAnswerForm(); answerForm.setAnswer("search", email); answerForm.setAnswer("Email", true); ReportedData data = search.getSearchResults(answerForm, "search." + "cuopencomm"); System.out.println("\nColumns that are included as part of the search results:"); Iterator<Column> columns = data.getColumns(); while (columns.hasNext()) { System.out.println(columns.next().getVariable()); } System.out.println("\nThe jids and emails from our each of our hits:"); Iterator<Row> rows = data.getRows(); while (rows.hasNext()) { Row row = rows.next(); Iterator<String> jids = row.getValues("jid"); Iterator<String> emails = row.getValues("email"); String jidFound = null; String emailFound = null; while (emails.hasNext() && jids.hasNext()) { jidFound = jids.next(); emailFound = emails.next(); System.out.println(jidFound); System.out.println(emailFound); if (emailFound.equalsIgnoreCase(email)) { jid = jidFound; String[] jidCleaned = jid.split("@"); jid = jidCleaned[0]; System.out.println(jid); } } } con.disconnect(); return jid; } catch (Exception ex) { System.out.println("Caught Exception :" + ex.getMessage()); return jid; } }
public XMPPConnection createConnection(ConnectionConfiguration config) { config.setCallbackHandler(this); XMPPConnection conn = new XMPPConnection(config); conn.getSASLAuthentication().supportSASLMechanism("X-OAUTH2"); return conn; }
/** * Connects to GCM Cloud Connection Server using the supplied credentials. * * @throws XMPPException */ public void connect() throws XMPPException { config = new ConnectionConfiguration(Properties.GCM_SERVER, Properties.GCM_PORT); config.setSecurityMode(SecurityMode.enabled); config.setReconnectionAllowed(true); config.setRosterLoadedAtLogin(false); config.setSendPresence(false); config.setSocketFactory(SSLSocketFactory.getDefault()); // NOTE: Set to true to launch a window with information about packets sent and received config.setDebuggerEnabled(false); // -Dsmack.debugEnabled=true XMPPConnection.DEBUG_ENABLED = false; connection = new XMPPConnection(config); connection.connect(); connection.addConnectionListener( new ConnectionListener() { public void reconnectionSuccessful() { logger.info("Reconnecting.."); } public void reconnectionFailed(Exception e) { logger.log(Level.INFO, "Reconnection failed.. ", e); } public void reconnectingIn(int seconds) { logger.log(Level.INFO, "Reconnecting in %d secs", seconds); } public void connectionClosedOnError(Exception e) { logger.log(Level.INFO, "Connection closed on error."); } public void connectionClosed() { logger.info("Connection closed."); } }); // Handle incoming packets connection.addPacketListener( new PacketListener() { public void processPacket(Packet packet) { logger.log(Level.INFO, "Received: " + packet.toXML()); Message incomingMessage = (Message) packet; GcmPacketExtension gcmPacket = (GcmPacketExtension) incomingMessage.getExtension(Properties.GCM_NAMESPACE); String json = gcmPacket.getJson(); try { @SuppressWarnings("unchecked") Map<String, Object> jsonObject = (Map<String, Object>) JSONValue.parseWithException(json); // present for "ack"/"nack", null otherwise Object messageType = jsonObject.get("message_type"); if (messageType == null) { // Normal upstream data message handleIncomingDataMessage(jsonObject); // Send ACK to CCS String messageId = jsonObject.get("message_id").toString(); String from = jsonObject.get("from").toString(); String ack = createJsonAck(from, messageId); send(ack); } else if ("ack".equals(messageType.toString())) { // Process Ack handleAckReceipt(jsonObject); } else if ("nack".equals(messageType.toString())) { // Process Nack handleNackReceipt(jsonObject); } else { logger.log(Level.WARNING, "Unrecognized message type (%s)", messageType.toString()); } } catch (ParseException e) { logger.log(Level.SEVERE, "Error parsing JSON " + json, e); } catch (Exception e) { logger.log(Level.SEVERE, "Couldn't send echo.", e); } } }, new PacketTypeFilter(Message.class)); // Log all outgoing packets connection.addPacketInterceptor( new PacketInterceptor() { public void interceptPacket(Packet packet) { logger.log(Level.INFO, "Sent: {0}", packet.toXML()); } }, new PacketTypeFilter(Message.class)); connection.login(Properties.userName, Properties.password); }
/** * Returns the host name of the server where the XMPP server is running. This would be the IP * address of the server or a name that may be resolved by a DNS server. * * @return the host name of the server where the XMPP server is running. */ public String getHost() { return config.getHost(); }
/** * Connects to GCM Cloud Connection Server using the supplied credentials. * * @param senderId Your GCM project number * @param apiKey API Key of your project */ public void connect(long senderId, String apiKey) throws XMPPException, IOException, SmackException { ConnectionConfiguration config = new ConnectionConfiguration(GCM_SERVER, GCM_PORT); config.setSecurityMode(SecurityMode.enabled); config.setReconnectionAllowed(true); config.setRosterLoadedAtLogin(false); config.setSendPresence(false); config.setSocketFactory(SSLSocketFactory.getDefault()); connection = new XMPPTCPConnection(config); connection.connect(); connection.addConnectionListener(new LoggingConnectionListener()); // Handle incoming packets connection.addPacketListener( new PacketListener() { @Override public void processPacket(Packet packet) { logger.log(Level.INFO, "Received: " + packet.toXML()); Message incomingMessage = (Message) packet; GcmPacketExtension gcmPacket = (GcmPacketExtension) incomingMessage.getExtension(GCM_NAMESPACE); String json = gcmPacket.getJson(); try { @SuppressWarnings("unchecked") Map<String, Object> jsonObject = (Map<String, Object>) JSONValue.parseWithException(json); // present for "ack"/"nack", null otherwise Object messageType = jsonObject.get("message_type"); if (messageType == null) { // Normal upstream data message handleUpstreamMessage(jsonObject); // Send ACK to CCS String messageId = (String) jsonObject.get("message_id"); String from = (String) jsonObject.get("from"); String ack = createJsonAck(from, messageId); send(ack); } else if ("ack".equals(messageType.toString())) { // Process Ack handleAckReceipt(jsonObject); } else if ("nack".equals(messageType.toString())) { // Process Nack handleNackReceipt(jsonObject); } else if ("control".equals(messageType.toString())) { // Process control message handleControlMessage(jsonObject); } else { logger.log(Level.WARNING, "Unrecognized message type (%s)", messageType.toString()); } } catch (ParseException e) { logger.log(Level.SEVERE, "Error parsing JSON " + json, e); } catch (Exception e) { logger.log(Level.SEVERE, "Failed to process packet", e); } } }, new PacketTypeFilter(Message.class)); // Log all outgoing packets connection.addPacketInterceptor( new PacketInterceptor() { @Override public void interceptPacket(Packet packet) { logger.log(Level.INFO, "Sent: {0}", packet.toXML()); } }, new PacketTypeFilter(Message.class)); connection.login(senderId + "@gcm.googleapis.com", apiKey); }
/** Constructor for XMPPNotificationManager. */ protected XMPPNotificationManager() { // get the category logger String oldPrefix = ThreadCategory.getPrefix(); ThreadCategory.setPrefix(LOG4J_CATEGORY); try { // Load up some properties File config = null; try { config = ConfigFileConstants.getFile(ConfigFileConstants.XMPP_CONFIG_FILE_NAME); } catch (IOException e) { log().warn(ConfigFileConstants.XMPP_CONFIG_FILE_NAME + " not readable", e); } if (Boolean.getBoolean("useSystemXMPPConfig") || !config.canRead()) { this.props.putAll(System.getProperties()); } else { FileInputStream fis = null; try { fis = new FileInputStream(config); this.props.load(fis); } catch (FileNotFoundException e) { log().warn("unable to load " + config, e); } catch (IOException e) { log().warn("unable to load " + config, e); } finally { IOUtils.closeQuietly(fis); } } xmppServer = this.props.getProperty("xmpp.server"); xmppServiceName = this.props.getProperty("xmpp.servicename", xmppServer); xmppUser = this.props.getProperty("xmpp.user"); xmppPassword = this.props.getProperty("xmpp.pass"); xmppPort = Integer.valueOf(this.props.getProperty("xmpp.port", XMPP_PORT)); xmppConfig = new ConnectionConfiguration(xmppServer, xmppPort, xmppServiceName); boolean debuggerEnabled = Boolean.parseBoolean(props.getProperty("xmpp.debuggerEnabled")); xmppConfig.setDebuggerEnabled(debuggerEnabled); if (debuggerEnabled) { log().setLevel(ThreadCategory.Level.DEBUG); } xmppConfig.setSASLAuthenticationEnabled( Boolean.parseBoolean(props.getProperty("xmpp.SASLEnabled", "true"))); xmppConfig.setSelfSignedCertificateEnabled( Boolean.parseBoolean(props.getProperty("xmpp.selfSignedCertificateEnabled"))); if (Boolean.parseBoolean(props.getProperty("xmpp.TLSEnabled"))) { xmppConfig.setSecurityMode(SecurityMode.enabled); } else { xmppConfig.setSecurityMode(SecurityMode.disabled); } if (this.props.containsKey("xmpp.truststorePassword")) { xmppConfig.setTruststorePassword(this.props.getProperty("xmpp.truststorePassword")); } else { xmppConfig.setTruststorePassword(TRUST_STORE_PASSWORD); } if (log().isDebugEnabled()) { log().debug("XMPP Manager connection config: " + xmppConfig.toString()); } xmpp = new XMPPConnection(xmppConfig); // Connect to xmpp server connectToServer(); } finally { ThreadCategory.setPrefix(oldPrefix); } }
/** * Returns if the reconnection mechanism is allowed to be used. By default reconnection is * allowed. * * @return true if the reconnection mechanism is allowed to be used. */ protected boolean isReconnectionAllowed() { return config.isReconnectionAllowed(); }
/** * Returns the port number of the XMPP server for this connection. The default port for normal * connections is 5222. The default port for SSL connections is 5223. * * @return the port number of the XMPP server. */ public int getPort() { return config.getPort(); }