org.jxmpp.stringprep.XmppStringprepException Java Examples

The following examples show how to use org.jxmpp.stringprep.XmppStringprepException. 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: RosterTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that roster pushes with invalid from are ignored.
 * @throws XmppStringprepException if the provided string is invalid.
 *
 * @see <a href="http://xmpp.org/rfcs/rfc6121.html#roster-syntax-actions-push">RFC 6121, Section 2.1.6</a>
 */
@Test
public void testIgnoreInvalidFrom() throws XmppStringprepException {
    final BareJid spammerJid = JidCreate.entityBareFrom("[email protected]");
    RosterPacket packet = new RosterPacket();
    packet.setType(Type.set);
    packet.setTo(connection.getUser());
    packet.setFrom(JidCreate.entityBareFrom("[email protected]"));
    packet.addRosterItem(new Item(spammerJid, "Cool products!"));

    final String requestId = packet.getStanzaId();
    // Simulate receiving the roster push
    connection.processStanza(packet);

    // Smack should reply with an error IQ
    ErrorIQ errorIQ = connection.getSentPacket();
    assertEquals(requestId, errorIQ.getStanzaId());
    assertEquals(Condition.service_unavailable, errorIQ.getError().getCondition());

    assertNull("Contact was added to roster", Roster.getInstanceFor(connection).getEntry(spammerJid));
}
 
Example #3
Source File: Domainpart.java    From jxmpp with Apache License 2.0 6 votes vote down vote up
/**
 * Get the {@link Domainpart} representing the input String.
 *
 * @param domain the input String.
 * @param context the JXMPP context.
 * @return the domainpart.
 * @throws XmppStringprepException if an error occurs.
 */
public static Domainpart from(String domain, JxmppContext context) throws XmppStringprepException {
	if (domain == null) {
		throw new XmppStringprepException(domain, "Input 'domain' must not be null");
	}
	// TODO cache
	// RFC 6122 § 2.2 "If the domainpart includes a final character considered to be a label
	// separator (dot) by [IDNA2003] or [DNS], this character MUST be stripped …"
	if (domain.length() > 0 && domain.charAt(domain.length() - 1) == '.') {
		domain = domain.substring(0, domain.length() - 1);
	}
	domain = XmppStringPrepUtil.domainprep(domain, context);
	// First prep the String, then assure the limits of the *result*
	assertNotLongerThan1023BytesOrEmpty(domain);
	return new Domainpart(domain);
}
 
Example #4
Source File: IQResponseTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Test creating a error response based on an IQ request.
 * @throws XmppStringprepException if the provided string is invalid.
 */
@Test
public void testGeneratingValidErrorResponse() throws XmppStringprepException {
    final StanzaError error = StanzaError.getBuilder(StanzaError.Condition.bad_request).build();
    final IQ request = new TestIQ(ELEMENT, NAMESPACE);

    request.setType(IQ.Type.set);
    request.setFrom(JidCreate.from("sender@test/Smack"));
    request.setTo(JidCreate.from("receiver@test/Smack"));

    final IQ result = IQ.createErrorResponse(request, error);

    assertEquals(IQ.Type.error, result.getType());
    assertNotNull(result.getStanzaId());
    assertEquals(request.getStanzaId(), result.getStanzaId());
    assertEquals(request.getFrom(), result.getTo());
    assertEquals(error.toXML().toString(), result.getError().toXML().toString());
    // TODO this test was never valid
    // assertEquals(CHILD_ELEMENT, result.getChildElementXML());
}
 
