org.jivesoftware.smack.Connection Java Examples

The following examples show how to use org.jivesoftware.smack.Connection. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: XMPPTransmitter.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
@Override
public synchronized void connectionStateChanged(Connection connection, ConnectionState state) {

  switch (state) {
    case CONNECTING:
      this.connection = connection;
      break;
    case CONNECTED:
      localJid = new JID(connection.getUser());
      break;
    case ERROR:
    case NOT_CONNECTED:
      this.connection = null;
      localJid = null;
      break;
    default:
      break; // NOP
  }
}
 
Example #2
Source File: MultiUserChatStateManager.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the {@link MultiUserChatStateManager} associated to the {@link MultiUserChat}. Creates
 * one if it does not yet exist.
 *
 * @param connection
 * @param muc
 * @return
 */
public static MultiUserChatStateManager getInstance(
    final Connection connection, final MultiUserChat muc) {

  if (connection == null) {
    return null;
  }

  synchronized (managers) {
    MultiUserChatStateManager manager = managers.get(muc);
    if (manager == null) {
      manager = new MultiUserChatStateManager(connection, muc);
      managers.put(muc, manager);
    }
    return manager;
  }
}
 
Example #3
Source File: XMPPContactsService.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
private void connectionChanged(Connection connection, ConnectionState state) {
  if (state == ConnectionState.CONNECTING) {
    roster = connection.getRoster();
    if (roster == null) {
      log.fatal("A new connection without a roster should not happen!");
      return;
    }

    roster.addRosterListener(rosterListener);
    contacts.clear();
  } else if (state == ConnectionState.CONNECTED) {
    /* The roster provided list is probably empty after connection start, and we get contacts
    later via {@link RosterListener#entriesAdded(Collection)}, but just to be sure. */
    contacts.init(roster);
    notifyListeners(null, UpdateType.CONNECTED);
  } else if (state == ConnectionState.DISCONNECTING || state == ConnectionState.ERROR) {
    if (roster != null) roster.removeRosterListener(rosterListener);
    roster = null;

    contacts.getAll().forEach(XMPPContact::removeResources);
    notifyListeners(null, UpdateType.NOT_CONNECTED);
  }
}
 
Example #4
Source File: XmppVcard.java    From yiim_v2 with GNU General Public License v2.0 6 votes vote down vote up
public void updatePresence() {
	try {
		Connection connection = XmppConnectionUtils.getInstance()
				.getConnection();
		if (connection != null && connection.isConnected()
				&& connection.isAuthenticated()) {
			// 在线状态获取
			Presence presence = connection.getRoster().getPresence(mUserId);
			if (presence.getType() != Type.unavailable) {
				setPresence("online");
			} else {
				setPresence("unavailable");
			}
			saveToDatabase();
		}
	} catch (Exception e) {
		// TODO: handle exception
	}
}
 
Example #5
Source File: FileDownloadListener.java    From yiim_v2 with GNU General Public License v2.0 6 votes vote down vote up
public FileDownloadListener(Context context, Connection connection) {
	this.mConnection = connection;
	this.mContext = context;
	recieveFilePath = YiFileUtils.getStorePath() + "yiim/"
			+ UserInfo.getUserInfo(context).getUserName() + "/file_recv/";

	// ServiceDiscoveryManager sdm = ServiceDiscoveryManager
	// .getInstanceFor(connection);
	// if (sdm == null)
	// sdm = new ServiceDiscoveryManager(connection);
	// sdm.addFeature("http://jabber.org/protocol/disco#info");
	// sdm.addFeature("jabber:iq:privacy");
	FileTransferManager transfer = new FileTransferManager(connection);
	FileTransferNegotiator.setServiceEnabled(connection, true);
	transfer.addFileTransferListener(new RecFileTransferListener());
}
 
Example #6
Source File: Socks5StreamService.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
private Socks5BytestreamManager createManager(Connection connection) {
  Socks5BytestreamManager socks5ByteStreamManager =
      Socks5BytestreamManager.getBytestreamManager(connection);

  socks5ByteStreamManager.setTargetResponseTimeout(TARGET_RESPONSE_TIMEOUT);

  return socks5ByteStreamManager;
}
 
