org.jxmpp.jid.EntityFullJid Java Examples

The following examples show how to use org.jxmpp.jid.EntityFullJid. 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: XmppConnection.java    From Zom-Android-XMPP with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void joined(EntityFullJid entityFullJid) {
     XmppAddress xa = new XmppAddress(entityFullJid.toString());
     ChatGroup chatGroup = mChatGroupManager.getChatGroup(xa);
     MultiUserChat muc = mChatGroupManager.getMultiUserChat(entityFullJid.asBareJid().toString());

     Occupant occupant = muc.getOccupant(entityFullJid);
     Jid jidSource = (occupant != null) ? occupant.getJid() : null;
     if (jidSource != null)
     xa = new XmppAddress(jidSource.toString());
     else
     xa = new XmppAddress(entityFullJid.toString());

     Contact mucContact = new Contact(xa, xa.getUser(), Imps.Contacts.TYPE_NORMAL);
     chatGroup.notifyMemberJoined(entityFullJid.toString(),mucContact);
    if (occupant != null) {
        chatGroup.notifyMemberRoleUpdate(mucContact, occupant.getRole().name(), occupant.getAffiliation().toString());
    }
}
 
Example #2
Source File: Socks5BytestreamManager.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the stream host information of the local SOCKS5 proxy containing the IP address and
 * the port or null if local SOCKS5 proxy is not running.
 *
 * @return the stream host information of the local SOCKS5 proxy or null if local SOCKS5 proxy
 *         is not running
 */
public List<StreamHost> getLocalStreamHost() {
    List<StreamHost> streamHosts = new ArrayList<>();

    XMPPConnection connection = connection();
    EntityFullJid myJid = connection.getUser();

    for (Socks5Proxy socks5Server : Socks5Proxy.getRunningProxies()) {
        List<InetAddress> addresses = socks5Server.getLocalAddresses();
        if (addresses.isEmpty()) {
            continue;
        }

        final int port = socks5Server.getPort();
        for (InetAddress address : addresses) {
            // Prevent loopback addresses from appearing as streamhost
            if (address.isLoopbackAddress()) {
                continue;
            }
            streamHosts.add(new StreamHost(myJid, address, port));
        }
    }

    return streamHosts;
}
 
Example #3
Source File: JidCreate.java    From jxmpp with Apache License 2.0 6 votes vote down vote up
/**
 * Get a {@link EntityFullJid} representing the given String.
 *
 * @param jid the JID's String.
 * @return a full JID representing the input String.
 * @throws XmppStringprepException if an error occurs.
 */
public static EntityFullJid entityFullFrom(String jid) throws XmppStringprepException {
	EntityFullJid fullJid = ENTITY_FULLJID_CACHE.lookup(jid);
	if (fullJid != null) {
		return fullJid;
	}

	String localpart = XmppStringUtils.parseLocalpart(jid);
	String domainpart = XmppStringUtils.parseDomain(jid);
	String resource = XmppStringUtils.parseResource(jid);
	try {
		fullJid = entityFullFrom(localpart, domainpart, resource);
	} catch (XmppStringprepException e) {
		throw new XmppStringprepException(jid, e);
	}
	ENTITY_FULLJID_CACHE.put(jid, fullJid);
	return fullJid;
}
 
Example #4
Source File: MucManager.java    From Yahala-Messenger with MIT License 6 votes vote down vote up
public List<String> getRoomParticipants(String threadId) {
    List<EntityFullJid> usersJids = null;
    List<String> usersIds = new ArrayList<>();
    try {
        //RoomInfo roomInfo = manager.getRoomInfo(JidCreate.entityBareFrom(threadId));
        MultiUserChat multiUserChat = manager.getMultiUserChat(JidCreate.entityBareFrom(threadId));
        usersJids = multiUserChat.getOccupants();

        for (EntityFullJid entityFullJid : usersJids) {
            usersIds.add(entityFullJid.toString());
        }
    } catch (XmppStringprepException e) {
        e.printStackTrace();
    }

    return usersIds;
}
 
