org.jxmpp.jid.parts.Resourcepart Java Examples

The following examples show how to use org.jxmpp.jid.parts.Resourcepart. 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: BookmarkManager.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #2
Source File: ChatContainer.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * 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 );
            }
        }
    } );
}
 
Example #3
Source File: Roster.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #4
Source File: Roster.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #5
Source File: Jid.java    From Conversations with GNU General Public License v3.0 6 votes vote down vote up
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);
    }
}
 
Example #6
Source File: BroadcastPlugin.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
    * 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("serveralert@" + 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);
   }
 
Example #7
Source File: MultiUserChatIntegrationTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #8
Source File: Jid.java    From Pix-Art-Messenger with GNU General Public License v3.0 6 votes vote down vote up
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);
    }
}
 
Example #9
Source File: Jid.java    From Pix-Art-Messenger with GNU General Public License v3.0 6 votes vote down vote up
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);
    }
}
 
Example #10
Source File: GroupChatRoom.java    From Spark with Apache License 2.0 6 votes vote down vote up
@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");
        }
    }
}
 
Example #11
Source File: ModularXmppClientToServerConnection.java    From Smack with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #12
Source File: Jid.java    From Conversations with GNU General Public License v3.0 5 votes vote down vote up
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);
    }
}
 
Example #13
Source File: Jid.java    From Pix-Art-Messenger with GNU General Public License v3.0 5 votes vote down vote up
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);
    }
}
 
Example #14
Source File: ConferenceUtils.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #15
Source File: GroupChatParticipantList.java    From Spark with Apache License 2.0 5 votes vote down vote up
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);
}
   }
 
Example #16
Source File: ChatRoomMemberJabberImpl.java    From jitsi with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #17
Source File: ChatContainer.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example #18
Source File: MultiUserChat.java    From Smack with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #19
Source File: MultiUserChat.java    From Smack with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #20
Source File: MultiUserChatIntegrationTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #21
Source File: UserManager.java    From Spark with Apache License 2.0 5 votes vote down vote up
public boolean hasVoice(GroupChatRoom groupChatRoom, Resourcepart nickname) {
    Occupant occupant = getOccupant(groupChatRoom, nickname);
    if (occupant != null) {
        if ( MUCRole.visitor == occupant.getRole()) {
            return false;
        }
    }
    return true;
}
 
Example #22
Source File: MultiUserChat.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #23
Source File: ModularXmppClientToServerConnection.java    From Smack with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #24
Source File: ChatManager.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #25
Source File: GroupChatParticipantList.java    From Spark with Apache License 2.0 5 votes vote down vote up
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);
	}
}
 
Example #26
Source File: AgentRoster.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a listener to this roster. The listener will be fired anytime one or more
 * changes to the roster are pushed from the server.
 *
 * @param listener an agent roster listener.
 */
public void addListener(AgentRosterListener listener) {
    synchronized (listeners) {
        if (!listeners.contains(listener)) {
            listeners.add(listener);

            // Fire events for the existing entries and presences in the roster
            for (EntityBareJid jid : getAgents()) {
                // Check again in case the agent is no longer in the roster (highly unlikely
                // but possible)
                if (entries.contains(jid)) {
                    // Fire the agent added event
                    listener.agentAdded(jid);
                    Jid j;
                    try {
                        j = JidCreate.from(jid);
                    }
                    catch (XmppStringprepException e) {
                        throw new IllegalStateException(e);
                    }
                    Map<Resourcepart, Presence> userPresences = presenceMap.get(j);
                    if (userPresences != null) {
                        Iterator<Presence> presences = userPresences.values().iterator();
                        while (presences.hasNext()) {
                            // Fire the presence changed event
                            listener.presenceChanged(presences.next());
                        }
                    }
                }
            }
        }
    }
}
 
Example #27
Source File: GroupChatParticipantList.java    From Spark with Apache License 2.0 5 votes vote down vote up
protected void revokeMember(Resourcepart nickname) {
try {
    Occupant o = userManager.getOccupant(groupChatRoom, nickname);
       BareJid bareJid = o.getJid().asBareJid();
    chat.revokeMembership(Collections.singleton(bareJid));
} catch (XMPPException | SmackException | InterruptedException e) {
    groupChatRoom.getTranscriptWindow().insertNotificationMessage(
	    "No can do " + e.getMessage(), ChatManager.ERROR_COLOR);
}
   }
 
Example #28
Source File: MultiUserChatIntegrationTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
@SmackIntegrationTest
public void mucTest() throws Exception {
    EntityBareJid mucAddress = JidCreate.entityBareFrom(Localpart.from("smack-inttest-" + randomString), mucService.getDomain());

    MultiUserChat mucAsSeenByOne = mucManagerOne.getMultiUserChat(mucAddress);
    MultiUserChat mucAsSeenByTwo = mucManagerTwo.getMultiUserChat(mucAddress);

    final String mucMessage = "Smack Integration Test MUC Test Message " + randomString;
    final ResultSyncPoint<String, Exception> resultSyncPoint = new ResultSyncPoint<>();

    mucAsSeenByTwo.addMessageListener(new MessageListener() {
        @Override
        public void processMessage(Message message) {
            String body = message.getBody();
            if (mucMessage.equals(body)) {
                resultSyncPoint.signal(body);
            }
        }
    });

    MucCreateConfigFormHandle handle = mucAsSeenByOne.createOrJoin(Resourcepart.from("one-" + randomString));
    if (handle != null) {
        handle.makeInstant();
    }
    mucAsSeenByTwo.join(Resourcepart.from("two-" + randomString));

    mucAsSeenByOne.sendMessage(mucMessage);
    resultSyncPoint.waitForResult(timeout);

    mucAsSeenByOne.leave();
    mucAsSeenByTwo.leave();
}
 
Example #29
Source File: Roster.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * 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 Map<Resourcepart, Presence> getPresencesInternal(BareJid entity) {
    Map<Resourcepart, Presence> entityPresences = presenceMap.get(entity);
    if (entityPresences == null) {
        entityPresences = nonRosterPresenceMap.lookup(entity);
    }
    return entityPresences;
}
 
Example #30
Source File: GroupChatParticipantList.java    From Spark with Apache License 2.0 5 votes vote down vote up
protected void grantModerator(Resourcepart nickname) {
try {
    chat.grantModerator(Collections.singleton(nickname));
} catch (XMPPException | SmackException | InterruptedException e) {
    groupChatRoom.getTranscriptWindow().insertNotificationMessage(
	    "No can do " + e.getMessage(), ChatManager.ERROR_COLOR);
}
   }