Java源码示例:org.jxmpp.jid.parts.Resourcepart

示例1
static Jid of(CharSequence local, CharSequence domain, CharSequence resource) {
    if (local == null) {
        if (resource == null) {
            return ofDomain(domain);
        } else {
            return ofDomainAndResource(domain, resource);
        }
    }
    if (resource == null) {
        return ofLocalAndDomain(local, domain);
    }
    try {
        return new WrappedJid(JidCreate.entityFullFrom(
                Localpart.fromUnescaped(local.toString()),
                Domainpart.from(domain.toString()),
                Resourcepart.from(resource.toString())
        ));
    } catch (XmppStringprepException e) {
        throw new IllegalArgumentException(e);
    }
}
 
示例2
static Jid ofEscaped(CharSequence local, CharSequence domain, CharSequence resource) {
    try {
        if (resource == null) {
            return new WrappedJid(
                    JidCreate.bareFrom(
                            Localpart.from(local.toString()),
                            Domainpart.from(domain.toString())
                    )
            );
        }
        return new WrappedJid(JidCreate.entityFullFrom(
                Localpart.from(local.toString()),
                Domainpart.from(domain.toString()),
                Resourcepart.from(resource.toString())
        ));
    } catch (XmppStringprepException e) {
        throw new IllegalArgumentException(e);
    }
}
 
示例3
@SmackIntegrationTest
public void mucJoinLeaveTest() throws XmppStringprepException, NotAMucServiceException, NoResponseException,
        XMPPErrorException, NotConnectedException, InterruptedException, MucNotJoinedException {
    EntityBareJid mucAddress = JidCreate.entityBareFrom(Localpart.from("smack-inttest-join-leave-" + randomString),
            mucService.getDomain());

    MultiUserChat muc = mucManagerOne.getMultiUserChat(mucAddress);

    muc.join(Resourcepart.from("nick-one"));

    Presence reflectedLeavePresence = muc.leave();

    MUCUser mucUser = MUCUser.from(reflectedLeavePresence);
    assertNotNull(mucUser);

    assertTrue(mucUser.getStatus().contains(MUCUser.Status.PRESENCE_TO_SELF_110));
}
 
示例4
static Jid of(CharSequence local, CharSequence domain, CharSequence resource) {
    if (local == null) {
        if (resource == null) {
            return ofDomain(domain);
        } else {
            return ofDomainAndResource(domain, resource);
        }
    }
    if (resource == null) {
        return ofLocalAndDomain(local, domain);
    }
    try {
        return new WrappedJid(JidCreate.entityFullFrom(
                Localpart.fromUnescaped(local.toString()),
                Domainpart.from(domain.toString()),
                Resourcepart.from(resource.toString())
        ));
    } catch (XmppStringprepException e) {
        throw new IllegalArgumentException(e);
    }
}
 
示例5
/**
    * Displays the Serverbroadcast like all other messages
    * in its on chatcontainer with transcript history
    * @param message
    * @param from
    */
   private void broadcastInChat(Message message)
   {
String from = message.getFrom() != null ? message.getFrom().toString() : "";
ChatManager chatManager = SparkManager.getChatManager();
       ChatContainer container = chatManager.getChatContainer();

       ChatRoomImpl chatRoom;
       try {
           chatRoom = (ChatRoomImpl)container.getChatRoom(from);
       }
       catch (ChatRoomNotFoundException e) {
          String windowtitle = message.getSubject()!=null ? message.getSubject() : Res.getString("administrator");
          EntityBareJid jid = JidCreate.entityBareFromOrThrowUnchecked("[email protected]" + from);
          Resourcepart resourcepart = Resourcepart.fromOrThrowUnchecked(Res.getString("broadcast"));
          chatRoom = new ChatRoomImpl(jid, resourcepart, windowtitle);
          chatRoom.getBottomPanel().setVisible(false);
          chatRoom.hideToolbar();
          SparkManager.getChatManager().getChatContainer().addChatRoom(chatRoom);
       }


       chatRoom.getTranscriptWindow().insertNotificationMessage(message.getBody(), ChatManager.NOTIFICATION_COLOR);
       broadcastRooms.add(chatRoom);
   }
 