Example #5
Source File: Occupant.java    From Smack with Apache License 2.0 6 votes vote down vote up
Occupant(Presence presence) {
    MUCUser mucUser = (MUCUser) presence.getExtensionElement("x",
            "http://jabber.org/protocol/muc#user");
    MUCItem item = mucUser.getItem();
    this.jid = item.getJid();
    this.affiliation = item.getAffiliation();
    this.role = item.getRole();
    // Get the nickname from the FROM attribute of the presence
    EntityFullJid from = presence.getFrom().asEntityFullJidIfPossible();
    if (from == null) {
        LOGGER.warning("Occupant presence without resource: " + presence.getFrom());
        this.nick = null;
    } else {
        this.nick = from.getResourcepart();
    }
}
 
Example #6
Source File: JidCreateTest.java    From jxmpp with Apache License 2.0 5 votes vote down vote up
@Test
public void entityFullFromUnsecapedComplexTest() throws XmppStringprepException {
	EntityFullJid entityFullJid = JidCreate.entityFullFromUnescaped("foo@[email protected]/bar@baz");

	Domainpart domainpart = entityFullJid.getDomain();
	assertEquals(Domainpart.from("[email protected]"), domainpart);

	Localpart localpart = entityFullJid.getLocalpart();
	assertEquals(Localpart.from("foo"), localpart);

	Resourcepart resourcepart = entityFullJid.getResourcepart();
	assertEquals(Resourcepart.from("bar@baz"), resourcepart);
}
 
Example #7
Source File: CarbonManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
private void addCarbonsListener(XMPPConnection connection) {
    EntityFullJid localAddress = connection.getUser();
    if (localAddress == null) {
        // We where not connected yet and thus we don't know our XMPP address at the moment, which we need to match incoming
        // carbons securely. Abort here. The ConnectionListener above will eventually setup the carbons listener.
        return;
    }

    // XEP-0280 ยง 11. Security Considerations "Any forwarded copies received by a Carbons-enabled client MUST be
    // from that user's bare JID; any copies that do not meet this requirement MUST be ignored." Otherwise, if
    // those copies do not get ignored, malicious users may be able to impersonate other users. That is why the
    // 'from' matcher is important here.
    connection.addSyncStanzaListener(carbonsListener, new AndFilter(CARBON_EXTENSION_FILTER,
                    FromMatchesFilter.createBare(localAddress)));
}
 
Example #8
Source File: MamManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * The the XMPP address of this MAM archive. Note that this method may return {@code null} if this MamManager
 * handles the local entity's archive and if the connection has never been authenticated at least once.
 *
 * @return the XMPP address of this MAM archive or {@code null}.
 * @since 4.3.0
 */
public Jid getArchiveAddress() {
    if (archiveAddress == null) {
        EntityFullJid localJid = connection().getUser();
        if (localJid == null) {
            return null;
        }
        return localJid.asBareJid();
    }
    return archiveAddress;
}
 
Example #9
Source File: GroupChatParticipantList.java    From Spark with Apache License 2.0 5 votes vote down vote up
protected void banUser(Resourcepart displayName) {
	try {
	    EntityFullJid entityFullJid = userMap.get(displayName);
		Occupant occupant = chat.getOccupant(entityFullJid);
		if (occupant != null) {
			EntityBareJid bareJID = occupant.getJid().asEntityBareJidOrThrow();
			chat.banUser(bareJID, Res
					.getString("message.you.have.been.banned"));
		}
	} catch (XMPPException | SmackException | InterruptedException | IllegalStateException e) {
	    groupChatRoom.getTranscriptWindow().
	    insertNotificationMessage("No can do "+e.getMessage(), ChatManager.ERROR_COLOR);
	}
}
 