Example #7
Source File: MessengerService.java    From KlyphMessenger with MIT License 5 votes vote down vote up
@Override
public void onCreate()
{
	Log.d(TAG, "onCreate");

	if (instance != null)
		Log.d(TAG, "instance is already defined !");

	instance = this;

	notificationsEnabled = MessengerPreferences.areNotificationsEnabled();
	ringtone = MessengerPreferences.getNotificationRingtone();
	ringtoneUri = MessengerPreferences.getNotificationRingtoneUri();
	vibrateEnabled = MessengerPreferences.isNotificationVibrationEnabled();

	chats = new ArrayList<Chat>();
	roster = new ArrayList<PRosterEntry>();
	savedMessages = new ArrayList<org.jivesoftware.smack.packet.Message>();
	pendingActions = new LinkedHashMap<String, Object>();

	configure(ProviderManager.getInstance());

	Connection.addConnectionCreationListener(new ConnectionCreationListener() {
		public void connectionCreated(Connection connection)
		{
			reconnectionManager = new ReconnectionManager(connection, ConnectionState.getInstance(MessengerService.this).isOnline());
			connection.addConnectionListener(reconnectionManager);
		}
	});

	registerReceiver(new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent)
		{
			Log.i(TAG, "Connection status change to " + ConnectionState.getInstance(MessengerService.this).isOnline());
			onConnectivityChange();
		}
	}, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));

	connect();
}
 
Example #8
Source File: ConnectionHandler.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void connectionStateChanged(Connection connection, ConnectionState state) {
  final Exception error =
      state == ConnectionState.ERROR ? connectionService.getConnectionError() : null;

  setConnectionState(state, error);
}
 
Example #9
Source File: DataTransferManager.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
/** Sets up the stream services for the given XMPPConnection */
private void prepareConnection(final Connection connection) {
  assert xmppConnection == null;

  xmppConnection = connection;
  currentLocalJID = new JID(connection.getUser());

  connectionPool.open();

  for (IStreamService streamService : streamServices)
    streamService.initialize(xmppConnection, byteStreamConnectionListener);
}
 
Example #10
Source File: XMPPReceiver.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void connectionStateChanged(Connection connection, ConnectionState state) {

  switch (state) {
    case CONNECTING:
      connection.addPacketListener(smackPacketListener, null);
      // $FALL-THROUGH$
    case CONNECTED:
      break;
    default:
      if (connection != null) connection.removePacketListener(smackPacketListener);
  }
}
 
Example #11
Source File: MultiUserChatStateManager.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
protected MultiUserChatStateManager(Connection connection, MultiUserChat muc) {
  log.setLevel(Level.TRACE);

  this.connection = connection;
  this.muc = muc;

  // intercepting incoming messages
  this.muc.addMessageListener(incomingMessageInterceptor);

  ServiceDiscoveryManager.getInstanceFor(connection).addFeature(CHATSTATES_FEATURE);
}
 
Example #12
Source File: Socks5StreamService.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void initialize(Connection connection, IByteStreamConnectionListener listener) {

  synchronized (this) {
    localAddress = new JID(connection.getUser());
    socks5Manager = createManager(connection);
    connectionListener = listener;
    socks5Manager.addIncomingBytestreamListener(this);
  }

  executorService =
      Executors.newCachedThreadPool(new NamedThreadFactory("SOCKS5ConnectionResponse-"));
}
 
Example #13
Source File: MultiUserChatService.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void connectionStateChanged(Connection connection, ConnectionState state) {

  if (state == ConnectionState.CONNECTED)
    MultiUserChatService.this.connection.set(connection);
  else MultiUserChatService.this.connection.set(null);
}
 
Example #14
Source File: XmppVcard.java    From yiim_v2 with GNU General Public License v2.0 5 votes vote down vote up
public void load(Connection connection) {
	try {
		load(connection, UserInfo.getUserInfo(mContext).getUser());
	} catch (Exception e) {
		// TODO: handle exception
	}
}
 
Example #15
Source File: XMPPUtils.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates the given account on the given XMPP server.
 *
 * @blocking
 * @param server the server on which to create the account
 * @param username for the new account
 * @param password for the new account
 * @return <code>null</code> if the account was registered, otherwise a {@link Registration
 *     description} is returned which may containing additional information on how to register an
 *     account on the given XMPP server or an error code
 * @see Registration#getError()
 * @throws XMPPException exception that occurs while registering
 */
