Search in sources :

Example 76 with XmlPullParser

use of org.jivesoftware.smack.xml.XmlPullParser in project Smack by igniterealtime.

the class JivePropertiesExtensionProvider method parse.

/**
 * Parse a properties sub-packet. If any errors occur while de-serializing Java object
 * properties, an exception will be printed and not thrown since a thrown exception will shut
 * down the entire connection. ClassCastExceptions will occur when both the sender and receiver
 * of the stanza don't have identical versions of the same class.
 * <p>
 * Note that you have to explicitly enabled Java object deserialization with @{link
 * {@link JivePropertiesManager#setJavaObjectEnabled(boolean)}
 *
 * @param parser the XML parser, positioned at the start of a properties sub-packet.
 * @return a map of the properties.
 * @throws IOException if an I/O error occurred.
 * @throws XmlPullParserException if an error in the XML parser occurred.
 */
@SuppressWarnings("BanSerializableRead")
@Override
public JivePropertiesExtension parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) throws XmlPullParserException, IOException {
    Map<String, Object> properties = new HashMap<>();
    while (true) {
        XmlPullParser.Event eventType = parser.next();
        if (eventType == XmlPullParser.Event.START_ELEMENT && parser.getName().equals("property")) {
            // Parse a property
            boolean done = false;
            String name = null;
            String type = null;
            String valueText = null;
            Object value = null;
            while (!done) {
                eventType = parser.next();
                if (eventType == XmlPullParser.Event.START_ELEMENT) {
                    String elementName = parser.getName();
                    if (elementName.equals("name")) {
                        name = parser.nextText();
                    } else if (elementName.equals("value")) {
                        type = parser.getAttributeValue("", "type");
                        valueText = parser.nextText();
                    }
                } else if (eventType == XmlPullParser.Event.END_ELEMENT) {
                    if (parser.getName().equals("property")) {
                        if ("integer".equals(type)) {
                            value = Integer.valueOf(valueText);
                        } else if ("long".equals(type)) {
                            value = Long.valueOf(valueText);
                        } else if ("float".equals(type)) {
                            value = Float.valueOf(valueText);
                        } else if ("double".equals(type)) {
                            value = Double.valueOf(valueText);
                        } else if ("boolean".equals(type)) {
                            // CHECKSTYLE:OFF
                            value = Boolean.valueOf(valueText);
                        // CHECKSTYLE:ON
                        } else if ("string".equals(type)) {
                            value = valueText;
                        } else if ("java-object".equals(type)) {
                            if (JivePropertiesManager.isJavaObjectEnabled()) {
                                try {
                                    byte[] bytes = Base64.decode(valueText);
                                    ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
                                    value = in.readObject();
                                } catch (Exception e) {
                                    LOGGER.log(Level.SEVERE, "Error parsing java object", e);
                                }
                            } else {
                                LOG_OBJECT_NOT_ENABLED.once(() -> LOGGER.severe("JavaObject is not enabled. Enable with JivePropertiesManager.setJavaObjectEnabled(true)"));
                            }
                        }
                        if (name != null && value != null) {
                            properties.put(name, value);
                        }
                        done = true;
                    }
                }
            }
        } else if (eventType == XmlPullParser.Event.END_ELEMENT) {
            if (parser.getName().equals(JivePropertiesExtension.ELEMENT)) {
                break;
            }
        }
    }
    return new JivePropertiesExtension(properties);
}
Also used : HashMap(java.util.HashMap) ByteArrayInputStream(java.io.ByteArrayInputStream) XmlPullParser(org.jivesoftware.smack.xml.XmlPullParser) IOException(java.io.IOException) XmlPullParserException(org.jivesoftware.smack.xml.XmlPullParserException) JivePropertiesExtension(org.jivesoftware.smackx.jiveproperties.packet.JivePropertiesExtension) ObjectInputStream(java.io.ObjectInputStream)

Example 77 with XmlPullParser

use of org.jivesoftware.smack.xml.XmlPullParser in project Smack by igniterealtime.

the class RosterTest method testSimpleRosterPush.

/**
 * Test a simple roster push according to the example in
 * <a href="http://xmpp.org/internet-drafts/draft-ietf-xmpp-3921bis-03.html#roster-syntax-actions-push"
 *     >RFC3921bis-03: Roster Push</a>.
 * @throws Throwable in case a throwable is thrown.
 */