Example #10
Source File: FastpathPlugin.java    From Spark with Apache License 2.0 5 votes vote down vote up
private void leaveWorkgroup() {
    workgroupLabel.setText(FpRes.getString("workgroup") + ":");
    logoutButton.setVisible(false);
    joinButton.setVisible(true);
    comboBox.setVisible(true);

    comboBox.removeAllItems();
    // Log into workgroup
    DomainBareJid workgroupService = JidCreate.domainBareFromOrThrowUnchecked("workgroup." + SparkManager.getSessionManager().getServerAddress());
    EntityFullJid jid = SparkManager.getSessionManager().getJID();

    try {
        Collection<String> col = Agent.getWorkgroups(workgroupService, jid, SparkManager.getConnection());
        // Add workgroups to combobox
        Iterator<String> workgroups = col.iterator();
        while (workgroups.hasNext()) {
            String workgroup = workgroups.next();
            String componentAddress = XmppStringUtils.parseDomain(workgroup);
            setComponentAddress(componentAddress);
            comboBox.addItem(XmppStringUtils.parseLocalpart(workgroup));
        }
    }
    catch (XMPPException | SmackException | InterruptedException ee) {
        // If the user does not belong to a workgroup, then don't initialize the rest of the plugin.
        return;
    }

    try {
        agentSession.setOnline(false);
    }
    catch (XMPPException | SmackException | InterruptedException e1) {
        Log.error(e1);
    }
    litWorkspace.unload();
    wgroup = null;

    // UnRegister tab handler
    SparkManager.getChatManager().removeSparkTabHandler(fastpathTabHandler);
}
 
Example #11
Source File: JidCreateTest.java    From jxmpp with Apache License 2.0 5 votes vote down vote up
@Test
public void fullFromThrowTest() {
	final String notAFullJid = "[email protected]/";
	try {
		EntityFullJid jid = JidCreate.entityFullFrom(notAFullJid);
		// Should throw
		fail(jid + " should never been created");
	} catch (XmppStringprepException e) {
		assertEquals(notAFullJid, e.getCausingString());
	}
}
 
Example #12
Source File: ParserUtils.java    From Smack with Apache License 2.0 5 votes vote down vote up
public static EntityFullJid getFullJidAttribute(XmlPullParser parser, String name) throws XmppStringprepException {
    final String jidString = parser.getAttributeValue("", name);
    if (jidString == null) {
        return null;
    }
    return JidCreate.entityFullFrom(jidString);
}
 
Example #13
Source File: DummyConnection.java    From Smack with Apache License 2.0 5 votes vote down vote up
private EntityFullJid getUserJid() {
    try {
        return JidCreate.entityFullFrom(config.getUsername()
                        + "@"
                        + config.getXMPPServiceDomain()
                        + "/"
                        + (config.getResource() != null ? config.getResource() : "Test"));
    }
    catch (XmppStringprepException e) {
        throw new IllegalStateException(e);
    }
}
 
Example #14
Source File: MultiUserChat.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Changes the occupant's nickname to a new nickname within the room. Each room occupant
 * will receive two presence packets. One of type "unavailable" for the old nickname and one
 * indicating availability for the new nickname. The unavailable presence will contain the new
 * nickname and an appropriate status code (namely 303) as extended presence information. The
 * status code 303 indicates that the occupant is changing his/her nickname.
 *
 * @param nickname the new nickname within the room.
 * @throws XMPPErrorException if the new nickname is already in use by another occupant.
 * @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.
 * @throws MucNotJoinedException if not joined to the Multi-User Chat.
 */