示例6
@Override
public StateTransitionResult.AttemptResult transitionInto(WalkStateGraphContext walkStateGraphContext)
                throws IOException, SmackException, InterruptedException, XMPPException {
    // Calling bindResourceAndEstablishSession() below requires the lastFeaturesReceived sync point to be signaled.
    // Since we entered this state, the FSM has decided that the last features have been received, hence signal
    // the sync point.
    lastFeaturesReceived = true;
    notifyWaitingThreads();

    LoginContext loginContext = walkStateGraphContext.getLoginContext();
    Resourcepart resource = bindResourceAndEstablishSession(loginContext.resource);

    // TODO: This should be a field in the Stream Management (SM) module. Here should be hook which the SM
    // module can use to set the field instead.
    streamResumed = false;

    return new ResourceBoundResult(resource, loginContext.resource);
}
 
示例7
@Override
protected void sendChatState(ChatState state) throws SmackException.NotConnectedException, InterruptedException
{
    if (!chatStatEnabled || !SparkManager.getConnection().isConnected() )
    {
        return;
    }

    // XEP-0085: SHOULD NOT send 'gone' in a MUC.
    if ( state == ChatState.gone )
    {
        return;
    }

    for ( final EntityFullJid occupant : chat.getOccupants() )
    {
        final Resourcepart occupantNickname = occupant.getResourcepart();
        final Resourcepart myNickname = chat.getNickname();
        if (occupantNickname != null && !occupantNickname.equals(myNickname))
        {
            SparkManager.getMessageEventManager().sendComposingNotification(occupant, "djn");
        }
    }
}
 
示例8
/**
 * Retrieve the user presences (a map from resource to {@link Presence}) for a given XMPP entity represented by their bare JID.
 *
 * @param entity the entity
 * @return the user presences
 */
private synchronized Map<Resourcepart, Presence> getOrCreatePresencesInternal(BareJid entity) {
    Map<Resourcepart, Presence> entityPresences = getPresencesInternal(entity);
    if (entityPresences == null) {
        if (contains(entity)) {
            entityPresences = new ConcurrentHashMap<>();
            presenceMap.put(entity, entityPresences);
        }
        else {
            LruCache<Resourcepart, Presence> nonRosterEntityPresences = new LruCache<>(32);
            nonRosterPresenceMap.put(entity, nonRosterEntityPresences);
            entityPresences = nonRosterEntityPresences;
        }
    }
    return entityPresences;
}
 
示例9
/**
 * Returns a List of Presence objects for all of a user's current presences if no presence information is available,
 * such as when you are not subscribed to the user's presence updates.
 *
 * @param bareJid an XMPP ID, e.g. [email protected]
 * @return a List of Presence objects for all the user's current presences, or an unavailable presence if no
 *         presence information is available.
 */
public List<Presence> getAllPresences(BareJid bareJid) {
    Map<Resourcepart, Presence> userPresences = getPresencesInternal(bareJid);
    List<Presence> res;
    if (userPresences == null) {
        // Create an unavailable presence if none was found
        Presence unavailable = synthesizeUnvailablePresence(bareJid);
        res = new ArrayList<>(Arrays.asList(unavailable));
    } else {
        res = new ArrayList<>(userPresences.values().size());
        for (Presence presence : userPresences.values()) {
            res.add(presence);
        }
    }
    return res;
}
 
示例10
/**
 * Notifies users that a user has joined a <code>ChatRoom</code>.
 *
 * @param room   - the <code>ChatRoom</code> that a user has joined.
 * @param userid - the userid of the person.
 */