Example #5
Source File: DigestMd5SaslTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
protected void runTest(boolean useAuthzid) throws SmackException, InterruptedException, XmppStringprepException {
    EntityBareJid authzid = null;
    if (useAuthzid) {
        authzid = JidCreate.entityBareFrom("[email protected]");
    }
    saslMechanism.authenticate("florian", "irrelevant", JidCreate.domainBareFrom("xmpp.org"), "secret", authzid, null);
    byte[] response = saslMechanism.evaluateChallenge(challengeBytes);
    String responseString = new String(response, StandardCharsets.UTF_8);
    String[] responseParts = responseString.split(",");
    Map<String, String> responsePairs = new HashMap<String, String>();
    for (String part : responseParts) {
        String[] keyValue = part.split("=", 2);
        String key = keyValue[0];
        String value = keyValue[1].replace("\"", "");
        responsePairs.put(key, value);
    }
    if (useAuthzid) {
      assertMapValue("authzid", "[email protected]", responsePairs);
    } else {
      assertTrue (!responsePairs.containsKey("authzid"));
    }
    assertMapValue("username", "florian", responsePairs);
    assertMapValue("realm", "xmpp.org", responsePairs);
    assertMapValue("digest-uri", "xmpp/xmpp.org", responsePairs);
    assertMapValue("qop", "auth", responsePairs);
}
 
Example #6
Source File: STUN.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Get a new STUN Server Address and port from the server.
 * If a error occurs or the server don't support STUN Service, null is returned.
 *
 * @param connection TODO javadoc me please
 * @return the STUN server address
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public static STUN getSTUNServer(XMPPConnection connection) throws NotConnectedException, InterruptedException {

    if (!connection.isConnected()) {
        return null;
    }

    STUN stunPacket = new STUN();
    DomainBareJid jid;
    try {
        jid = JidCreate.domainBareFrom(DOMAIN + "." + connection.getXMPPServiceDomain());
    } catch (XmppStringprepException e) {
        throw new AssertionError(e);
    }
    stunPacket.setTo(jid);

    StanzaCollector collector = connection.createStanzaCollectorAndSend(stunPacket);

    STUN response = collector.nextResult();

    // Cancel the collector.
    collector.cancel();

    return response;
}
 
Example #7
Source File: OmemoDeviceTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Test, if the equals() method works as intended.
 */
@Test
public void testEquals() {
    BareJid romeo, juliet, guyUnderTheBalcony;
    try {
        romeo = JidCreate.bareFrom("[email protected]");
        guyUnderTheBalcony = JidCreate.bareFrom("[email protected]/underTheBalcony");
        juliet = JidCreate.bareFrom("[email protected]");
    } catch (XmppStringprepException e) {
        Assert.fail(e.getMessage());
        return;
    }

    OmemoDevice r = new OmemoDevice(romeo, 1);
    OmemoDevice g = new OmemoDevice(guyUnderTheBalcony, 1);
    OmemoDevice r2 = new OmemoDevice(romeo, 2);
    OmemoDevice j = new OmemoDevice(juliet, 3);
    OmemoDevice j2 = new OmemoDevice(juliet, 1);

    assertTrue(r.equals(g));
    assertFalse(r.equals(r2));
    assertFalse(j.equals(j2));
    assertFalse(j2.equals(r2));
}
 
Example #8
Source File: XmppFileService.java    From xyTalk-pc with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void requestOfflineFile(org.jivesoftware.smack.packet.Message message) {
	// TODO 向离线文件机器人发送请求
	// 将接收到的离线文件消息,原封不动的发给离线文件机器人 ,
	//	离线机器人接收后,会立即将已存储的文件发过来,同时会发送一条消息回执,发送成功后,删除文件
	//	用户收到回执后,需要对聊天UI进行处理,注意:此时的fromJid是机器人,应处理为实际发送者,即senderFullJid
	Chat chat;
	try {
		chat = ChatManager.getInstanceFor(Launcher.connection).chatWith(JidCreate.entityBareFrom(Launcher.OFFLINEFILEROBOTJID));
        
		chat.send(message); //发送请求到机器人,然后机器人会把文件发给我
		OfflineFile of = (OfflineFile)message.getExtension(OfflineFile.NAMESPACE);
		offlineFileJidMap.put(of.getFileName(), of.getSenderFullJid());
		DebugUtil.debug( "send offlinefile request:"+ message.toXML());	
		
	} catch (XmppStringprepException |NotConnectedException | InterruptedException e) {
		
	}
}
 
