org.jxmpp.jid.EntityJid Java Examples

The following examples show how to use org.jxmpp.jid.EntityJid. 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: ParserUtils.java    From Smack with Apache License 2.0 6 votes vote down vote up
public static EntityJid getEntityJidAttribute(XmlPullParser parser, String name) throws XmppStringprepException {
    final String jidString = parser.getAttributeValue("", name);
    if (jidString == null) {
        return null;
    }
    Jid jid = JidCreate.from(jidString);

    if (!jid.hasLocalpart()) return null;

    EntityFullJid fullJid = jid.asEntityFullJidIfPossible();
    if (fullJid != null) {
        return fullJid;
    }

    EntityBareJid bareJid = jid.asEntityBareJidIfPossible();
    return bareJid;
}
 
Example #2
Source File: MultiUserChatLight.java    From Smack with Apache License 2.0 6 votes vote down vote up
MultiUserChatLight(XMPPConnection connection, EntityJid room) {
    this.connection = connection;
    this.room = room;

    fromRoomFilter = FromMatchesFilter.create(room);
    fromRoomGroupChatFilter = new AndFilter(fromRoomFilter, MessageTypeFilter.GROUPCHAT);

    messageListener = new StanzaListener() {
        @Override
        public void processStanza(Stanza packet) throws NotConnectedException {
            Message message = (Message) packet;
            for (MessageListener listener : messageListeners) {
                listener.processMessage(message);
            }
        }
    };

    connection.addSyncStanzaListener(messageListener, fromRoomGroupChatFilter);
}
 
Example #3
Source File: ChatManager.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@link Chat} based on the message. May returns null if no chat could be
 * created, e.g. because the message comes without from.
 *
 * @param message TODO javadoc me please
 * @return a Chat or null if none can be created
 */
private Chat createChat(Message message) {
    Jid from = message.getFrom();
    // According to RFC6120 8.1.2.1 4. messages without a 'from' attribute are valid, but they
    // are of no use in this case for ChatManager
    if (from == null) {
        return null;
    }

    EntityJid userJID = from.asEntityJidIfPossible();
    if (userJID == null) {
        LOGGER.warning("Message from JID without localpart: '" + message.toXML() + "'");
        return null;
    }
    String threadID = message.getThread();
    if (threadID == null) {
        threadID = nextID();
    }

    return createChat(userJID, threadID, false);
}
 
Example #4
Source File: MUCUserProvider.java    From Smack with Apache License 2.0 6 votes vote down vote up
private static MUCUser.Invite parseInvite(XmlPullParser parser) throws XmlPullParserException, IOException {
    String reason = null;
    EntityBareJid to = ParserUtils.getBareJidAttribute(parser, "to");
    EntityJid from = ParserUtils.getEntityJidAttribute(parser, "from");

    outerloop: while (true) {
        XmlPullParser.Event eventType = parser.next();
        if (eventType == XmlPullParser.Event.START_ELEMENT) {
            if (parser.getName().equals("reason")) {
                reason = parser.nextText();
            }
        }
        else if (eventType == XmlPullParser.Event.END_ELEMENT) {
            if (parser.getName().equals("invite")) {
                break outerloop;
            }
        }
    }
    return new MUCUser.Invite(reason, from, to);
}
 
Example #5
Source File: JidCreate.java    From jxmpp with Apache License 2.0 5 votes vote down vote up
/**
 * Get a {@link EntityJid} 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 EntityJid entityFromUnesacpedOrNull(CharSequence cs) {
	try {
		return entityFromUnescaped(cs.toString());
	} catch (XmppStringprepException e) {
		return null;
	}
}
 
Example #6
Source File: Chat.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new chat with the specified user and thread ID.
 *
 * @param chatManager the chatManager the chat will use.
 * @param participant the user to chat with.
 * @param threadID the thread ID to use.
 */
Chat(ChatManager chatManager, EntityJid participant, String threadID) {
    if (StringUtils.isEmpty(threadID)) {
        throw new IllegalArgumentException("Thread ID must not be null");
    }
    this.chatManager = chatManager;
    this.participant = participant;
    this.threadID = threadID;
}
 
