Java Code Examples for org.jivesoftware.smack.XMPPConnection#isAuthenticated()

The following examples show how to use org.jivesoftware.smack.XMPPConnection#isAuthenticated() . 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: XmppLoginRunnable.java    From yiim_v2 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public XmppResult execute() {
	XmppResult result = createResult();
	try {
		XMPPConnection connection = XmppConnectionUtils.getInstance()
				.getConnection();
		if (connection.isAuthenticated()) {
			XmppConnectionUtils.getInstance().closeConnection();
			connection = XmppConnectionUtils.getInstance().getConnection();
		}
		connection.login(mUserName, mPasswd);
		Presence presence = new Presence(mType, mStatus, 1, mMode);
		connection.sendPacket(presence);

		FileDownloadListener.setRecieveFilePath(YiFileUtils.getStorePath()
				+ "yiim/" + mUserName + "file_recv/");

		result.status = Status.SUCCESS;
	} catch (Exception e) {
		result.obj = e.getMessage();
	}
	return result;
}
 
Example 2
Source File: YiIMUtils.java    From yiim_v2 with GNU General Public License v2.0 6 votes vote down vote up
public static boolean isRoomExist(String roomJid) throws Exception {
	XMPPConnection connection = XmppConnectionUtils.getInstance()
			.getRawConnection();
	if (connection == null || !connection.isAuthenticated()) {
		throw new Exception("no connections");
	}
	try {
		RoomInfo roomInfo = MultiUserChat.getRoomInfo(connection, roomJid);
		if (roomInfo != null) {
			return true;
		}
		return false;
	} catch (Exception e) {
		return false;
	}
}
 
Example 3
Source File: AccountManager.java    From Smack with Apache License 2.0 6 votes vote down vote up
public boolean isSupported()
                throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    XMPPConnection connection = connection();

    ExtensionElement extensionElement = connection.getFeature(Registration.Feature.ELEMENT,
                    Registration.Feature.NAMESPACE);
    if (extensionElement != null) {
        return true;
    }

    // Fallback to disco#info only if this connection is authenticated, as otherwise we won't have an full JID and
    // won't be able to do IQs.
    if (connection.isAuthenticated()) {
        return ServiceDiscoveryManager.getInstanceFor(connection).serverSupportsFeature(Registration.NAMESPACE);
    }

    return false;
}
 
Example 4
Source File: YiIMUtils.java    From yiim_v2 with GNU General Public License v2.0 5 votes vote down vote up
public static int addGroup(Context context, String groupName) {
	String owner = UserInfo.getUserInfo(context).getUser();
	Cursor groupCursor = null;
	try {
		groupCursor = context.getContentResolver().query(
				RosterGroupColumns.CONTENT_URI,
				new String[] { RosterGroupColumns._ID },
				RosterGroupColumns.NAME + "='" + groupName + "' and "
						+ RosterGroupColumns.OWNER + "='" + owner + "'",
				null, null);
		if (groupCursor != null && groupCursor.getCount() != 0) {
			return -1;
		}

		XMPPConnection connection = XmppConnectionUtils.getInstance()
				.getConnection();
		if (connection != null && connection.isConnected()
				&& connection.isAuthenticated()) {
			connection.getRoster().createGroup(groupName);

			ContentValues values = new ContentValues();
			values.put(RosterGroupColumns.NAME, groupName);
			values.put(RosterGroupColumns.OWNER, owner);

			context.getContentResolver().insert(
					RosterGroupColumns.CONTENT_URI, values);
			return 0;
		} else {
			return -2;
		}
	} catch (Exception e) {
		return -2;
	} finally {
		if (groupCursor != null) {
			groupCursor.close();
			groupCursor = null;
		}
	}
}
 
Example 5
Source File: PubSubManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Get the PubSub manager for the given connection and PubSub service. Use <code>null</code> as argument for
 * pubSubService to retrieve a PubSubManager for the users PEP service.
 *
 * @param connection the XMPP connection.
 * @param pubSubService the PubSub service, may be <code>null</code>.
 * @return a PubSub manager for the connection and service.
 */
// CHECKSTYLE:OFF:RegexpSingleline
public static PubSubManager getInstanceFor(XMPPConnection connection, BareJid pubSubService) {
// CHECKSTYLE:ON:RegexpSingleline
    if (pubSubService != null && connection.isAuthenticated() && connection.getUser().asBareJid().equals(pubSubService)) {
        // PEP service.
        pubSubService = null;
    }

    PubSubManager pubSubManager;
    Map<BareJid, PubSubManager> managers;
    synchronized (INSTANCES) {
        managers = INSTANCES.get(connection);
        if (managers == null) {
            managers = new HashMap<>();
            INSTANCES.put(connection, managers);
        }
    }
    synchronized (managers) {
        pubSubManager = managers.get(pubSubService);
        if (pubSubManager == null) {
            pubSubManager = new PubSubManager(connection, pubSubService);
            managers.put(pubSubService, pubSubManager);
        }
    }

    return pubSubManager;
}
 