Example #9
Source File: IQResponseTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * According to <a href="http://xmpp.org/rfcs/rfc3920.html#stanzas-semantics-iq"
 * >RFC3920: IQ Semantics</a> we shouldn't respond to an IQ of type error.
 * @throws XmppStringprepException if the provided string is invalid.
 */
@Test
public void testGeneratingErrorBasedOnError() throws XmppStringprepException {
    final StanzaError error = StanzaError.getBuilder(StanzaError.Condition.bad_request).build();
    final IQ request = new TestIQ(ELEMENT, NAMESPACE);

    request.setType(IQ.Type.error);
    request.setFrom(JidCreate.from("sender@test/Smack"));
    request.setTo(JidCreate.from("receiver@test/Smack"));
    request.setError(error);

    try {
        IQ.createErrorResponse(request, error);
    }
    catch (IllegalArgumentException e) {
        return;
    }

    fail("It shouldn't be possible to generate a response for a error IQ!");
}
 
Example #10
Source File: RosterManager.java    From mangosta-android with Apache License 2.0 6 votes vote down vote up
public void removeContact(String jidString)
        throws SmackException.NotLoggedInException, InterruptedException,
        SmackException.NotConnectedException, XMPPException.XMPPErrorException,
        SmackException.NoResponseException, XmppStringprepException {
    Roster roster = Roster.getInstanceFor(XMPPSession.getInstance().getXMPPConnection());
    if (!roster.isLoaded()) {
        roster.reloadAndWait();
    }

    BareJid jid = JidCreate.bareFrom(jidString);
    roster.removeEntry(roster.getEntry(jid));

    Presence presence = new Presence(Presence.Type.unsubscribe);
    presence.setTo(JidCreate.from(jidString));
    XMPPSession.getInstance().sendStanza(presence);
}
 
Example #11
Source File: JidCreate.java    From jxmpp with Apache License 2.0 6 votes vote down vote up
/**
 * Get a domain bare JID.
 *
 * @param jid the JID String.
 * @param context the JXMPP context.
 * @return a domain bare JID.
 * @throws XmppStringprepException if an error occurs.
 */
public static DomainBareJid domainBareFrom(String jid, JxmppContext context) throws XmppStringprepException {
	DomainBareJid domainJid;
	if (context.isCachingEnabled()) {
		domainJid = DOMAINJID_CACHE.lookup(jid);
		if (domainJid != null) {
			return domainJid;
		}
	}

	String domain = XmppStringUtils.parseDomain(jid);
	try {
		domainJid = new DomainpartJid(domain, context);
	} catch (XmppStringprepException e) {
		throw new XmppStringprepException(jid, e);
	}

	if (context.isCachingEnabled()) {
		DOMAINJID_CACHE.put(jid, domainJid);
	}
	return domainJid;
}
 
Example #12
Source File: DataProvider.java    From XMPPSample_Studio with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public static MyListWrapper<MessageItem> getMessages(String jid) throws XmppStringprepException {
	if (get().messages.containsKey(JidCreate.domainBareFrom(jid))) {
		return get().messages.get(JidCreate.domainBareFrom(jid));
	}

	MyListWrapper<MessageItem> msgs = null;
	try {
		msgs = new MyListWrapper(DatabaseHelper.getInstance(LiveApp.get())
				.getDao(MessageItem.class)
				.queryForEq("opponent", JidCreate.domainBareFrom(jid)));
	} catch (SQLException e) {
		msgs = new MyListWrapper<MessageItem>();
	}
	get().messages.put((jid), msgs);
	return msgs;
}
 