protected void fireUserHasJoined( final ChatRoom room, final Resourcepart userid )
{
    SwingUtilities.invokeLater( () ->
    {
        for ( final ChatRoomListener listener : chatRoomListeners )
        {
            try
            {
                listener.userHasJoined( room, userid.toString() );
            }
            catch ( Exception e )
            {
                Log.error( "A ChatRoomListener (" + listener + ") threw an exception while processing a 'user joined' event for user '" + userid + "' in room: " + room, e );
            }
        }
    } );
}
 
示例11
/**
 * Adds or updates a conference in the bookmarks.
 *
 * @param name the name of the conference
 * @param jid the jid of the conference
 * @param isAutoJoin whether or not to join this conference automatically on login
 * @param nickname the nickname to use for the user when joining the conference
 * @param password the password to use for the user when joining the conference
 * @throws XMPPErrorException thrown when there is an issue retrieving the current bookmarks from
 * the server.
 * @throws NoResponseException if there was no response from the server.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public void addBookmarkedConference(String name, EntityBareJid jid, boolean isAutoJoin,
        Resourcepart nickname, String password) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    retrieveBookmarks();
    BookmarkedConference bookmark
            = new BookmarkedConference(name, jid, isAutoJoin, nickname, password);
    List<BookmarkedConference> conferences = bookmarks.getBookmarkedConferences();
    if (conferences.contains(bookmark)) {
        BookmarkedConference oldConference = conferences.get(conferences.indexOf(bookmark));
        if (oldConference.isShared()) {
            throw new IllegalArgumentException("Cannot modify shared bookmark");
        }
        oldConference.setAutoJoin(isAutoJoin);
        oldConference.setName(name);
        oldConference.setNickname(nickname);
        oldConference.setPassword(password);
    }
    else {
        bookmarks.addBookmarkedConference(bookmark);
    }
    privateDataManager.setPrivateData(bookmarks);
}
 
示例12
@SmackIntegrationTest
public void mucDestroyTest() throws TimeoutException, Exception {

    EntityBareJid mucAddress = JidCreate.entityBareFrom(Localpart.from("smack-inttest-join-leave-" + randomString),
                                                        mucService.getDomain());

    MultiUserChat muc = mucManagerOne.getMultiUserChat(mucAddress);
    muc.join(Resourcepart.from("nick-one"));

    final SimpleResultSyncPoint mucDestroyed = new SimpleResultSyncPoint();

    @SuppressWarnings("deprecation")
    DefaultUserStatusListener userStatusListener = new DefaultUserStatusListener() {
        @Override
        public void roomDestroyed(MultiUserChat alternateMUC, String reason) {
            mucDestroyed.signal();
        }
    };

    muc.addUserStatusListener(userStatusListener);

    assertTrue(mucManagerOne.getJoinedRooms().size() == 1);
    assertTrue(muc.getOccupantsCount() == 1);
    assertTrue(muc.getNickname() != null);

    try {
        muc.destroy("Dummy reason", null);
        mucDestroyed.waitForResult(timeout);
    } finally {
        muc.removeUserStatusListener(userStatusListener);
    }

    assertTrue(mucManagerOne.getJoinedRooms().size() == 0);
    assertTrue(muc.getOccupantsCount() == 0);
    assertTrue(muc.getNickname() == null);
}
 
示例13
public static void joinAllRooms() throws XmppStringprepException, XMPPErrorException, NoResponseException,
		NotConnectedException, InterruptedException, NotAMucServiceException {
	// TODO 启动MUC房间订阅,订阅全部房间
	// 在sqlite库中查询MUC群组
	List<Room> dbMucRooms = Launcher.roomService.findByType("m");
	for (Room roomDb : dbMucRooms) {
		if (roomDb.getRoomId() != null && !roomDb.getRoomId().isEmpty() && roomDb.getRoomId().contains("@")) {
			MultiUserChat room = MultiUserChatManager.getInstanceFor(Launcher.connection)
					.getMultiUserChat(JidCreate.entityBareFrom(roomDb.getRoomId()));
			// 将room加入堆缓存,以便重复利用
			// roomCacheService.put(roomDb.getRoomId(),room);
			// 以“username-真实姓名”为nickname进入群
			// room.join(Resourcepart.from(UserCache.CurrentUserName + "-" +
			// UserCache.CurrentUserRealName));
			MucEnterConfiguration.Builder builder = room.getEnterConfigurationBuilder(
					Resourcepart.from(UserCache.CurrentUserName + "-" + UserCache.CurrentUserRealName));
			// 只获取最后10条历史记录
			// builder.requestMaxStanzasHistory(10);
			// 只获取该房间最后一条消息的时间戳到当前时间戳的离线
			int historySince = MucChatService.getHistoryOffsize(roomDb.getLastChatAt());
			builder.requestHistorySince(historySince);
			// 只获取2018-5-1以来的历史记录
			// builder.requestHistorySince(new Date(2018,5,1));
			MucEnterConfiguration mucEnterConfiguration = builder.build();
			room.join(mucEnterConfiguration);

		}
	}
}
 
示例14
public void login(String userName, String password) throws Exception {
    try {
        mXMPPConnection.connect();
    } catch (SmackException.AlreadyConnectedException ace) {
        Log.w(XMPP_TAG, "Client Already Connected");
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    Preferences preferences = Preferences.getInstance();
    try {
        String resourceString = Settings.Secure.getString(MangostaApplication.getInstance().getContentResolver(), Settings.Secure.ANDROID_ID);
        Resourcepart resourcepart = Resourcepart.from(resourceString);

        // login
        if (connectionDoneOnce && !preferences.getXmppOauthAccessToken().isEmpty() && tokenSetMinutesAgo(30)) {
            mXMPPConnection.login(preferences.getXmppOauthAccessToken(), resourcepart);
        } else {
            mXMPPConnection.login(userName, password, resourcepart);
        }

        preferences.setUserXMPPJid(XMPPUtils.fromUserNameToJID(userName));
        preferences.setUserXMPPPassword(password);

        sendPresenceAvailable();
        mConnectionPublisher.onNext(new ChatConnection(ChatConnection.ChatConnectionStatus.Authenticated));
    } catch (SmackException.AlreadyLoggedInException ale) {
        sendPresenceAvailable();
        mConnectionPublisher.onNext(new ChatConnection(ChatConnection.ChatConnectionStatus.Authenticated));
    }

}
 
示例15
static Jid ofDomainAndResource(CharSequence domain, CharSequence resource) {
    try {
        return new WrappedJid(
                JidCreate.domainFullFrom(
                        Domainpart.from(domain.toString()),
                        Resourcepart.from(resource.toString())
                ));
    } catch (XmppStringprepException e) {
        throw new IllegalArgumentException(e);
    }
}
 
示例16
/**
 * Create or join a MUC if it is necessary, i.e. if not the MUC is not already joined.
 *
 * @param nickname the required nickname to use.
 * @param password the optional password required to join
 * @return A {@link MucCreateConfigFormHandle} if the room was created while joining, or {@code null} if the room was just joined.
 * @throws NoResponseException if there was no response from the remote entity.
 * @throws XMPPErrorException if there was an XMPP error returned.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 * @throws NotAMucServiceException if the entity is not a MUC serivce.
 */