Example #7
Source File: ChatManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
private Chat createChat(EntityJid userJID, String threadID, boolean createdLocally) {
    Chat chat = new Chat(this, userJID, threadID);
    threadChats.put(threadID, chat);
    jidChats.put(userJID, chat);
    baseJidChats.put(userJID.asEntityBareJid(), chat);

    for (ChatManagerListener listener : chatManagerListeners) {
        listener.chatCreated(chat, createdLocally);
    }

    return chat;
}
 
Example #8
Source File: MUCLightCreateIQ.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * MUCLight create IQ constructor.
 *
 * @param room TODO javadoc me please
 * @param roomName TODO javadoc me please
 * @param subject TODO javadoc me please
 * @param customConfigs TODO javadoc me please
 * @param occupants TODO javadoc me please
 */
public MUCLightCreateIQ(EntityJid room, String roomName, String subject, HashMap<String, String> customConfigs,
        List<Jid> occupants) {
    super(ELEMENT, NAMESPACE);
    this.configuration = new MUCLightRoomConfiguration(roomName, subject, customConfigs);

    this.occupants = new HashMap<>();
    for (Jid occupant : occupants) {
        this.occupants.put(occupant, MUCLightAffiliation.member);
    }

    this.setType(Type.set);
    this.setTo(room);
}
 
Example #9
Source File: JidCreateTest.java    From jxmpp with Apache License 2.0 5 votes vote down vote up
@Test
public void entityFromUnescapedFullTest() throws XmppStringprepException {
	EntityJid entityBareJid = JidCreate.entityFromUnescaped("d'[email protected]/elder");

	Domainpart domainpart = entityBareJid.getDomain();
	assertEquals(Domainpart.from("gascon.fr"), domainpart);

	Resourcepart resourcepart = entityBareJid.getResourceOrThrow();
	assertEquals(Resourcepart.from("elder"), resourcepart);

	Localpart localpart = entityBareJid.getLocalpart();
	assertEquals(Localpart.from("d\\27artagnan"), localpart);
}
 
Example #10
Source File: JidCreateTest.java    From jxmpp with Apache License 2.0 5 votes vote down vote up
@Test
public void entityFromUnescapedBareTest() throws XmppStringprepException {
	EntityJid entityJid = JidCreate.entityFromUnescaped("d'[email protected]");

	Domainpart domainpart = entityJid.getDomain();
	assertEquals(Domainpart.from("musketeers.lit"), domainpart);

	Localpart localpart = entityJid.getLocalpart();
	assertEquals(Localpart.from("d\\27artagnan"), localpart);

	assertEquals(localpart, Localpart.fromUnescaped("d'artagnan"));
}
 
Example #11
Source File: ChatManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new chat using the specified thread ID, then returns it.
 *
 * @param userJID the jid of the user this chat is with
 * @param thread the thread of the created chat.
 * @param listener the optional listener to add to the chat
 * @return the created chat.
 */
public Chat createChat(EntityJid userJID, String thread, ChatMessageListener listener) {
    if (thread == null) {
        thread = nextID();
    }
    Chat chat = threadChats.get(thread);
    if (chat != null) {
        throw new IllegalArgumentException("ThreadID is already used");
    }
    chat = createChat(userJID, thread, true);
    chat.addMessageListener(listener);
    return chat;
}
 
Example #12
Source File: DepartQueuePacket.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a depart queue request to the specified workgroup and for the
 * specified user.
 *
 * @param workgroup the workgroup to depart.
 * @param user the user to make depart from the queue.
 */
public DepartQueuePacket(EntityBareJid workgroup, EntityJid user) {
    super("depart-queue", "http://jabber.org/protocol/workgroup");
    this.user = user;

    setTo(workgroup);
    setType(IQ.Type.set);
    setFrom(user);
}
 