Example #13
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 #14
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 #15
Source File: ChatArgumentsPlugin.java    From Spark with Apache License 2.0 6 votes vote down vote up
@Override
public void initialize() {
       EntityBareJid start_chat_jid = null;
       try {
           start_chat_jid = JidCreate.entityBareFromUnescaped(Spark.getArgumentValue("start_chat_jid"));
       } catch (XmppStringprepException e1) {
       }
       EntityBareJid start_chat_muc = null;
       try {
           start_chat_muc = JidCreate.entityBareFromUnescaped(Spark.getArgumentValue("start_chat_muc"));
       } catch (XmppStringprepException e) {
       }

       if (start_chat_jid != null) {
           Localpart nickname = start_chat_jid.getLocalpart();
           SparkManager.getChatManager().createChatRoom(start_chat_jid, nickname.toString(), start_chat_jid.toString());
       }

       if (start_chat_muc != null) {
           ConferenceUtils.joinConferenceOnSeperateThread(start_chat_muc, start_chat_muc, null);
       }

   }
 
Example #16
Source File: JidCreate.java    From jxmpp with Apache License 2.0 5 votes vote down vote up
/**
 * Get a {@link Jid} from the given String.
 *
 * @param jidString the input String.
 * @param context the JXMPP context.
 * @return the Jid represented by the input String.
 * @throws XmppStringprepException if an error occurs.
 * @see #from(CharSequence)
 */
public static Jid from(String jidString, JxmppContext context) throws XmppStringprepException {
	String localpart = XmppStringUtils.parseLocalpart(jidString);
	String domainpart = XmppStringUtils.parseDomain(jidString);
	String resource = XmppStringUtils.parseResource(jidString);
	try {
		return from(localpart, domainpart, resource, context);
	} catch (XmppStringprepException e) {
		throw new XmppStringprepException(jidString, e);
	}
}
 
Example #17
Source File: LibIdnXmppStringprep.java    From jxmpp with Apache License 2.0 5 votes vote down vote up
@Override
public String resourceprep(String string) throws XmppStringprepException {
	try {
		// Allow unassigned codepoints as of RFC6122 B.2
		return Stringprep.resourceprep(string, true);
	} catch (StringprepException e) {
		throw new XmppStringprepException(string, e);
	}
}
 
Example #18
Source File: SimpleXmppStringprep.java    From jxmpp with Apache License 2.0 5 votes vote down vote up
@Override
public String resourceprep(String string) throws XmppStringprepException {
	// rfc6122-bis specifies that resourceprep uses saslprep-bis OpaqueString Profile which says that
	// "Uppercase and titlecase characters MUST NOT be mapped to their lowercase equivalents."

	// TODO apply Unicode Normalization Form C (NFC) with help of java.text.Normalize
	// but unfortunately this is API is only available on Android API 9 or higher and Smack is currently API 8
	return string;
}
 
Example #19
Source File: GroupChatParticipantList.java    From Spark with Apache License 2.0 5 votes vote down vote up
protected void unbanUser(String jidString) {
	try {
	    Jid jid = JidCreate.from(jidString);
		chat.grantMembership(jid);
	} catch (XMPPException | SmackException | XmppStringprepException | InterruptedException e) {
	    groupChatRoom.getTranscriptWindow().
	    insertNotificationMessage("No can do "+e.getMessage(), ChatManager.ERROR_COLOR);
	}
}
 
Example #20
Source File: Domainpart.java    From jxmpp with Apache License 2.0 5 votes vote down vote up
/**
 * Get a {@link Domainpart} from a given {@link CharSequence} or {@code null} if the input is not a valid domainpart.
 *
 * @param cs the input CharSequence
 * @return a Domainpart or {@code null}
 */
public static Domainpart fromOrNull(CharSequence cs) {
	try {
		return from(cs.toString());
	} catch (XmppStringprepException e) {
		return null;
	}
}
 
Example #21
Source File: LibIdnXmppStringprep.java    From jxmpp with Apache License 2.0 5 votes vote down vote up
@Override
public String localprep(String string) throws XmppStringprepException {
	try {
		// Allow unassigned codepoints as of RFC6122 A.2
		return Stringprep.nodeprep(string, true);
	} catch (StringprepException e) {
		throw new XmppStringprepException(string, e);
	}
}
 