public MucCreateConfigFormHandle createOrJoinIfNecessary(Resourcepart nickname, String password) throws NoResponseException,
                XMPPErrorException, NotConnectedException, InterruptedException, NotAMucServiceException {
    if (isJoined()) {
        return null;
    }
    MucEnterConfiguration mucEnterConfiguration = getEnterConfigurationBuilder(nickname).withPassword(
                    password).build();
    try {
        return createOrJoin(mucEnterConfiguration);
    }
    catch (MucAlreadyJoinedException e) {
        return null;
    }
}
 
示例17
protected void grantOwner(Resourcepart nickname) {
try {
    Occupant o = userManager.getOccupant(groupChatRoom, nickname);
       BareJid bareJid = o.getJid().asBareJid();
    chat.grantOwnership(Collections.singleton(bareJid));
} catch (XMPPException | SmackException | InterruptedException e) {
    groupChatRoom.getTranscriptWindow().insertNotificationMessage(
	    "No can do " + e.getMessage(), ChatManager.ERROR_COLOR);
}
   }
 
示例18
/**
 * Get a {@link FullJid} constructed from a {@link BareJid} and a {@link Resourcepart}.
 *
 * @param bareJid a entity bare JID.
 * @param resource a resourcepart.
 * @return a full JID.
 */