public synchronized void changeNickname(Resourcepart nickname) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException, MucNotJoinedException  {
    Objects.requireNonNull(nickname, "Nickname must not be null or blank.");
    // Check that we already have joined the room before attempting to change the
    // nickname.
    if (!isJoined()) {
        throw new MucNotJoinedException(this);
    }
    final EntityFullJid jid = JidCreate.entityFullFrom(room, nickname);
    // We change the nickname by sending a presence packet where the "to"
    // field is in the form "roomName@service/nickname"
    // We don't have to signal the MUC support again
    Presence joinPresence = connection.getStanzaFactory().buildPresenceStanza()
            .to(jid)
            .ofType(Presence.Type.available)
            .build();

    // Wait for a presence packet back from the server.
    StanzaFilter responseFilter =
        new AndFilter(
            FromMatchesFilter.createFull(jid),
            new StanzaTypeFilter(Presence.class));
    StanzaCollector response = connection.createStanzaCollectorAndSend(responseFilter, joinPresence);
    // Wait up to a certain number of seconds for a reply. If there is a negative reply, an
    // exception will be thrown
    response.nextResultOrThrow();

    // TODO: Shouldn't this handle nickname rewriting by the MUC service?
    setNickname(nickname);
}
 
Example #15
Source File: JidCreate.java    From jxmpp with Apache License 2.0 5 votes vote down vote up
/**
 * Get a {@link EntityFullJid} from a given {@link CharSequence} or {@code null} if the input does not represent a JID.
 *
 * @param cs the input {@link CharSequence}
 * @return a JID or {@code null}
 */
public static EntityFullJid entityFullFromOrNull(CharSequence cs) {
	try {
		return entityFullFrom(cs);
	} catch (XmppStringprepException e) {
		return null;
	}
}
 
Example #16
Source File: FileTransferManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an OutgoingFileTransfer to send a file to another user.
 *
 * @param userID TODO javadoc me please
 *            The fully qualified jabber ID (i.e. full JID) with resource of the user to
 *            send the file to.
 * @return The send file object on which the negotiated transfer can be run.
 * @exception IllegalArgumentException if userID is null or not a full JID
 */
public OutgoingFileTransfer createOutgoingFileTransfer(EntityFullJid userID) {
    // We need to create outgoing file transfers with a full JID since this method will later
    // use XEP-0095 to negotiate the stream. This is done with IQ stanzas that need to be addressed to a full JID
    // in order to reach an client entity.
    if (userID == null) {
        throw new IllegalArgumentException("userID was null");
    }

    return new OutgoingFileTransfer(connection().getUser(), userID,
            FileTransferNegotiator.getNextStreamID(),
            fileTransferNegotiator);
}
 
Example #17
Source File: GroupChatParticipantList.java    From Spark with Apache License 2.0 4 votes vote down vote up
protected void addParticipant(final EntityFullJid participantJID, Presence presence) {
// Remove reference to invitees
for (CharSequence displayName : invitees.keySet()) {
    EntityFullJid jid = SparkManager.getUserManager().getJIDFromDisplayName(
	    displayName);

    Occupant occ = chat.getOccupant(jid);
    if (occ != null) {
	String actualJID = occ.getJid().toString();
	if (actualJID.equals(jid)) {
	    removeUser(displayName);
	}
    }
}

Resourcepart nickname = participantJID.getResourcepart();

MUCAffiliation affiliation = null;
MUCRole role = null;
final MUCUser extension = (MUCUser) presence.getExtension( MUCUser.NAMESPACE );
if ( extension != null && extension.getItem() != null )
{
	affiliation = extension.getItem().getAffiliation();
	role = extension.getItem().getRole();
}

if ( affiliation == null ) {
	affiliation = MUCAffiliation.none;
}
if ( role == null ) {
	role = MUCRole.none;
}

usersToRoles.put(participantJID, role);
usersToAffiliation.put(participantJID, affiliation);

Icon icon;
if (_localPreferences.isShowingRoleIcons()) {
    icon = getIconForRole(role, affiliation);
} else {
    icon = PresenceManager.getIconFromPresence(presence);
    if (icon == null) {
		icon = SparkRes.getImageIcon(SparkRes.GREEN_BALL);
	}
}

if (!exists(nickname)) {
    addUser(icon, nickname);
} else {
    int index = getIndex(nickname);
    if (index != -1) {
	final JLabel userLabel = new JLabel(nickname.toString(), icon,
		JLabel.HORIZONTAL);
	model.setElementAt(userLabel, index);
    }
}
   }
 