Example 6
Source File: OmemoManagerSetupHelper.java    From Smack with Apache License 2.0 5 votes vote down vote up
public static OmemoManager prepareOmemoManager(XMPPConnection connection) throws Exception {
    final OmemoManager manager = OmemoManager.getInstanceFor(connection, OmemoManager.randomDeviceId());
    manager.setTrustCallback(new EphemeralTrustCallback());

    if (connection.isAuthenticated()) {
        manager.initialize();
    } else {
        throw new AssertionError("Connection must be authenticated.");
    }
    return manager;
}
 
Example 7
Source File: XmppService.java    From yiim_v2 with GNU General Public License v2.0 4 votes vote down vote up
public boolean isAuthenticated() {
	XMPPConnection connection = XmppConnectionUtils.getInstance()
			.getRawConnection();
	return isXmppServiceStarted() && connection.isAuthenticated();
}
 
Example 8
Source File: YiIMUtils.java    From yiim_v2 with GNU General Public License v2.0 4 votes vote down vote up
public static void updatePresenceType(Context context, String user) {
	String currentUser = UserInfo.getUserInfo(context).getUser();
	user = StringUtils.escapeUserResource(user);

	Cursor cursor = null;
	try {
		cursor = context.getContentResolver().query(
				RosterColumns.CONTENT_URI,
				new String[] { RosterColumns._ID },
				RosterColumns.USERID + "='" + user + "' and "
						+ RosterColumns.OWNER + "='" + currentUser + "'",
				null, null);
		if (cursor != null && cursor.getCount() > 0) {
			cursor.moveToFirst();
			XMPPConnection connection = XmppConnectionUtils.getInstance()
					.getConnection();
			if (connection != null && connection.isConnected()
					&& connection.isAuthenticated()) {
				RosterEntry rosterEntry = connection.getRoster().getEntry(
						user);
				if (rosterEntry != null) {
					do {
						ContentValues values = new ContentValues();
						values.put(RosterColumns.ROSTER_TYPE, rosterEntry
								.getType().toString());
						context.getContentResolver().update(
								ContentUris.withAppendedId(
										RosterColumns.CONTENT_URI,
										cursor.getLong(0)), values, null,
								null);
					} while (cursor.moveToNext());
				}
			}
		}
	} catch (Exception e) {

	} finally {
		if (cursor != null) {
			cursor.close();
			cursor = null;
		}
	}
}
 
Example 9
Source File: YiIMUtils.java    From yiim_v2 with GNU General Public License v2.0 4 votes vote down vote up
public static int deleteGroup(Context context, long groupId) {
	String owner = UserInfo.getUserInfo(context).getUser();

	Cursor groupCursor = null;
	Cursor entriesCursor = null;
	Cursor defaultGroupCursor = null;
	try {
		groupCursor = context.getContentResolver().query(
				ContentUris.withAppendedId(RosterGroupColumns.CONTENT_URI,
						groupId), new String[] { RosterGroupColumns.NAME },
				null, null, null);
		if (groupCursor == null || groupCursor.getCount() != 1) {
			return -1;
		}
		groupCursor.moveToFirst();
		String groupName = groupCursor.getString(0);
		if ("unfiled".equals(groupName)) {
			return -2;
		}

		defaultGroupCursor = context.getContentResolver().query(
				RosterGroupColumns.CONTENT_URI,
				new String[] { RosterGroupColumns._ID },
				RosterGroupColumns.NAME + "='unfiled' and "
						+ RosterGroupColumns.OWNER + "='" + owner + "'",
				null, null);
		if (defaultGroupCursor == null
				|| defaultGroupCursor.getCount() != 1) {
			return -1;
		}
		defaultGroupCursor.moveToFirst();
		int defaultGroupId = defaultGroupCursor.getInt(0);

		XMPPConnection connection = XmppConnectionUtils.getInstance()
				.getConnection();
		if (connection == null || !connection.isConnected()
				|| !connection.isAuthenticated()) {
			return -1;
		}

		RosterGroup rosterGroup = connection.getRoster()
				.getGroup(groupName);
		if (rosterGroup == null) {
			return -1;
		}

		Collection<RosterEntry> entries = rosterGroup.getEntries();
		if (entries != null && entries.size() > 0) {
			for (RosterEntry rosterEntry : entries) {
				rosterGroup.removeEntry(rosterEntry);
			}
		}

		entriesCursor = context.getContentResolver().query(
				RosterColumns.CONTENT_URI,
				new String[] { RosterColumns._ID },
				RosterColumns.GROUP_ID + "=" + groupId, null, null);
		List<Integer> mIntegers = new ArrayList<Integer>();
		if (entriesCursor != null && entriesCursor.getCount() > 0) {
			entriesCursor.moveToFirst();
			do {
				mIntegers.add(entriesCursor.getInt(0));
			} while (entriesCursor.moveToNext());
		}

		for (Integer integer : mIntegers) {
			ContentValues values = new ContentValues();
			values.put(RosterColumns.GROUP_ID, defaultGroupId);
			context.getContentResolver().update(
					ContentUris.withAppendedId(RosterColumns.CONTENT_URI,
							integer), values, null, null);
		}

		context.getContentResolver().delete(
				ContentUris.withAppendedId(RosterGroupColumns.CONTENT_URI,
						groupId), null, null);
		return 0;
	} catch (Exception e) {
		return -1;
	} finally {
		if (groupCursor != null) {
			groupCursor.close();
			groupCursor = null;
		}

		if (entriesCursor != null) {
			entriesCursor.close();
			entriesCursor = null;
		}

		if (defaultGroupCursor != null) {
			defaultGroupCursor.close();
			defaultGroupCursor = null;
		}
	}
}
 
