Java Code Examples for org.jxmpp.jid.impl.JidCreate#from()

The following examples show how to use org.jxmpp.jid.impl.JidCreate#from() . 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: TransportUtils.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * Checks if the user is registered with a gateway.
 *
 * @param con       the XMPPConnection.
 * @param transport the transport.
 * @return true if the user is registered with the transport.
 */
public static boolean isRegistered(XMPPConnection con, Transport transport) {
    if (!con.isConnected()) {
        return false;
    }

    ServiceDiscoveryManager discoveryManager = ServiceDiscoveryManager.getInstanceFor(con);
    try {
        Jid jid = JidCreate.from(transport.getXMPPServiceDomain());
        DiscoverInfo info = discoveryManager.discoverInfo(jid);
        return info.containsFeature("jabber:iq:registered");
    }
    catch (XMPPException | SmackException | XmppStringprepException | InterruptedException e) {
        Log.error(e);
    }
    return false;
}
 
Example 2
Source File: MUCLightChangeAffiliationsIQTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Test
public void checkChangeAffiliationsMUCLightStanza() throws Exception {
    HashMap<Jid, MUCLightAffiliation> affiliations = new HashMap<>();
    affiliations.put(JidCreate.from("[email protected]"), MUCLightAffiliation.owner);
    affiliations.put(JidCreate.from("[email protected]"), MUCLightAffiliation.member);
    affiliations.put(JidCreate.from("[email protected]"), MUCLightAffiliation.none);

    MUCLightChangeAffiliationsIQ mucLightChangeAffiliationsIQ = new MUCLightChangeAffiliationsIQ(
            JidCreate.from("[email protected]"), affiliations);
    mucLightChangeAffiliationsIQ.setStanzaId("member1");

    assertEquals(mucLightChangeAffiliationsIQ.getTo(), "[email protected]");
    assertEquals(mucLightChangeAffiliationsIQ.getType(), IQ.Type.set);

    HashMap<Jid, MUCLightAffiliation> iqAffiliations = mucLightChangeAffiliationsIQ.getAffiliations();
    assertEquals(iqAffiliations.get(JidCreate.from("[email protected]")), MUCLightAffiliation.member);
    assertEquals(iqAffiliations.get(JidCreate.from("[email protected]")), MUCLightAffiliation.owner);
    assertEquals(iqAffiliations.get(JidCreate.from("[email protected]")), MUCLightAffiliation.none);
}
 
Example 3
Source File: ConferenceServiceBrowser.java    From Spark with Apache License 2.0 6 votes vote down vote up
public Collection<String> getConferenceServices(String serverString) throws Exception {
    Jid server = JidCreate.from(serverString);
    List<String> answer = new ArrayList<>();
    ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(SparkManager.getConnection());
    DiscoverItems items = discoManager.discoverItems(server);
    for (DiscoverItems.Item item : items.getItems() ) {
        if (item.getEntityID().toString().startsWith("conference") || item.getEntityID().toString().startsWith("private")) {
            answer.add(item.getEntityID().toString());
        }
        else {
            try {
                DiscoverInfo info = discoManager.discoverInfo(item.getEntityID());
                if (info.containsFeature("http://jabber.org/protocol/muc")) {
                    answer.add(item.getEntityID().toString());
                }
            }
            catch (XMPPException | SmackException e) {
                // Nothing to do
            }
        }
    }
    return answer;
}
 
Example 4
Source File: JidUtil.java    From jxmpp with Apache License 2.0 6 votes vote down vote up
/**
 * Convert a collection of Strings to a Set of {@link Jid}'s.
 * <p>
 * If the optional argument <code>exceptions</code> is given, then all {@link XmppStringprepException} thrown while
 * converting will be added to the list. Otherwise, if an XmppStringprepExceptions is thrown, it will be wrapped in
 * a AssertionError Exception and throw.
 * </p>
 * 
 * @param jidStrings
 *            the strings that are going to get converted
 * @param output
 *            the collection where the Jid's will be added to
 * @param exceptions the list of exceptions thrown while converting.
 */