Example #18
Source File: GroupChatParticipantList.java    From Spark with Apache License 2.0 4 votes vote down vote up
protected ImageIcon getImageIcon(EntityFullJid participantJID) {
	Resourcepart displayName = participantJID.getResourcepart();
	ImageIcon icon = SparkRes.getImageIcon(SparkRes.GREEN_BALL);
	icon.setDescription(displayName.toString());
	return icon;
}
 
Example #19
Source File: DefaultParticipantStatusListener.java    From Smack with Apache License 2.0 4 votes vote down vote up
@Override
public void left(EntityFullJid participant) {
}
 
Example #20
Source File: DefaultParticipantStatusListener.java    From Smack with Apache License 2.0 4 votes vote down vote up
@Override
public void kicked(EntityFullJid participant, Jid actor, String reason) {
}
 
Example #21
Source File: DefaultParticipantStatusListener.java    From Smack with Apache License 2.0 4 votes vote down vote up
@Override
public void voiceGranted(EntityFullJid participant) {
}
 
Example #22
Source File: DefaultParticipantStatusListener.java    From Smack with Apache License 2.0 4 votes vote down vote up
@Override
public void voiceRevoked(EntityFullJid participant) {
}
 
Example #23
Source File: DefaultParticipantStatusListener.java    From Smack with Apache License 2.0 4 votes vote down vote up
@Override
public void banned(EntityFullJid participant, Jid actor, String reason) {
}
 
Example #24
Source File: FastpathPlugin.java    From Spark with Apache License 2.0 4 votes vote down vote up
public void initialize() {

        new WorkgroupInitializer().initialize();

        EventQueue.invokeLater(new Runnable() {

			@Override
			public void run() {
				  container = new FastpathContainer();
				  workgroupLabel = new JLabel(FpRes.getString("workgroup"));
				  comboBox = new JComboBox();
				  joinButton = new JButton(FpRes.getString("join"), null);
				  logoutButton = new RolloverButton(FpRes.getString("logout"), null);
		        // Initialize tab handler for Fastpath chats.
		        fastpathTabHandler = new FastpathTabHandler();
		        mainPanel = new BackgroundPane();
			}
   		 
   	 });
   	 




			
			
        try {
            DiscoverItems items = SparkManager.getSessionManager().getDiscoveredItems();
            for (DiscoverItems.Item item : items.getItems() ) {
                String entityID = item.getEntityID() != null ? item.getEntityID().toString() : "";
                if (entityID.startsWith("workgroup")) {
                    // Log into workgroup
                    final DomainBareJid workgroupService = JidCreate.domainBareFromOrThrowUnchecked("workgroup." + SparkManager.getSessionManager().getServerAddress());
                    final EntityFullJid jid = SparkManager.getSessionManager().getJID();


                    SwingWorker worker = new SwingWorker() {
                        public Object construct() {
                            try {
                                return Agent.getWorkgroups(workgroupService, jid, SparkManager.getConnection());
                            }
                            catch (XMPPException | SmackException | InterruptedException e1) {
                                return Collections.emptyList();
                            }
                        }

                        public void finished() {
                            Collection<String> agents = (Collection<String>)get();
                            if (agents.size() == 0) {
                                return;
                            }
                            showSelection(agents);
                        }
                    };

                    worker.start();

                }

            }
        }
        catch (Exception e) {
            Log.error(e);
        }

        SparkManager.getConnection().addConnectionListener(this);
    }
 
Example #25
Source File: DefaultParticipantStatusListener.java    From Smack with Apache License 2.0 4 votes vote down vote up
@Override
public void joined(EntityFullJid participant) {
}
 