Example 10
Source File: YiIMUtils.java    From yiim_v2 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 加入会议室
 * 
 * @param user
 *            昵称
 * @param password
 *            会议室密码
 * @param roomsName
 *            会议室名
 */
public static MultiUserChat joinMultiUserChat(Context context, String user,
		String roomJid, String password) throws Exception {
	XMPPConnection connection = XmppConnectionUtils.getInstance()
			.getRawConnection();
	if (connection == null || !connection.isConnected()
			|| !connection.isAuthenticated())
		throw new Exception("connection not ready");

	Cursor cursor = null;
	try {
		// 使用XMPPConnection创建一个MultiUserChat窗口
		MultiUserChat muc = new MultiUserChat(connection, roomJid);
		// 聊天室服务将会决定要接受的历史记录数量
		DiscussionHistory history = new DiscussionHistory();

		cursor = context.getContentResolver().query(
				MultiChatRoomColumns.CONTENT_URI,
				new String[] { MultiChatRoomColumns.LAST_MSG_TIME },
				MultiChatRoomColumns.ROOM_JID + "='" + roomJid + "' and "
						+ MultiChatRoomColumns.OWNER + "='"
						+ UserInfo.getUserInfo(context).getUser() + "'",
				null, null);
		if (cursor != null && cursor.getCount() == 1) {
			cursor.moveToFirst();
			history.setSince(new Date(cursor.getLong(0)));
		} else {
			history.setMaxStanzas(15);
		}
		// 用户加入聊天室
		muc.join(StringUtils.escapeUserHost(user), password, history,
				SmackConfiguration.getPacketReplyTimeout());
		return muc;
	} catch (Exception e) {
		throw e;
	} finally {
		if (cursor != null) {
			cursor.close();
			cursor = null;
		}
	}
}
 
Example 11
Source File: Workgroup.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new workgroup instance using the specified workgroup JID
 * (eg [email protected]) and XMPP connection. The connection must have
 * undergone a successful login before being used to construct an instance of
 * this class.
 *
 * @param workgroupJID the JID of the workgroup.
 * @param connection   an XMPP connection which must have already undergone a
 *                     successful login.
 */
public Workgroup(EntityBareJid workgroupJID, XMPPConnection connection) {
    // Login must have been done before passing in connection.
    if (!connection.isAuthenticated()) {
        throw new IllegalStateException("Must login to server before creating workgroup.");
    }

    this.workgroupJID = workgroupJID;
    this.connection = connection;
    inQueue = false;
    invitationListeners = new CopyOnWriteArraySet<>();
    queueListeners = new CopyOnWriteArraySet<>();

    // Register as a queue listener for internal usage by this instance.
    addQueueListener(new QueueListener() {
        @Override
        public void joinedQueue() {
            inQueue = true;
        }

        @Override
        public void departedQueue() {
            inQueue = false;
            queuePosition = -1;
            queueRemainingTime = -1;
        }

        @Override
        public void queuePositionUpdated(int currentPosition) {
            queuePosition = currentPosition;
        }

        @Override
        public void queueWaitTimeUpdated(int secondsRemaining) {
            queueRemainingTime = secondsRemaining;
        }
    });

    /**
     * Internal handling of an invitation.Recieving an invitation removes the user from the queue.
     */
    MultiUserChatManager.getInstanceFor(connection).addInvitationListener(
            new org.jivesoftware.smackx.muc.InvitationListener() {
                @Override
                public void invitationReceived(XMPPConnection conn, org.jivesoftware.smackx.muc.MultiUserChat room, EntityJid inviter,
                                               String reason, String password, Message message, MUCUser.Invite invitation) {
                    inQueue = false;
                    queuePosition = -1;
                    queueRemainingTime = -1;
                }
            });

    // Register a packet listener for all the messages sent to this client.
    StanzaFilter typeFilter = new StanzaTypeFilter(Message.class);

    connection.addAsyncStanzaListener(new StanzaListener() {
        @Override
        public void processStanza(Stanza packet) {
            handlePacket(packet);
        }
    }, typeFilter);
}