public static void jidsFrom(Collection<? extends CharSequence> jidStrings, Collection<? super Jid> output,
		List<XmppStringprepException> exceptions) {
	for (CharSequence jidString : jidStrings) {
		try {
			Jid jid = JidCreate.from(jidString);
			output.add(jid);
		} catch (XmppStringprepException e) {
			if (exceptions != null) {
				exceptions.add(e);
			} else {
				throw new AssertionError(e);
			}
		}
	}
}
 
Example 5
Source File: RoomManager.java    From mangosta-android with Apache License 2.0 5 votes vote down vote up
public void addToMUCLight(User user, String chatJID) {
    MultiUserChatLightManager multiUserChatLightManager = XMPPSession.getInstance().getMUCLightManager();
    try {
        MultiUserChatLight mucLight = multiUserChatLightManager.getMultiUserChatLight(JidCreate.from(chatJID).asEntityBareJidIfPossible());

        Jid jid = JidCreate.from(XMPPUtils.fromUserNameToJID(user.getLogin()));

        HashMap<Jid, MUCLightAffiliation> affiliations = new HashMap<>();
        affiliations.put(jid, MUCLightAffiliation.member);

        mucLight.changeAffiliations(affiliations);
    } catch (XmppStringprepException | InterruptedException | SmackException.NotConnectedException | SmackException.NoResponseException | XMPPException.XMPPErrorException e) {
        e.printStackTrace();
    }
}
 
Example 6
Source File: MUCLightSetConfigsIQTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Test
public void checkSetConfigsStanza() throws Exception {
    HashMap<String, String> customConfigs = new HashMap<>();
    customConfigs.put("color", "blue");

    MUCLightSetConfigsIQ mucLightSetConfigsIQ = new MUCLightSetConfigsIQ(
            JidCreate.from("[email protected]"), "A Darker Cave", customConfigs);
    mucLightSetConfigsIQ.setStanzaId("conf1");

    assertEquals(setConfigsIQExample, mucLightSetConfigsIQ.toXML(StreamOpen.CLIENT_NAMESPACE).toString());
}
 
Example 7
Source File: BuzzRoomDecorator.java    From Spark with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent e) {
       Jid jid;
       try {
           jid = JidCreate.from(((ChatRoomImpl)chatRoom).getParticipantJID());
       } catch (XmppStringprepException exception) {
           throw new IllegalStateException(exception);
       }
       Message message = new Message();
       message.setTo(jid);
       message.addExtension(new BuzzPacket());
       try
       {
           SparkManager.getConnection().sendStanza(message);
       }
       catch ( SmackException.NotConnectedException | InterruptedException e1 )
       {
           Log.warning( "Unable to send stanza to " + jid, e1 );
       }

       chatRoom.getTranscriptWindow().insertNotificationMessage(Res.getString("message.buzz.sent"), ChatManager.NOTIFICATION_COLOR);
       buzzButton.setEnabled(false);

       // Enable the button after 30 seconds to prevent abuse.
       final TimerTask enableTask = new SwingTimerTask() {
           @Override
		public void doRun() {
               buzzButton.setEnabled(true);
           }
       };

       TaskEngine.getInstance().schedule(enableTask, 30000);
   }
 
Example 8
Source File: RosterTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
public boolean deletedAddressesContains(String jidString) {
    Jid jid;
    try {
        jid = JidCreate.from(jidString);
    }
    catch (XmppStringprepException e) {
        throw new IllegalArgumentException(e);
    }
    return addressesDeleted.contains(jid);
}
 
Example 9
Source File: MUCLightInfoTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Test
public void checkMUCLightGetInfoIQStanzaWithVersion() throws Exception {
    MUCLightGetInfoIQ mucLightGetInfoIQWithVersion = new MUCLightGetInfoIQ(
            JidCreate.from("[email protected]"), "abcdefg");
    mucLightGetInfoIQWithVersion.setStanzaId("getinfo1");
    assertEquals(mucLightGetInfoIQWithVersion.toXML(StreamOpen.CLIENT_NAMESPACE).toString(), exampleWithVersion);
}
 