public static Registration createAccount(String server, String username, String password)
    throws XMPPException {

  Connection connection = new XMPPConnection(server);

  try {
    connection.connect();

    Registration registration = getRegistrationInfo(connection, username);

    /*
     * TODO registration cannot be null, can it?
     */
    if (registration != null) {

      // no in band registration
      if (registration.getError() != null) return registration;

      // already registered
      if (registration.getAttributes().containsKey("registered")) return registration;

      // redirect
      if (registration.getAttributes().size() == 1
          && registration.getAttributes().containsKey("instructions")) return registration;
    }

    AccountManager manager = connection.getAccountManager();
    manager.createAccount(username, password);
  } finally {
    connection.disconnect();
  }

  return null;
}
 
Example #16
Source File: XMPPUtils.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Removes given contact from the {@link Roster}.
 *
 * @blocking
 * @param rosterEntry the contact that is to be removed
 * @throws XMPPException is thrown if no connection is established.
 */
public static void removeFromRoster(Connection connection, RosterEntry rosterEntry)
    throws XMPPException {
  if (!connection.isConnected()) {
    throw new XMPPException("Not connected");
  }
  connection.getRoster().removeEntry(rosterEntry);
}
 
Example #17
Source File: MultiUserChatService.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Connects to a {@link MultiUserChat}. Automatically (if necessary) created and joins the {@link
 * MultiUserChat} based on the {@link MultiUserChatPreferences}.
 *
 * @param preferences
 * @return an {@link IChat} interface for the created chat or <code>null</code> if the chat
 *     creation failed
 */
/*
 * TODO connectMUC should be split into create and join; bkahlert 2010/11/23
 */
public IChat createChat(MultiUserChatPreferences preferences) {
  Connection currentConnection = this.connection.get();

  if (currentConnection == null) {
    log.error("Can't join chat: Not connected.");
    return null;
  }

  MultiUserChat chat = new MultiUserChat(currentConnection, preferences);

  log.debug("Joining MUC...");

  if (preferences.getService() == null) {
    log.warn("MUC service is not available, aborting connection request");
    notifyChatAborted(chat, null);
    return null;
  }

  boolean createdRoom = false;

  try {
    createdRoom = chat.connect();
  } catch (XMPPException e) {
    notifyChatAborted(chat, e.getMessage());
    log.error("Couldn't join chat: " + preferences.getRoom(), e);
    return null;
  }

  chats.add(chat);
  chat.setCurrentState(ChatState.active);
  notifyChatCreated(chat, createdRoom);
  chat.notifyJIDConnected(chat.getJID());

  return chat;
}
 
Example #18
Source File: IBBStreamService.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Override
public synchronized void initialize(
    Connection connection, IByteStreamConnectionListener listener) {
  localAddress = new JID(connection.getUser());
  connectionListener = listener;
  manager = InBandBytestreamManager.getByteStreamManager(connection);
  manager.addIncomingBytestreamListener(this);
}
 
Example #19
Source File: DataTransferManager.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void connectionStateChanged(Connection connection, ConnectionState newState) {
  if (newState == ConnectionState.CONNECTED) prepareConnection(connection);
  else if (this.xmppConnection != null) disposeConnection();
}
 
Example #20
Source File: TCPTransport.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void initialize(Connection connection, IByteStreamConnectionListener listener) {

  currentListener = listener;
}
 
Example #21
Source File: ChatRoomConnection.java    From oneops with Apache License 2.0 4 votes vote down vote up
/**
 * @return the connection
 */
Connection getConnection() {
    return connection;
}
 
Example #22
Source File: SubscriptionHandler.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void connectionStateChanged(Connection connection, ConnectionState connectionSate) {

  if (connectionSate == ConnectionState.CONNECTING) prepareConnection(connection);
  else if (connectionSate != ConnectionState.CONNECTED) disposeConnection();
}
 