Example #22
Source File: Icu4jXmppStringprep.java    From jxmpp with Apache License 2.0 5 votes vote down vote up
@Override
public String resourceprep(String string) throws XmppStringprepException {
	try {
		return RESOURCEPREP.prepare(string, StringPrep.DEFAULT);
	} catch (StringPrepParseException e) {
		throw new XmppStringprepException(string, e);
	}
}
 
Example #23
Source File: JidCreateTest.java    From jxmpp with Apache License 2.0 5 votes vote down vote up
@Test
public void entityBareFromUnescapedTest() throws XmppStringprepException {
	EntityBareJid entityBareJid = JidCreate.entityBareFromUnescaped("foo@[email protected]/baz");

	// Tricky question. Currently yields '[email protected]'. Domainparts are U-Labels, so this may be correct, even
	// if it is not a valid DNS label/name.
	Domainpart domainpart = entityBareJid.getDomain();
	assertEquals(Domainpart.from("[email protected]"), domainpart);

	Localpart localpart = entityBareJid.getLocalpart();
	assertEquals(Localpart.from("foo"), localpart);
}
 
Example #24
Source File: Resourcepart.java    From jxmpp with Apache License 2.0 5 votes vote down vote up
/**
 * Get a {@link Resourcepart} from a given {@link CharSequence} or {@code null} if the input is not a valid resourcepart.
 *
 * @param cs the input CharSequence
 * @return a Resourcepart or {@code null}
 */
public static Resourcepart fromOrNull(CharSequence cs) {
	try {
		return from(cs.toString());
	} catch (XmppStringprepException e) {
		return null;
	}
}
 
Example #25
Source File: JidCreateTest.java    From jxmpp with Apache License 2.0 5 votes vote down vote up
@Test
public void jidResourcepartWithAtSignTest() throws XmppStringprepException {
	Jid jid = JidCreate.from("a.example.com/[email protected]");

	assertEquals(Domainpart.from("a.example.com"), jid.getDomain());
	assertEquals(Resourcepart.from("[email protected]"), jid.getResourceOrNull());
}
 
Example #26
Source File: JidCreate.java    From jxmpp with Apache License 2.0 5 votes vote down vote up
/**
 * Get a {@link Jid} 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 Jid fromOrNull(CharSequence cs) {
	try {
		return from(cs);
	} catch (XmppStringprepException e) {
		return null;
	}
}
 
Example #27
Source File: Jid.java    From Pix-Art-Messenger with GNU General Public License v3.0 5 votes vote down vote up
static Jid ofDomain(CharSequence domain) {
    try {
        return new WrappedJid(JidCreate.domainBareFrom(domain));
    } catch (XmppStringprepException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example #28
Source File: Localpart.java    From jxmpp with Apache License 2.0 5 votes vote down vote up
/**
 * Get a {@link Localpart} from a given {@link CharSequence} or {@code null} if the input is not a valid localpart.
 *
 * @param cs the input CharSequence
 * @return a Localpart or {@code null}
 */
public static Localpart formUnescapedOrNull(CharSequence cs) {
	try {
		return fromUnescaped(cs);
	} catch (XmppStringprepException e) {
		return null;
	}
}
 
Example #29
Source File: Jid.java    From Pix-Art-Messenger with GNU General Public License v3.0 5 votes vote down vote up
static Jid ofLocalAndDomain(CharSequence local, CharSequence domain) {
    try {
        return new WrappedJid(
                JidCreate.bareFrom(
                        Localpart.fromUnescaped(local.toString()),
                        Domainpart.from(domain.toString())
                )
        );
    } catch (XmppStringprepException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example #30
Source File: JID.java    From desktopclient-java with GNU General Public License v3.0 5 votes vote down vote up
public Jid toSmack() {
    try {
        return JidCreate.from(this.string());
    } catch (XmppStringprepException ex) {
        LOGGER.log(Level.WARNING, "could not convert to smack", ex);
        throw new RuntimeException("Not even a simple Jid?");
    }
}