@Test
public void testSimpleRosterPush() throws Throwable {
    final BareJid contactJID = JidCreate.entityBareFrom("nurse@example.com");
    assertNotNull("Can't get the roster from the provided connection!", roster);
    final StringBuilder sb = new StringBuilder();
    sb.append("<iq id=\"rostertest1\" type=\"set\" ").append("to=\"").append(connection.getUser()).append("\">").append("<query xmlns=\"jabber:iq:roster\">").append("<item jid=\"").append(contactJID).append("\"/>").append("</query>").append("</iq>");
    final XmlPullParser parser = TestUtils.getIQParser(sb.toString());
    final IQ rosterPush = PacketParserUtils.parseIQ(parser);
    initRoster();
    rosterListener.reset();
    // Simulate receiving the roster push
    connection.processStanza(rosterPush);
    rosterListener.waitUntilInvocationOrTimeout();
    // Verify the roster entry of the new contact
    final RosterEntry addedEntry = roster.getEntry(contactJID);
    assertNotNull("The new contact wasn't added to the roster!", addedEntry);
    assertTrue("The roster listener wasn't invoked for the new contact!", rosterListener.getAddedAddresses().contains(contactJID));
    assertSame("Setup wrong default subscription status!", ItemType.none, addedEntry.getType());
    assertSame("The new contact shouldn't be member of any group!", 0, addedEntry.getGroups().size());
    // Verify the unchanged roster items
    verifyRomeosEntry(roster.getEntry(JidCreate.entityBareFrom("romeo@example.net")));
    verifyMercutiosEntry(roster.getEntry(JidCreate.entityBareFrom("mercutio@example.com")));
    verifyBenvoliosEntry(roster.getEntry(JidCreate.entityBareFrom("benvolio@example.net")));
    assertSame("Wrong number of roster entries.", 4, roster.getEntries().size());
}
Also used : BareJid(org.jxmpp.jid.BareJid) XmlPullParser(org.jivesoftware.smack.xml.XmlPullParser) ErrorIQ(org.jivesoftware.smack.packet.ErrorIQ) IQ(org.jivesoftware.smack.packet.IQ) Test(org.junit.Test)

Example 78 with XmlPullParser

use of org.jivesoftware.smack.xml.XmlPullParser in project Smack by igniterealtime.

the class RosterTest method testEmptyGroupRosterPush.

/**
 * Test processing a roster push with an empty group is equivalent with providing
 * no group.
 *
 * @throws Throwable in case a throwable is thrown.
 * @see <a href="http://www.igniterealtime.org/issues/browse/SMACK-294">SMACK-294</a>
 */
@Test
public void testEmptyGroupRosterPush() throws Throwable {
    final BareJid contactJID = JidCreate.entityBareFrom("nurse@example.com");
    assertNotNull("Can't get the roster from the provided connection!", roster);
    final StringBuilder sb = new StringBuilder();
    sb.append("<iq id=\"rostertest2\" type=\"set\" ").append("to=\"").append(connection.getUser()).append("\">").append("<query xmlns=\"jabber:iq:roster\">").append("<item jid=\"").append(contactJID).append("\">").append("<group></group>").append("</item>").append("</query>").append("</iq>");
    final XmlPullParser parser = TestUtils.getIQParser(sb.toString());
    final IQ rosterPush = PacketParserUtils.parseIQ(parser);
    initRoster();
    rosterListener.reset();
    // Simulate receiving the roster push
    connection.processStanza(rosterPush);
    rosterListener.waitUntilInvocationOrTimeout();
    // Verify the roster entry of the new contact
    final RosterEntry addedEntry = roster.getEntry(contactJID);
    assertNotNull("The new contact wasn't added to the roster!", addedEntry);
    assertTrue("The roster listener wasn't invoked for the new contact!", rosterListener.getAddedAddresses().contains(contactJID));
    assertSame("Setup wrong default subscription status!", ItemType.none, addedEntry.getType());
    assertSame("The new contact shouldn't be member of any group!", 0, addedEntry.getGroups().size());
    // Verify the unchanged roster items
    verifyRomeosEntry(roster.getEntry(JidCreate.entityBareFrom("romeo@example.net")));
    verifyMercutiosEntry(roster.getEntry(JidCreate.entityBareFrom("mercutio@example.com")));
    verifyBenvoliosEntry(roster.getEntry(JidCreate.entityBareFrom("benvolio@example.net")));
    assertSame("Wrong number of roster entries.", 4, roster.getEntries().size());
}
Also used : BareJid(org.jxmpp.jid.BareJid) XmlPullParser(org.jivesoftware.smack.xml.XmlPullParser) ErrorIQ(org.jivesoftware.smack.packet.ErrorIQ) IQ(org.jivesoftware.smack.packet.IQ) Test(org.junit.Test)