Example 10
Source File: RemoteDisablingProvider.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public RemoteDisablingExtension parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) throws XmlPullParserException, IOException {
    Jid userJid = null;
    String node = parser.getAttributeValue("", "node");

    outerloop: while (true) {
        XmlPullParser.Event eventType = parser.next();
        if (eventType == XmlPullParser.Event.START_ELEMENT) {
            if (parser.getName().equals("affiliation")) {
                userJid = JidCreate.from(parser.getAttributeValue("", "jid"));

                String affiliation = parser.getAttributeValue("", "affiliation");
                if (affiliation == null || !affiliation.equals("none")) {
                    // TODO: Is this correct? We previously returned null here, but was certainly wrong, as
                    // providers should always return an element or throw.
                    throw new IOException("Invalid affiliation: " + affiliation);
                }
            }
        } else if (eventType == XmlPullParser.Event.END_ELEMENT) {
            if (parser.getDepth() == initialDepth) {
                break outerloop;
            }
        }
    }

    return new RemoteDisablingExtension(node, userJid);
}
 
Example 11
Source File: MUCLightAffiliationsChangeProvider.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public AffiliationsChangeExtension parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) throws XmlPullParserException, IOException {
    HashMap<Jid, MUCLightAffiliation> affiliations = new HashMap<>();
    String prevVersion = null;
    String version = null;

    outerloop: while (true) {
        XmlPullParser.Event eventType = parser.next();

        if (eventType == XmlPullParser.Event.START_ELEMENT) {

            if (parser.getName().equals("prev-version")) {
                prevVersion = parser.nextText();
            }

            if (parser.getName().equals("version")) {
                version = parser.nextText();
            }

            if (parser.getName().equals("user")) {
                MUCLightAffiliation mucLightAffiliation = MUCLightAffiliation
                        .fromString(parser.getAttributeValue("", "affiliation"));
                Jid jid = JidCreate.from(parser.nextText());
                affiliations.put(jid, mucLightAffiliation);
            }

        } else if (eventType == XmlPullParser.Event.END_ELEMENT) {
            if (parser.getDepth() == initialDepth) {
                break outerloop;
            }
        }
    }

    return new AffiliationsChangeExtension(affiliations, prevVersion, version);
}
 
Example 12
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 13
Source File: Jid.java    From Pix-Art-Messenger with GNU General Public License v3.0 5 votes vote down vote up
static Jid ofEscaped(CharSequence jid) {
    try {
        return new WrappedJid(JidCreate.from(jid));
    } catch (XmppStringprepException e) {
        e.printStackTrace();
        throw new IllegalArgumentException(e);
    }
}
 