Example #13
Source File: JidCreate.java    From jxmpp with Apache License 2.0 5 votes vote down vote up
/**
 * Get a {@link EntityJid} 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 EntityJid entityFromOrNull(CharSequence cs) {
	try {
		return entityFrom(cs);
	} catch (XmppStringprepException e) {
		return null;
	}
}
 
Example #14
Source File: MucChatService.java    From xyTalk-pc with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void mucInvitation() {
	MultiUserChatManager.getInstanceFor(Launcher.connection).addInvitationListener(new InvitationListener() {
		@Override
		public void invitationReceived(XMPPConnection conn, MultiUserChat room, EntityJid inviter, String reason,
				String password, Message message, Invite invitation) {
			String barejid = message.getFrom().toString();
			DebugUtil.debug("被邀请加入群聊:" + barejid + reason);
			try {

				room.join(Resourcepart.from(UserCache.CurrentUserName + "-" + UserCache.CurrentUserRealName));

				if (barejid != null) {
					if (Launcher.currRoomId.equals(barejid)) {
						// 当前聊天者即为已有群
						// updateChatPanel(message);
					} else {
						if (Launcher.roomService.exist(barejid)) {
							// 联系人列表中存在群组,更新未读信息,则修改
							// updateRoom(message);
						} else {
							// 联系人中不存在群组,则新建一个群
							createNewRoom(message);
						}
						// dbMessagePersistence(message);
					}
				}

			} catch (NotAMucServiceException | NoResponseException | XMPPErrorException | NotConnectedException
					| XmppStringprepException | InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	});
}
 
Example #15
Source File: ChatRoomImpl.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
 * Set the XMPP address of the participant.
 *
 * @param jidString the XMPP address
 * @deprecated use {@link #setparticipantJID(EntityJid)} instead.
 */
@Deprecated
private void setparticipantJID(String jidString) {
    EntityJid jid;
    try {
        jid = JidCreate.entityFrom(jidString);
    } catch (XmppStringprepException e) {
        throw new IllegalStateException(e);
    }
    setparticipantJID(jid);
}
 
Example #16
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 #17
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);
}
 
Example #18
Source File: RoomInvitation.java    From Smack with Apache License 2.0 4 votes vote down vote up
public EntityJid getInviter() {
    return inviter;
}
 
Example #19
Source File: LocalDomainAndResourcepartJid.java    From jxmpp with Apache License 2.0 4 votes vote down vote up
@Override
public EntityJid asEntityJidIfPossible() {
	return this;
}
 
Example #20
Source File: InvitationRequest.java    From Smack with Apache License 2.0 4 votes vote down vote up
public InvitationRequest(EntityJid inviter, EntityBareJid room, String reason) {
    this.inviter = inviter;
    this.room = room;
    this.reason = reason;
}
 
Example #21
Source File: InvitationRequest.java    From Smack with Apache License 2.0 4 votes vote down vote up
public EntityJid getInviter() {
    return inviter;
}
 
Example #22
Source File: ChatManager.java    From Smack with Apache License 2.0 4 votes vote down vote up
void closeChat(Chat chat) {
    threadChats.remove(chat.getThreadID());
    EntityJid userJID = chat.getParticipant();
    jidChats.remove(userJID);
    baseJidChats.remove(userJID.asEntityBareJid());
}
 
Example #23
Source File: MUCUser.java    From Smack with Apache License 2.0 4 votes vote down vote up
public Invite(String reason, EntityJid from, EntityBareJid to) {
    this.reason = reason;
    this.from = from;
    this.to = to;
}
 
Example #24
Source File: ChatRoomImpl.java    From Spark with Apache License 2.0 4 votes vote down vote up
public ChatRoomImpl(final EntityJid participantJID, Resourcepart participantNickname, CharSequence title) {
    this(participantJID, participantNickname, title, true);
}
 
Example #25
Source File: ChatRoomImpl.java    From Spark with Apache License 2.0 4 votes vote down vote up
/**
 * Constructs a 1-to-1 ChatRoom.
 *
 * Note that the participantJID value can be a bare JID, or a full JID. In regular one-on-one chats, a bare JID is
 * expected. This instance will then display relevant data sent by any of the (full) JIDs associated to the bare JID.
 * When this instance is created to reflect a private message in MUC context, a full JID is expected to be provided
 * as the participantJID value (room@service/nick). In such case, only data sent from that full JID is displayed.
 *
 * @param participantJID      the participants jid to chat with.
 * @param participantNickname the nickname of the participant.
 * @param title               the title of the room.
 */