Example 79 with XmlPullParser

use of org.jivesoftware.smack.xml.XmlPullParser in project Smack by igniterealtime.

the class MessageMarkupTest method nestedBlockQuoteTest.

@Test
public void nestedBlockQuoteTest() throws Exception {
    String xml = "<markup xmlns='urn:xmpp:markup:0'>" + "<bquote start='0' end='57'/>" + "<bquote start='11' end='34'/>" + "</markup>";
    MarkupElement.Builder m = MarkupElement.getBuilder();
    m.setBlockQuote(0, 57);
    m.setBlockQuote(11, 34);
    assertXmlSimilar(xml, m.build().toXML().toString());
    XmlPullParser parser = TestUtils.getParser(xml);
    MarkupElement parsed = new MarkupElementProvider().parse(parser);
    List<MarkupElement.MarkupChildElement> children = parsed.getChildElements();
    assertEquals(2, children.size());
    BlockQuoteElement q1 = (BlockQuoteElement) children.get(0);
    BlockQuoteElement q2 = (BlockQuoteElement) children.get(1);
    assertEquals(0, q1.getStart());
    assertEquals(57, q1.getEnd());
    assertEquals(11, q2.getStart());
    assertEquals(34, q2.getEnd());
}
Also used : MarkupElementProvider(org.jivesoftware.smackx.message_markup.provider.MarkupElementProvider) BlockQuoteElement(org.jivesoftware.smackx.message_markup.element.BlockQuoteElement) XmlPullParser(org.jivesoftware.smack.xml.XmlPullParser) MarkupElement(org.jivesoftware.smackx.message_markup.element.MarkupElement) Test(org.junit.jupiter.api.Test)

Example 80 with XmlPullParser

use of org.jivesoftware.smack.xml.XmlPullParser in project Smack by igniterealtime.

the class MessageMarkupTest method codeTest.

@Test
public void codeTest() throws Exception {
    String xml = "<markup xmlns='urn:xmpp:markup:0'>" + "<span start='9' end='15'>" + "<code/>" + "</span>" + "</markup>";
    MarkupElement.Builder m = MarkupElement.getBuilder();
    m.setCode(9, 15);
    assertXmlSimilar(xml, m.build().toXML().toString());
    XmlPullParser parser = TestUtils.getParser(xml);
    MarkupElement parsed = new MarkupElementProvider().parse(parser);
    List<MarkupElement.MarkupChildElement> children = parsed.getChildElements();
    assertEquals(1, children.size());
    SpanElement spanElement = (SpanElement) children.get(0);
    assertEquals(9, spanElement.getStart());
    assertEquals(15, spanElement.getEnd());
    assertEquals(1, spanElement.getStyles().size());
    assertEquals(SpanElement.SpanStyle.code, spanElement.getStyles().iterator().next());
}
Also used : SpanElement(org.jivesoftware.smackx.message_markup.element.SpanElement) MarkupElementProvider(org.jivesoftware.smackx.message_markup.provider.MarkupElementProvider) XmlPullParser(org.jivesoftware.smack.xml.XmlPullParser) MarkupElement(org.jivesoftware.smackx.message_markup.element.MarkupElement) Test(org.junit.jupiter.api.Test)

Aggregations

XmlPullParser (org.jivesoftware.smack.xml.XmlPullParser)139 Test (org.junit.jupiter.api.Test)69 Message (org.jivesoftware.smack.packet.Message)15 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)15 Date (java.util.Date)12 ExtensionElement (org.jivesoftware.smack.packet.ExtensionElement)11 Jid (org.jxmpp.jid.Jid)11 IOException (java.io.IOException)10 ArrayList (java.util.ArrayList)10 XmlPullParserException (org.jivesoftware.smack.xml.XmlPullParserException)10 EnumSource (org.junit.jupiter.params.provider.EnumSource)9 IQ (org.jivesoftware.smack.packet.IQ)8 Test (org.junit.Test)8 MarkupElement (org.jivesoftware.smackx.message_markup.element.MarkupElement)7 MarkupElementProvider (org.jivesoftware.smackx.message_markup.provider.MarkupElementProvider)7 XmlElement (org.jivesoftware.smack.packet.XmlElement)5 HashMap (java.util.HashMap)4 HashSet (java.util.HashSet)4 NamedElement (org.jivesoftware.smack.packet.NamedElement)4 HttpOverXmppResp (org.jivesoftware.smackx.hoxt.packet.HttpOverXmppResp)4