Example #23
Source File: XMPPConnectionService.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Configures the service. Must be at least called once before {@link #connect} is called.
 *
 * @param resource the resource qualifier for a running connection
 * @param enableDebug true to show Smack Debug Window upon XMPP connection
 * @param proxyEnabled true to enable Socks5Proxy
 * @param proxyPort Socks5Proxy port
 * @param proxyAddresses collection of addresses (either host name or ip address) for the local
 *     Socks5 proxy, if <code>null</code> the addresses will be determined automatically at proxy
 *     start
 * @param gatewayDeviceID the USN of a UPNP compatible gateways device to perform port mapping on
 *     or <code>null</code>
 * @param useExternalGatewayDeviceAddress if <code>true</code> the external (ip) address of the
 *     gateway will be included into the Socks5 proxy addresses
 * @param stunServer STUN server address or <code>null</code> if STUN discovery should not be
 *     performed
 * @param stunPort STUN server port if 0 the default stun port will be used
 */
public synchronized void configure(
    final String resource,
    final boolean enableDebug,
    final boolean proxyEnabled,
    final int proxyPort,
    final Collection<String> proxyAddresses,
    final String gatewayDeviceID,
    final boolean useExternalGatewayDeviceAddress,
    final String stunServer,
    final int stunPort,
    boolean enablePortMapping) {

  if (isConnected())
    throw new IllegalStateException(
        "cannot configure the network while a connection is established");

  Connection.DEBUG_ENABLED = enableDebug;
  this.resource = resource;
  this.proxyPort = proxyPort;

  if (proxyAddresses != null) this.proxyAddresses = new ArrayList<String>(proxyAddresses);
  else this.proxyAddresses = null;

  this.isProxyEnabled = proxyEnabled;
  this.gatewayDeviceID = gatewayDeviceID;
  this.useExternalGatewayDeviceAddress = useExternalGatewayDeviceAddress;
  this.stunServer = stunServer;
  this.stunPort = stunPort;

  this.device = null;

  if (this.stunServer != null && this.stunServer.isEmpty()) this.stunServer = null;

  if (this.gatewayDeviceID != null && this.gatewayDeviceID.isEmpty()) this.gatewayDeviceID = null;

  if (this.gatewayDeviceID == null) return;

  /*
   * perform blocking tasks in the background meanwhile to speed up first
   * connection attempt, currently it is only UPNP discovery
   */

  ThreadUtils.runSafeAsync(
      "upnp-resolver",
      log,
      new Runnable() {
        @Override
        public void run() {
          if (upnpService != null) upnpService.getGateways(true);
        }
      });
}
 
Example #24
Source File: XMPPUtils.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @param connectionService network component that should be used to resolve the nickname or
 *     <code>null</code> to use the default one
 * @param jid the JID to resolve the nickname for
 * @param alternative nickname to return if no nickname is available, can be <code>null</code>
 * @return The nickname associated with the given JID in the current roster or the
 *     <tt>alternative</tt> representation if the current roster is not available or the nickname
 *     has not been set.
 */
public static String getNickname(
    XMPPConnectionService connectionService, final JID jid, final String alternative) {

  if (connectionService == null) connectionService = defaultConnectionService;

  if (connectionService == null) return alternative;

  Connection connection = connectionService.getConnection();

  if (connection == null) return alternative;

  Roster roster = connection.getRoster();

  if (roster == null) return alternative;

  RosterEntry entry = roster.getEntry(jid.getBase());

  if (entry == null) return alternative;

  String nickName = entry.getName();

  if (nickName != null && nickName.trim().length() > 0) return nickName;

  return alternative;
}
 
Example #25
Source File: XMPPUtils.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns whether the given JID can be found on the server.
 *
 * @blocking
 * @param connection
 * @throws XMPPException if the service discovery failed
 */
public static boolean isJIDonServer(Connection connection, JID jid, String resourceHint)
    throws XMPPException {

  if (isListedInUserDirectory(connection, jid)) return true;

  ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection);

  boolean discovered = sdm.discoverInfo(jid.getRAW()).getIdentities().hasNext();

  if (!discovered && jid.isBareJID() && resourceHint != null && !resourceHint.isEmpty()) {
    discovered = sdm.discoverInfo(jid.getBase() + "/" + resourceHint).getIdentities().hasNext();
  }

  return discovered;
}
 
Example #26
Source File: DataTransferManagerTest.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void initialize(Connection connection, IByteStreamConnectionListener listener) {
  this.listener = listener;
}
 
Example #27
Source File: MessengerService.java    From KlyphMessenger with MIT License 4 votes vote down vote up
private ReconnectionManager(Connection connection, boolean internetIsActive)
{
	this.connection = connection;
}
 