public ChatRoomImpl(final EntityJid participantJID, Resourcepart participantNickname, CharSequence title, boolean initUi) {
    this.active = true;
    //activateNotificationTime = System.currentTimeMillis();
    setparticipantJID(participantJID);
    this.participantNickname = participantNickname;

    // Loads the current history for this user.
    loadHistory();

    // Register StanzaListeners
    final StanzaFilter directFilter = new AndFilter(
        FromMatchesFilter.create( participantJID ),
        new OrFilter( new StanzaTypeFilter( Presence.class ),
                      new StanzaTypeFilter( Message.class ) )
    );

    final StanzaFilter carbonFilter = new AndFilter(
        FromMatchesFilter.create( SparkManager.getSessionManager().getBareUserAddress() ), // Security Consideration, see https://xmpp.org/extensions/xep-0280.html#security
        new StanzaTypeFilter( Message.class ),
        new OrFilter(
            new StanzaExtensionFilter( "sent", CarbonExtension.NAMESPACE ),
            new StanzaExtensionFilter( "received", CarbonExtension.NAMESPACE )
        )
    );

    SparkManager.getConnection().addSyncStanzaListener( this, new OrFilter( directFilter, carbonFilter ) );

    // Use the agents username as the Tab Title
    this.tabTitle = title.toString();

    // The name of the room will be the node of the user jid + conversation.
    this.roomTitle = participantNickname.toString();

    // Add RoomInfo
    this.getSplitPane().setRightComponent(null);
    getSplitPane().setDividerSize(0);


    presence = PresenceManager.getPresence(participantJID.asBareJid());

    roster = Roster.getInstanceFor( SparkManager.getConnection() );

    RosterEntry entry = roster.getEntry(participantJID.asBareJid());

    tabIcon = PresenceManager.getIconFromPresence(presence);

    if (initUi) {
        // Create toolbar buttons.
        infoButton = new ChatRoomButton("", SparkRes.getImageIcon(SparkRes.PROFILE_IMAGE_24x24));
        infoButton.setToolTipText(Res.getString("message.view.information.about.this.user"));
        // Create basic toolbar.
        addChatRoomButton(infoButton);
        // Show VCard.
        infoButton.addActionListener(this);
    }

    // If this is a private chat from a group chat room, do not show toolbar.
    privateChat = participantNickname.equals(participantJID.getResourceOrNull());
    if ( privateChat ) {
        getToolBar().setVisible(false);
    }

    // If the user is not in the roster, then allow user to add them.
    addToRosterButton = new ChatRoomButton("", SparkRes.getImageIcon(SparkRes.ADD_IMAGE_24x24));
    if (entry == null && !privateChat) {
        addToRosterButton.setToolTipText(Res.getString("message.add.this.user.to.your.roster"));
        if (!Default.getBoolean("ADD_CONTACT_DISABLED") && Enterprise.containsFeature(Enterprise.ADD_CONTACTS_FEATURE)) addChatRoomButton(addToRosterButton);
        addToRosterButton.addActionListener(this);
    }

    lastActivity = System.currentTimeMillis();
}
 
Example #26
Source File: DomainpartJid.java    From jxmpp with Apache License 2.0 4 votes vote down vote up
@Override
public EntityJid asEntityJidIfPossible() {
	return null;
}
 
Example #27
Source File: AbstractJid.java    From jxmpp with Apache License 2.0 4 votes vote down vote up
@Override
public EntityJid asEntityJidOrThrow() {
	EntityJid entityJid = asEntityJidIfPossible();
	if (entityJid == null) throwIse("can not be converted to EntityJid");
	return entityJid;
}
 
Example #28
Source File: AbstractJid.java    From jxmpp with Apache License 2.0 4 votes vote down vote up
@Override
public final boolean hasLocalpart() {
	return this instanceof EntityJid;
}
 
Example #29
Source File: LocalAndDomainpartJid.java    From jxmpp with Apache License 2.0 4 votes vote down vote up
@Override
public EntityJid asEntityJidIfPossible() {
	return this;
}
 
Example #30
Source File: DomainAndResourcepartJid.java    From jxmpp with Apache License 2.0 4 votes vote down vote up
@Override
public EntityJid asEntityJidIfPossible() {
	return null;
}