Example 14
Source File: PrivacyPresenceHandler.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
 * Send Unavailable (offline status) to jid .
 * 
 * @param jid
 *            JID to send offline status
 * @deprecated use {#link {@link #sendUnavailableTo(Jid)}} instead. 
 */
@Deprecated
public void sendUnavailableTo(String jidString) throws SmackException.NotConnectedException
{
    Jid jid;
    try {
        jid = JidCreate.from(jidString);
    } catch (XmppStringprepException e) {
        throw new IllegalStateException(e);
    }
    sendUnavailableTo(jid);
}
 
Example 15
Source File: DoX.java    From Smack with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws XMPPException, SmackException, IOException, InterruptedException {
    SmackConfiguration.DEBUG = true;

    XMPPTCPConnection connection = new XMPPTCPConnection(args[0], args[1]);
    connection.setReplyTimeout(60000);

    connection.connect().login();

    DnsOverXmppManager dox = DnsOverXmppManager.getInstanceFor(connection);

    Jid target = JidCreate.from("[email protected]/listener");
    Question question = new Question("geekplace.eu", Record.TYPE.A);

    DnsMessage response = dox.query(target, question);

    // CHECKSTYLE:OFF
    System.out.println(response);
    // CHECKSTYLE:ON

    connection.disconnect();
}
 
Example 16
Source File: FillableForm.java    From Smack with Apache License 2.0 4 votes vote down vote up
public void setAnswer(String fieldName, CharSequence answer) {
    FormField blankField = getFieldOrThrow(fieldName);
    FormField.Type type = blankField.getType();

    FormField filledFormField;
    switch (type) {
    case list_multi:
    case jid_multi:
        throw new IllegalArgumentException("Can not answer fields of type '" + type + "' with a CharSequence");
    case fixed:
        throw new IllegalArgumentException("Fields of type 'fixed' are not answerable");
    case list_single:
    case text_private:
    case text_single:
    case hidden:
        filledFormField = createSingleKindFieldBuilder(fieldName, type)
            .setValue(answer)
            .build();
        break;
    case bool:
        filledFormField = FormField.booleanBuilder(fieldName)
            .setValue(answer)
            .build();
        break;
    case jid_single:
        Jid jid;
        try {
            jid = JidCreate.from(answer);
        } catch (XmppStringprepException e) {
            throw new IllegalArgumentException(e);
        }
        filledFormField = FormField.jidSingleBuilder(fieldName)
            .setValue(jid)
            .build();
        break;
    case text_multi:
        filledFormField = createMultiKindFieldbuilder(fieldName, type)
            .addValue(answer)
            .build();
        break;
    default:
        throw new AssertionError();
    }
    write(filledFormField);
}
 
Example 17
Source File: JingleS5BTransportCandidate.java    From Smack with Apache License 2.0 4 votes vote down vote up
public Builder setJid(String jid) throws XmppStringprepException {
    this.jid = JidCreate.from(jid);
    return this;
}
 
Example 18
Source File: SubscriptionPreApprovalTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
@Test(expected = FeatureNotSupportedException.class)
public void testPreApprovalNotSupported() throws Throwable {
    final Jid contactJID = JidCreate.from("[email protected]");
    roster.preApprove(contactJID.asBareJid());
}
 
Example 19
Source File: MUCLightDestroyTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
@Test
public void checkDestroyMUCLightStanza() throws Exception {
    MUCLightDestroyIQ mucLightDestroyIQ = new MUCLightDestroyIQ(JidCreate.from("[email protected]"));
    mucLightDestroyIQ.setStanzaId("destroy1");
    assertEquals(mucLightDestroyIQ.toXML(StreamOpen.CLIENT_NAMESPACE).toString(), stanza);
}
 
Example 20
Source File: Node.java    From Smack with Apache License 2.0 3 votes vote down vote up
/**
 * The user subscribes to the node using the supplied jid.  The
 * bare jid portion of this one must match the jid for the connection.
 *
 * Please note that the {@link Subscription.State} should be checked
 * on return since more actions may be required by the caller.
 * {@link Subscription.State#pending} - The owner must approve the subscription
 * request before messages will be received.
 * {@link Subscription.State#unconfigured} - If the {@link Subscription#isConfigRequired()} is true,
 * the caller must configure the subscription before messages will be received.  If it is false
 * the caller can configure it but is not required to do so.
 *
 * @param jidString The jid to subscribe as.
 * @return The subscription
 * @throws XMPPErrorException if there was an XMPP error returned.
 * @throws NoResponseException if there was no response from the remote entity.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 * @throws IllegalArgumentException if the provided string is not a valid JID.
 * @deprecated use {@link #subscribe(Jid)} instead.
 */
@Deprecated
// TODO: Remove in Smack 4.5.
public Subscription subscribe(String jidString) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    Jid jid;
    try {
        jid = JidCreate.from(jidString);
    } catch (XmppStringprepException e) {
        throw new IllegalArgumentException(e);
    }
    return subscribe(jid);
}