Example #28
Source File: NotificationManager.java    From yiim_v2 with GNU General Public License v2.0 4 votes vote down vote up
public void update() {
	Cursor cursor = null;
	try {
		mOwnUser = UserInfo.getUserInfo(mContext).getUser();

		cursor = mContext.getContentResolver().query(
				ConversationColumns.CONTENT_URI,
				new String[] { ConversationColumns._ID,
						ConversationColumns.MSG,
						ConversationColumns.SUB_MSG,
						ConversationColumns.DEALT,
						ConversationColumns.MSG_DATE },
				ConversationColumns.USER + " like '"
						+ UserInfo.getUserInfo(mContext).getUser()
						+ "%' and " + ConversationColumns.DEALT
						+ " > 0 and " + ConversationColumns.MSG_TYPE
						+ " == " + ConversationType.CHAT_RECORD.getCode(),
				null, null);

		if (cursor != null && cursor.getCount() > 0) {
			cursor.moveToFirst();

			String user = cursor.getString(
					cursor.getColumnIndex(ConversationColumns.MSG))
					.replaceAll("/.+$", "");

			updateNotification(user, cursor.getString(cursor
					.getColumnIndex(ConversationColumns.SUB_MSG)),
					cursor.getLong(cursor
							.getColumnIndex(ConversationColumns.MSG_DATE)));
		} else {
			String string = mContext.getString(R.string.str_online);
			Connection rawConnection = XmppConnectionUtils.getInstance()
					.getRawConnection();
			if (rawConnection == null || !rawConnection.isConnected()
					|| !rawConnection.isAuthenticated()
					|| mXmppBinder.isConnectionClosed()) {
				string = mContext.getString(R.string.str_unavailable);
			}
			updateNotification(mOwnUser, string, System.currentTimeMillis());
		}
	} catch (Exception e) {
		YiLog.getInstance().e(e, "update notification failed");
	} finally {
		if (cursor != null) {
			cursor.close();
			cursor = null;
		}
	}
}
 
Example #29
Source File: AndroidDebugger.java    From AndroidPNClient with Apache License 2.0 4 votes vote down vote up
public AndroidDebugger(Connection connection, Writer writer, Reader reader) {
    this.connection = connection;
    this.writer = writer;
    this.reader = reader;
    createDebug();
}
 
Example #30
Source File: FileUpload.java    From yiim_v2 with GNU General Public License v2.0 4 votes vote down vote up
/**
	 * 发送文件
	 * 
	 * @param connection
	 * @param user
	 * @param toUserName
	 * @param file
	 */
	public static void sendFile(final Context context,
			final Connection connection, final String toUser, final Uri uri,
			final String filePath, final MsgType msgType) {
		new Thread() {
			public void run() {
				XMPPConnection.DEBUG_ENABLED = true;
				// AccountManager accountManager;
				try {
					// accountManager = connection.getAccountManager();
					Presence pre = connection.getRoster().getPresence(toUser);
					if (pre.getType() != Presence.Type.unavailable) {
						if (connection.isConnected()) {
							Log.d(TAG, "connection con");
						}
						// 创建文件传输管理器
//						ServiceDiscoveryManager sdm = ServiceDiscoveryManager
//								.getInstanceFor(connection);
//						if (sdm == null)
//							sdm = new ServiceDiscoveryManager(connection);
						
						FileTransferManager manager = new FileTransferManager(
								connection);
						// 创建输出的文件传输
						OutgoingFileTransfer transfer = manager
								.createOutgoingFileTransfer(pre.getFrom());
						// 发送文件
						transfer.sendFile(new File(filePath),
								msgType.toString());
						while (!transfer.isDone()) {
							if (transfer.getStatus() == FileTransfer.Status.in_progress) {
								// 可以调用transfer.getProgress();获得传输的进度 
								// Log.d(TAG,
								// "send status:" + transfer.getStatus());
								// Log.d(TAG,
								// "send progress:"
								// + transfer.getProgress());
								if (mFileUploadListener != null) {
									mFileUploadListener.transProgress(context,
											uri, filePath,
											transfer.getProgress());
								}
							}
						}
						// YiLog.getInstance().i("send file error: %s",
						// transfer.);
						Log.d(TAG, "send status 1 " + transfer.getStatus());
						if (transfer.isDone()) {
							if (mFileUploadListener != null) {
								mFileUploadListener.transDone(context, toUser,
										uri, msgType, filePath,
										transfer.getStatus());
							}
						}
					}
				} catch (Exception e) {
					Log.d(TAG, "send exception");
					if (mFileUploadListener != null) {
						mFileUploadListener.transDone(context, toUser, uri,
								msgType, filePath, Status.error);
					}
				}
			}
		}.start();
	}