Example #26
Source File: IntegrationTestRosterUtil.java    From Smack with Apache License 2.0 4 votes vote down vote up
public static void ensureSubscribedTo(final XMPPConnection presenceRequestReceiverConnection, final XMPPConnection presenceRequestingConnection, long timeout) throws TimeoutException, Exception {
    final Roster presenceRequestReceiverRoster = Roster.getInstanceFor(presenceRequestReceiverConnection);
    final Roster presenceRequestingRoster = Roster.getInstanceFor(presenceRequestingConnection);

    final EntityFullJid presenceRequestReceiverAddress = presenceRequestReceiverConnection.getUser();
    final EntityFullJid presenceRequestingAddress = presenceRequestingConnection.getUser();

    if (presenceRequestReceiverRoster.isSubscribedToMyPresence(presenceRequestingAddress)) {
        return;
    }

    final SubscribeListener subscribeListener = new SubscribeListener() {
        @Override
        public SubscribeAnswer processSubscribe(Jid from, Presence subscribeRequest) {
            if (from.equals(presenceRequestingConnection.getUser().asBareJid())) {
                return SubscribeAnswer.Approve;
            }
            return SubscribeAnswer.Deny;
        }
    };
    presenceRequestReceiverRoster.addSubscribeListener(subscribeListener);

    final SimpleResultSyncPoint syncPoint = new SimpleResultSyncPoint();
    final PresenceEventListener presenceEventListener = new AbstractPresenceEventListener() {
        @Override
        public void presenceSubscribed(BareJid address, Presence subscribedPresence) {
            if (!address.equals(presenceRequestReceiverAddress.asBareJid())) {
                return;
            }
            syncPoint.signal();
        }
    };
    presenceRequestingRoster.addPresenceEventListener(presenceEventListener);

    try {
        presenceRequestingRoster.sendSubscriptionRequest(presenceRequestReceiverAddress.asBareJid());

        syncPoint.waitForResult(timeout);
    } finally {
        presenceRequestReceiverRoster.removeSubscribeListener(subscribeListener);
        presenceRequestingRoster.removePresenceEventListener(presenceEventListener);
    }
}
 
Example #27
Source File: OmemoManager.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * Encrypt a message for all recipients in the MultiUserChat.
 *
 * @param muc multiUserChat
 * @param message message to send
 * @return encrypted message
 *
 * @throws UndecidedOmemoIdentityException when there are undecided devices.
 * @throws CryptoFailedException if the OMEMO cryptography failed.
 * @throws XMPPException.XMPPErrorException if there was an XMPP error returned.
 * @throws SmackException.NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 * @throws SmackException.NoResponseException if there was no response from the remote entity.
 * @throws NoOmemoSupportException When the muc doesn't support OMEMO.
 * @throws SmackException.NotLoggedInException if the XMPP connection is not authenticated.
 * @throws IOException if an I/O error occurred.
 */
public synchronized OmemoMessage.Sent encrypt(MultiUserChat muc, String message)
        throws UndecidedOmemoIdentityException, CryptoFailedException,
        XMPPException.XMPPErrorException, SmackException.NotConnectedException, InterruptedException,
        SmackException.NoResponseException, NoOmemoSupportException,
        SmackException.NotLoggedInException, IOException {
    if (!multiUserChatSupportsOmemo(muc)) {
        throw new NoOmemoSupportException();
    }

    Set<BareJid> recipients = new HashSet<>();

    for (EntityFullJid e : muc.getOccupants()) {
        recipients.add(muc.getOccupant(e).getJid().asBareJid());
    }
    return encrypt(recipients, message);
}
 
Example #28
Source File: DefaultParticipantStatusListener.java    From Smack with Apache License 2.0 4 votes vote down vote up
@Override
public void nicknameChanged(EntityFullJid participant, Resourcepart newNickname) {
}
 
Example #29
Source File: MUCUser.java    From Smack with Apache License 2.0 4 votes vote down vote up
public Invite(String reason, EntityFullJid from) {
    this(reason, from, null);
}
 
Example #30
Source File: GroupChatParticipantList.java    From Spark with Apache License 2.0 4 votes vote down vote up
protected Map<CharSequence, EntityFullJid> getUserMap() {
    return userMap;
}