public static FullJid fullFrom(BareJid bareJid, Resourcepart resource) {
	if (bareJid.isEntityBareJid()) {
		EntityBareJid entityBareJid = (EntityBareJid) bareJid;
		return new LocalDomainAndResourcepartJid(entityBareJid, resource);
	} else {
		DomainBareJid domainBareJid = (DomainBareJid) bareJid;
		return new DomainAndResourcepartJid(domainBareJid, resource);
	}
}
 
示例19
private void changeRole(Resourcepart nickname, MUCRole role, String reason) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    MUCAdmin iq = new MUCAdmin();
    iq.setTo(room);
    iq.setType(IQ.Type.set);
    // Set the new role.
    MUCItem item = new MUCItem(role, nickname, reason);
    iq.addItem(item);

    connection.createStanzaCollectorAndSend(iq).nextResultOrThrow();
}
 
示例20
private void changeRole(Collection<Resourcepart> nicknames, MUCRole role) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException  {
    MUCAdmin iq = new MUCAdmin();
    iq.setTo(room);
    iq.setType(IQ.Type.set);
    for (Resourcepart nickname : nicknames) {
        // Set the new role.
        MUCItem item = new MUCItem(role, nickname);
        iq.addItem(item);
    }

    connection.createStanzaCollectorAndSend(iq).nextResultOrThrow();
}
 
示例21
/**
 * Handles the presence of a one to one chat room.
 *
 * @param p the presence to handle.
 */
private void handleRoomPresence(final Presence p) {
    final EntityBareJid roomname = p.getFrom().asEntityBareJidIfPossible();
    ChatRoom chatRoom;
    try {
        chatRoom = getChatRoom(roomname);
    }
    catch (ChatRoomNotFoundException e1) {
        Log.debug("Could not locate chat room " + roomname);
        return;
    }

    final Resourcepart userid = p.getFrom().getResourceOrNull();
    if (p.getType() == Presence.Type.unavailable) {
        fireUserHasLeft(chatRoom, userid);
    }
    else if (p.getType() == Presence.Type.available) {
        fireUserHasJoined(chatRoom, userid);
    }

    // Change tab icon
    if (chatRoom instanceof ChatRoomImpl) {
        // Notify state change.
        int tabLoc = indexOfComponent(chatRoom);
        if (tabLoc != -1) {
            SparkManager.getChatManager().notifySparkTabHandlers(chatRoom);
        }
    }
}
 
示例22
/**
 * Update the name of this parcipant
 * @param newNick the newNick of the participant
 */
protected void setName(Resourcepart newNick)
{
    if ((newNick == null) || !(newNick.length() > 0))
        throw new IllegalArgumentException(
            "a room member nickname could not be null");
    nickName = newNick;
}
 
示例23
protected void revokeAdmin(Resourcepart nickname) {
try {
    Occupant o = userManager.getOccupant(groupChatRoom, nickname);
       BareJid bareJid = o.getJid().asBareJid();
    chat.revokeAdmin(Collections.singleton(bareJid));
} catch (XMPPException | SmackException | InterruptedException e) {
    groupChatRoom.getTranscriptWindow().insertNotificationMessage(
	    "No can do " + e.getMessage(), ChatManager.ERROR_COLOR);
}
   }
 
示例24
/**
 * Joins a chat room without using the UI.
 *
 * @param groupChat the <code>MultiUserChat</code>
 * @param nickname  the nickname of the user.
 * @param password  the password to join the room with.
 * @return a List of errors, if any.
 */
public static List<String> joinRoom(MultiUserChat groupChat, Resourcepart nickname, String password) {
    final List<String> errors = new ArrayList<>();
    if ( !groupChat.isJoined() )
    {
        try
        {
            if ( ModelUtil.hasLength( password ) )
            {
                groupChat.join( nickname, password );
            }
            else
            {
                groupChat.join( nickname );
            }
            changePresenceToAvailableIfInvisible();
        }
        catch ( XMPPException | SmackException | InterruptedException ex )
        {
            StanzaError error = null;
            if ( ex instanceof XMPPException.XMPPErrorException )
            {
                error = ( (XMPPException.XMPPErrorException) ex ).getStanzaError();
            }

            final String errorText = ConferenceUtils.getReason( error );
            errors.add( errorText );
        }
    }

    return errors;
}
 
示例25
static Jid ofDomainAndResource(CharSequence domain, CharSequence resource) {
    try {
        return new WrappedJid(
                JidCreate.domainFullFrom(
                        Domainpart.from(domain.toString()),
                        Resourcepart.from(resource.toString())
                ));
    } catch (XmppStringprepException e) {
        throw new IllegalArgumentException(e);
    }
}
 
示例26
public boolean hasVoice(GroupChatRoom groupChatRoom, Resourcepart nickname) {
    Occupant occupant = getOccupant(groupChatRoom, nickname);
    if (occupant != null) {
        if ( MUCRole.visitor == occupant.getRole()) {
            return false;
        }
    }
    return true;
}
 
示例27
/**
 * Returns the nickname that was used to join the room, or <code>null</code> if not
 * currently joined.
 *
 * @return the nickname currently being used.
 */
public Resourcepart getNickname() {
    final EntityFullJid myRoomJid = this.myRoomJid;
    if (myRoomJid == null) {
        return null;
    }
    return myRoomJid.getResourcepart();
}
 
示例28
@Override
protected void loginInternal(String username, String password, Resourcepart resource)
                throws XMPPException, SmackException, IOException, InterruptedException {
    WalkStateGraphContext walkStateGraphContext = buildNewWalkTo(
                    AuthenticatedAndResourceBoundStateDescriptor.class).withLoginContext(username, password,
                                    resource).build();
    walkStateGraph(walkStateGraphContext);
}
 
示例29
/**
 * Creates and/or opens a chat room with the specified user.
 *
 * @param userJID  the jid of the user to chat with.
 * @param nicknameCs the nickname to use for the user.
 * @param title    the title to use for the room.
 * @return the newly created <code>ChatRoom</code>.
 */
public ChatRoom createChatRoom(EntityJid userJID, CharSequence nicknameCs, CharSequence title) {
    Resourcepart nickname = Resourcepart.fromOrThrowUnchecked(nicknameCs);
    ChatRoom chatRoom;
    try {
        chatRoom = getChatContainer().getChatRoom(userJID);
    }
    catch (ChatRoomNotFoundException e) {
        chatRoom = UIComponentRegistry.createChatRoom(userJID, nickname, title);
        getChatContainer().addChatRoom(chatRoom);
    }

    return chatRoom;
}
 
示例30
protected void revokeVoice(Resourcepart nickname) {
	try {
		chat.revokeVoice(Collections.singleton(nickname));
	} catch (XMPPException | SmackException  | InterruptedException e) {
	    groupChatRoom.getTranscriptWindow().
	    insertNotificationMessage("No can do "+e.getMessage(), ChatManager.ERROR_COLOR);
	}
}