org.jivesoftware.smack.packet.ExtensionElement Java Examples

The following examples show how to use org.jivesoftware.smack.packet.ExtensionElement. 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: ChatService.java    From xyTalk-pc with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void sendMessage(String roomId, String content,ExtensionElement ext) {
	EntityBareJid jid = null;
	try {
		jid = JidCreate.entityBareFrom(roomId);
	} catch (XmppStringprepException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
	Chat chat = ChatManager.getInstanceFor(Launcher.connection).chatWith(jid);

	org.jivesoftware.smack.packet.Message message = new org.jivesoftware.smack.packet.Message();
	message.setType(Type.chat);
	message.addExtension(ext);
	message.setBody(content);
	try {
		chat.send(message);
		DebugUtil.debug("chat.sendMessage::" + message.toString());
	} catch (NotConnectedException | InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

}
 
Example #2
Source File: JingleContentInfoProvider.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Parse a JingleDescription.Audio extension.
 */
@Override
public ExtensionElement parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) {
    ExtensionElement result = null;

    if (audioInfo != null) {
        result = audioInfo;
    } else {
        String elementName = parser.getName();

        // Try to get an Audio content info
        ContentInfo mi = ContentInfo.Audio.fromString(elementName);
        if (mi != null) {
            result = new JingleContentInfo.Audio(mi);
        }
    }
    return result;
}
 
Example #3
Source File: AMPExtensionTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Test
public void isCorrectFromXmlErrorHandling() throws Exception {
    AMPExtensionProvider ampProvider = new AMPExtensionProvider();
    XmlPullParser parser = PacketParserUtils.getParserFor(INCORRECT_RECEIVING_STANZA_STREAM);

    assertEquals(XmlPullParser.Event.START_ELEMENT, parser.next());
    assertEquals(AMPExtension.ELEMENT, parser.getName());

    ExtensionElement extension = ampProvider.parse(parser);
    assertTrue(extension instanceof AMPExtension);
    AMPExtension amp = (AMPExtension) extension;

    assertEquals(0, amp.getRulesCount());
    assertEquals(AMPExtension.Status.alert, amp.getStatus());
    assertEquals("[email protected]/elsinore", amp.getFrom());
    assertEquals("[email protected]", amp.getTo());
}
 
Example #4
Source File: Base64BinaryChunkProviderTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Test
public void isLatsChunkParsedCorrectly() throws Exception {
    String base64Text = "2uPzi9u+tVWJd+e+y1AAAAABJRU5ErkJggg==";
    String string = "<chunk xmlns='urn:xmpp:http' streamId='Stream0001' nr='1' last='true'>" + base64Text + "</chunk>";

    Base64BinaryChunkProvider provider = new Base64BinaryChunkProvider();
    XmlPullParser parser = PacketParserUtils.getParserFor(string);

    ExtensionElement extension = provider.parse(parser);
    assertTrue(extension instanceof Base64BinaryChunk);

    Base64BinaryChunk chunk = (Base64BinaryChunk) extension;
    assertEquals("Stream0001", chunk.getStreamId());
    assertTrue(chunk.isLast());
    assertEquals(base64Text, chunk.getText());
    assertEquals(1, chunk.getNr());
}
 
Example #5
Source File: LogPacket.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the SIP Setting for the user.
 *
 * @param connection the XMPPConnection to use.
 * @return the information for about the latest Spark Client.
 * @throws XMPPException
 */
public static LogPacket logEvent(XMPPConnection connection, ExtensionElement ext)
        throws XMPPException, SmackException.NotConnectedException
{

    LogPacket lp = new LogPacket();
    lp.addExtension(ext);

    lp.setTo(NAME + "." + connection.getXMPPServiceDomain());
    lp.setType(IQ.Type.set);

    StanzaCollector collector = connection
            .createStanzaCollector(new PacketIDFilter(lp.getPacketID()));
    connection.sendStanza(lp);

    LogPacket response = (LogPacket)collector
            .nextResult(SmackConfiguration.getDefaultPacketReplyTimeout());

    // Cancel the collector.
    collector.cancel();
    if (response == null) {
        SmackException.NoResponseException.newWith( connection, collector );
    }
    XMPPException.XMPPErrorException.ifHasErrorThenThrow( response );
    return response;
}
 
Example #6
Source File: OXInstantMessagingManager.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Send an OX message to a {@link OpenPgpContact}. The message will be encrypted to all active keys of the contact,
 * as well as all of our active keys. The message is also signed with our key.
 *
 * @param contact contact capable of OpenPGP for XMPP: Instant Messaging.
 * @param body message body.
 *
 * @return {@link OpenPgpMetadata} about the messages encryption + signatures.
 *
 * @throws InterruptedException if the thread is interrupted
 * @throws IOException IO is dangerous
 * @throws SmackException.NotConnectedException if we are not connected
 * @throws SmackException.NotLoggedInException if we are not logged in
 * @throws PGPException PGP is brittle
 */
public OpenPgpMetadata sendOxMessage(OpenPgpContact contact, CharSequence body)
        throws InterruptedException, IOException,
        SmackException.NotConnectedException, SmackException.NotLoggedInException, PGPException {
    MessageBuilder messageBuilder = connection()
            .getStanzaFactory()
            .buildMessageStanza()
            .to(contact.getJid());

    Message.Body mBody = new Message.Body(null, body.toString());
    OpenPgpMetadata metadata = addOxMessage(messageBuilder, contact, Collections.<ExtensionElement>singletonList(mBody));

    Message message = messageBuilder.build();
    ChatManager.getInstanceFor(connection()).chatWith(contact.getJid().asEntityBareJidIfPossible()).send(message);

    return metadata;
}
 
Example #7
Source File: StatusBar.java    From Spark with Apache License 2.0 6 votes vote down vote up
public void changeAvailability(final Presence presence) {
	// SPARK-1524: if we were reconnected because of the error
	// then we get presence with the mode == null. 
	if (presence.getMode() == null)
		return;

	if ((presence.getMode() == currentPresence.getMode()) && (presence.getType() == currentPresence.getType()) && (presence.getStatus().equals(currentPresence.getStatus()))) {
		ExtensionElement pe = presence.getExtension("x", "vcard-temp:x:update");
		if (pe != null) {
			// Update VCard
			loadVCard();
		}
		return;
	}
	currentPresence = presence;

	SwingUtilities.invokeLater(changePresenceRunnable);
}
 
Example #8
Source File: OpenPgpElementTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Test
public void signElementProviderTest() throws Exception {
    String expected =
            "<sign xmlns='urn:xmpp:openpgp:0'>" +
                    "<to jid='[email protected]'/>" +
                    "<to jid='[email protected]'/>" +
                    "<time stamp='2014-07-10T15:06:00.000+00:00'/>" +
                    "<payload>" +
                    "<body xmlns='jabber:client' xml:lang='en'>Hello World!</body>" +
                    "</payload>" +
                    "</sign>";

    List<ExtensionElement> payload = new ArrayList<>();
    payload.add(new Message.Body("en", "Hello World!"));
    SignElement element = new SignElement(recipients, testDate, payload);

    assertXmlSimilar(expected, element.toXML().toString());

    XmlPullParser parser = TestUtils.getParser(expected);
    SignElement parsed = (SignElement) OpenPgpContentElementProvider.parseOpenPgpContentElement(parser);

    assertEquals(element.getTimestamp(), parsed.getTimestamp());
    assertEquals(element.getTo(), parsed.getTo());
    assertEquals(element.getExtensions(), parsed.getExtensions());
}
 
Example #9
Source File: AccountManager.java    From Smack with Apache License 2.0 6 votes vote down vote up
public boolean isSupported()
                throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    XMPPConnection connection = connection();

    ExtensionElement extensionElement = connection.getFeature(Registration.Feature.ELEMENT,
                    Registration.Feature.NAMESPACE);
    if (extensionElement != null) {
        return true;
    }

    // Fallback to disco#info only if this connection is authenticated, as otherwise we won't have an full JID and
    // won't be able to do IQs.
    if (connection.isAuthenticated()) {
        return ServiceDiscoveryManager.getInstanceFor(connection).serverSupportsFeature(Registration.NAMESPACE);
    }

    return false;
}
 
Example #10
Source File: EmbeddedExtensionProvider.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Override
public final PE parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) throws XmlPullParserException, IOException, SmackParsingException {
    final String namespace = parser.getNamespace();
    final String name = parser.getName();
    final int attributeCount = parser.getAttributeCount();
    Map<String, String> attMap = new HashMap<>(attributeCount);

    for (int i = 0; i < attributeCount; i++) {
        attMap.put(parser.getAttributeName(i), parser.getAttributeValue(i));
    }

    List<ExtensionElement> extensions = new ArrayList<>();
    XmlPullParser.Event event;
    do {
        event = parser.next();

        if (event == XmlPullParser.Event.START_ELEMENT)
            PacketParserUtils.addExtensionElement(extensions, parser, xmlEnvironment);
    }
    while (!(event == XmlPullParser.Event.END_ELEMENT && parser.getDepth() == initialDepth));

    return createReturnExtension(name, namespace, attMap, extensions);
}
 
Example #11
Source File: Node.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Override
        public void processStanza(Stanza packet) {
// CHECKSTYLE:OFF
            EventElement event = (EventElement) packet.getExtensionElement("event", PubSubNamespace.event.getXmlns());

            List<ExtensionElement> extList = event.getExtensions();

            if (extList.get(0).getElementName().equals(PubSubElementType.PURGE_EVENT.getElementName())) {
                listener.handlePurge();
            }
            else {
                ItemsExtension itemsElem = (ItemsExtension)event.getEvent();
                @SuppressWarnings("unchecked")
                Collection<RetractItem> pubItems = (Collection<RetractItem>) itemsElem.getItems();
                List<String> items = new ArrayList<>(pubItems.size());

                for (RetractItem item : pubItems) {
                    items.add(item.getId());
                }

                ItemDeleteEvent eventItems = new ItemDeleteEvent(itemsElem.getNode(), items, getSubscriptionIds(packet));
                listener.handleDeletedItems(eventItems);
            }
// CHECKSTYLE:ON
        }
 
Example #12
Source File: Node.java    From Smack with Apache License 2.0 6 votes vote down vote up
private List<Affiliation> getAffiliations(AffiliationNamespace affiliationsNamespace, List<ExtensionElement> additionalExtensions,
                Collection<ExtensionElement> returnedExtensions) throws NoResponseException, XMPPErrorException,
                NotConnectedException, InterruptedException {
    PubSubElementType pubSubElementType = affiliationsNamespace.type;

    PubSub pubSub = createPubsubPacket(Type.get, new NodeExtension(pubSubElementType, getId()));
    if (additionalExtensions != null) {
        for (ExtensionElement pe : additionalExtensions) {
            pubSub.addExtension(pe);
        }
    }
    PubSub reply = sendPubsubPacket(pubSub);
    if (returnedExtensions != null) {
        returnedExtensions.addAll(reply.getExtensions());
    }
    AffiliationsExtension affilElem = reply.getExtension(pubSubElementType);
    return affilElem.getAffiliations();
}
 
Example #13
Source File: EligibleForChatMarkerFilter.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * From XEP-0333, Protocol Format: The Chat Marker MUST have an 'id' which is the 'id' of the
 * message being marked.<br>
 * In order to make Chat Markers works together with XEP-0085 as it said in
 * 8.5 Interaction with Chat States, only messages with <code>active</code> chat
 * state are accepted.
 *
 * @param message to be analyzed.
 * @return true if the message contains a stanza Id.
 * @see <a href="http://xmpp.org/extensions/xep-0333.html">XEP-0333: Chat Markers</a>
 */
@Override
public boolean accept(Stanza message) {
    if (!message.hasStanzaIdSet()) {
        return false;
    }

    if (super.accept(message)) {
        ExtensionElement extension = message.getExtension(ChatStateManager.NAMESPACE);
        String chatStateElementName = extension.getElementName();

        ChatState state;
        try {
            state = ChatState.valueOf(chatStateElementName);
            return state == ChatState.active;
        }
        catch (Exception ex) {
            return false;
        }
    }

    return true;
}
 
Example #14
Source File: Node.java    From Smack with Apache License 2.0 6 votes vote down vote up
private List<Subscription> getSubscriptions(SubscriptionsNamespace subscriptionsNamespace, List<ExtensionElement> additionalExtensions,
                Collection<ExtensionElement> returnedExtensions)
                throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    PubSubElementType pubSubElementType = subscriptionsNamespace.type;

    PubSub pubSub = createPubsubPacket(Type.get, new NodeExtension(pubSubElementType, getId()));
    if (additionalExtensions != null) {
        for (ExtensionElement pe : additionalExtensions) {
            pubSub.addExtension(pe);
        }
    }
    PubSub reply = sendPubsubPacket(pubSub);
    if (returnedExtensions != null) {
        returnedExtensions.addAll(reply.getExtensions());
    }
    SubscriptionsExtension subElem = reply.getExtension(pubSubElementType);
    return subElem.getSubscriptions();
}
 
Example #15
Source File: RSMManager.java    From Smack with Apache License 2.0 6 votes vote down vote up
Collection<ExtensionElement> continuePage(int max,
                Collection<ExtensionElement> returnedExtensions,
                Collection<ExtensionElement> additionalExtensions) {
    if (returnedExtensions == null) {
        throw new IllegalArgumentException("returnedExtensions must no be null");
    }
    if (additionalExtensions == null) {
        additionalExtensions = new LinkedList<>();
    }
    RSMSet resultRsmSet = PacketUtil.extensionElementFrom(returnedExtensions, RSMSet.ELEMENT, RSMSet.NAMESPACE);
    if (resultRsmSet == null) {
        throw new IllegalArgumentException("returnedExtensions did not contain a RSMset");
    }
    RSMSet continuePageRsmSet = new RSMSet(max, resultRsmSet.getLast(), PageDirection.after);
    additionalExtensions.add(continuePageRsmSet);
    return additionalExtensions;
}
 
Example #16
Source File: KonMessageListener.java    From desktopclient-java with GNU General Public License v3.0 6 votes vote down vote up
private static Date getDelay(Message m) {
    // first: new XEP-0203 specification
    ExtensionElement delay = DelayInformation.from(m);

    // fallback: obsolete XEP-0091 specification
    if (delay == null) {
        delay = m.getExtension("x", "jabber:x:delay");
    }

    if (delay instanceof DelayInformation) {
        Date date = ((DelayInformation) delay).getStamp();
        if (date.after(new Date()))
            LOGGER.warning("delay time is in future: "+date);
        return date;
    }

    return null;
}
 
Example #17
Source File: FasteningElement.java    From Smack with Apache License 2.0 5 votes vote down vote up
private void addPayloads(XmlStringBuilder xml) {
    for (ExternalElement external : externalPayloads) {
        xml.append(external);
    }
    for (ExtensionElement wrapped : wrappedPayloads) {
        xml.append(wrapped);
    }
}
 
Example #18
Source File: PacketUtil.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Get a extension element from a collection.
 *
 * @param collection Collection of ExtensionElements.
 * @param element name of the targeted ExtensionElement.
 * @param namespace namespace of the targeted ExtensionElement.
 * @param <PE> Type of the ExtensionElement
 *
 * @return the extension element
 */
@SuppressWarnings("unchecked")
public static <PE extends ExtensionElement> PE extensionElementFrom(Collection<ExtensionElement> collection,
                String element, String namespace) {
    for (ExtensionElement packetExtension : collection) {
        if ((element == null || packetExtension.getElementName().equals(
                        element))
                        && packetExtension.getNamespace().equals(namespace)) {
            return (PE) packetExtension;
        }
    }
    return null;
}
 
Example #19
Source File: LeafNode.java    From Smack with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private <T extends Item> List<T> getItems(PubSub request,
                List<ExtensionElement> returnedExtensions) throws NoResponseException,
                XMPPErrorException, NotConnectedException, InterruptedException {
    PubSub result = pubSubManager.getConnection().createStanzaCollectorAndSend(request).nextResultOrThrow();
    ItemsExtension itemsElem = result.getExtension(PubSubElementType.ITEMS);
    if (returnedExtensions != null) {
        returnedExtensions.addAll(result.getExtensions());
    }
    return (List<T>) itemsElem.getItems();
}
 
Example #20
Source File: ClientUtils.java    From desktopclient-java with GNU General Public License v3.0 5 votes vote down vote up
public static MessageContent parseMessageContent(Message m, boolean decrypted) {
    MessageContent.Builder builder = new MessageContent.Builder();

    // parsing only default body
    String plainText = StringUtils.defaultString(m.getBody());
    String encrypted = "";

    if (!decrypted) {
        ExtensionElement e2eExt = m.getExtension(E2EEncryption.ELEMENT_NAME, E2EEncryption.NAMESPACE);
        if (e2eExt instanceof E2EEncryption) {
            // encryption extension (RFC 3923), decrypted later
            encrypted = EncodingUtils.bytesToBase64(((E2EEncryption) e2eExt).getData());
            // remove extension before parsing all others
            m.removeExtension(E2EEncryption.ELEMENT_NAME, E2EEncryption.NAMESPACE);
        }
        ExtensionElement openPGPExt = m.getExtension(OpenPGPExtension.ELEMENT_NAME, OpenPGPExtension.NAMESPACE);
        if (openPGPExt instanceof OpenPGPExtension) {
            if (!encrypted.isEmpty()) {
                LOGGER.info("message contains e2e and OpenPGP element, ignoring e2e");
            }
            encrypted = ((OpenPGPExtension) openPGPExt).getData();
            // remove extension before parsing all others
            m.removeExtension(OpenPGPExtension.ELEMENT_NAME, OpenPGPExtension.NAMESPACE);
        }
    }

    if (!encrypted.isEmpty()) {
        if (!plainText.isEmpty()) {
            LOGGER.config("message contains encryption and body (ignoring body): " + plainText);
            plainText = "";
        }
        builder.encrypted(encrypted);
    }
    addContent(builder, m.getExtensions(), plainText, decrypted);
    return builder.build();
}
 
Example #21
Source File: ReferenceElement.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Return a list of all reference extensions contained in a stanza.
 * If there are no reference elements, return an empty list.
 *
 * @param stanza stanza
 * @return list of all references contained in the stanza
 */
public static List<ReferenceElement> getReferencesFromStanza(Stanza stanza) {
    List<ReferenceElement> references = new ArrayList<>();
    List<ExtensionElement> extensions = stanza.getExtensions(ReferenceElement.ELEMENT, ReferenceManager.NAMESPACE);
    for (ExtensionElement e : extensions) {
        references.add((ReferenceElement) e);
    }
    return references;
}
 
Example #22
Source File: UserLocationExtension.java    From Yahala-Messenger with MIT License 5 votes vote down vote up
@Override
public ExtensionElement parse(XmlPullParser parser, int initialDepth) throws XmlPullParserException, IOException {
    /* String jid = parser.getAttributeValue(null, "jid");
    String nodeId = parser.getAttributeValue(null, "node");
    String subId = parser.getAttributeValue(null, "subid");
    String state = parser.getAttributeValue(null, "subscription");*/
    Double lon = 0d;
    Double lat = 0d;
    boolean done = false;
    while (!done) {
        int eventType = parser.next();

        if (eventType == XmlPullParser.START_TAG) {
            if ("lon".equalsIgnoreCase(parser.getName())) {
                String longValue = parser.nextText();

               /* if (longValue.equals("0.0"))
                    longValue="0";*/
                lon = Double.parseDouble(longValue);
                parser.nextTag();

                if ("lat".equalsIgnoreCase(parser.getName())) {
                    String latValue = parser.nextText();
                   /* if (latValue.equals("0.0"))
                        latValue="0";*/
                    lat = Double.parseDouble(latValue);
                }
                done = true;
            }


        }
    }


    return new UserLocationExtension(new Location(lon, lat));
}
 
Example #23
Source File: PubSubManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
PubSub sendPubsubPacket(Jid to, Type type, List<ExtensionElement> extList, PubSubNamespace ns)
                    throws NoResponseException, XMPPErrorException, NotConnectedException,
                    InterruptedException {
// CHECKSTYLE:OFF
        PubSub pubSub = new PubSub(to, type, ns);
        for (ExtensionElement pe : extList) {
            pubSub.addExtension(pe);
        }
// CHECKSTYLE:ON
        return sendPubsubPacket(pubSub);
    }
 
Example #24
Source File: OpenPgpContentElement.java    From Smack with Apache License 2.0 5 votes vote down vote up
protected void addCommonXml(XmlStringBuilder xml) {
    for (Jid toJid : to != null ? to : Collections.<Jid>emptySet()) {
        xml.halfOpenElement(ELEM_TO).attribute(ATTR_JID, toJid).closeEmptyElement();
    }

    ensureTimestampStringSet();
    xml.halfOpenElement(ELEM_TIME).attribute(ATTR_STAMP, timestampString).closeEmptyElement();

    xml.openElement(ELEM_PAYLOAD);
    for (ExtensionElement element : payload.values()) {
        xml.append(element.toXML(getNamespace()));
    }
    xml.closeElement(ELEM_PAYLOAD);
}
 
Example #25
Source File: ItemProvider.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public Item parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment)
                throws XmlPullParserException, IOException, SmackParsingException {
    String id = parser.getAttributeValue(null, "id");
    String node = parser.getAttributeValue(null, "node");
    String xmlns = parser.getNamespace();
    ItemNamespace itemNamespace = ItemNamespace.fromXmlns(xmlns);

    XmlPullParser.Event tag = parser.next();

    if (tag == XmlPullParser.Event.END_ELEMENT)  {
        return new Item(itemNamespace, id, node);
    }
    else {
        String payloadElemName = parser.getName();
        String payloadNS = parser.getNamespace();

        final ExtensionElementProvider<ExtensionElement> extensionProvider = ProviderManager.getExtensionProvider(payloadElemName, payloadNS);
        if (extensionProvider == null) {
            // TODO: Should we use StandardExtensionElement in this case? And probably remove SimplePayload all together.
            CharSequence payloadText = PacketParserUtils.parseElement(parser, true);
            return new PayloadItem<>(itemNamespace, id, node, new SimplePayload(payloadText.toString()));
        }
        else {
            return new PayloadItem<>(itemNamespace, id, node, extensionProvider.parse(parser));
        }
    }
}
 
Example #26
Source File: SubscriptionsProvider.java    From Smack with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected SubscriptionsExtension createReturnExtension(String currentElement, String currentNamespace, Map<String, String> attributeMap, List<? extends ExtensionElement> content) {
    SubscriptionsNamespace subscriptionsNamespace = SubscriptionsNamespace.fromXmlns(currentNamespace);
    String nodeId = attributeMap.get("node");
    return new SubscriptionsExtension(subscriptionsNamespace, nodeId, (List<Subscription>) content);
}
 
Example #27
Source File: ConfigurationEvent.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public List<ExtensionElement> getExtensions() {
    if (getConfiguration() == null)
        return Collections.emptyList();
    else
        return Arrays.asList((ExtensionElement) getConfiguration().getDataForm());
}
 
Example #28
Source File: OpenPgpElementTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Test
public void cryptElementProviderTest() throws Exception {
    String expected =
            "<crypt xmlns='urn:xmpp:openpgp:0'>" +
                    "<to jid='[email protected]'/>" +
                    "<time stamp='2014-07-10T15:06:00.000+00:00'/>" +
                    "<payload>" +
                    "<body xmlns='jabber:client' xml:lang='en'>The cake is a lie.</body>" +
                    "</payload>" +
                    "<rpad>f0rm1l4n4-mT8y33j!Y%fRSrcd^ZE4Q7VDt1L%WEgR!kv</rpad>" +
                    "</crypt>";
    List<ExtensionElement> payload = new ArrayList<>();
    payload.add(new Message.Body("en", "The cake is a lie."));
    Set<Jid> to = new HashSet<>();
    to.add(JidCreate.bareFrom("[email protected]"));
    CryptElement element = new CryptElement(to,
            "f0rm1l4n4-mT8y33j!Y%fRSrcd^ZE4Q7VDt1L%WEgR!kv",
            testDate,
            payload);

    assertXmlSimilar(expected, element.toXML().toString());

    XmlPullParser parser = TestUtils.getParser(expected);
    CryptElement parsed = (CryptElement) OpenPgpContentElementProvider.parseOpenPgpContentElement(parser);

    assertEquals(element.getTimestamp(), parsed.getTimestamp());
    assertEquals(element.getTo(), parsed.getTo());
    assertEquals(element.getExtensions(), parsed.getExtensions());
}
 
Example #29
Source File: OpenPgpElementTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Test
public void signcryptElementProviderTest() throws Exception {
    String expected =
            "<signcrypt xmlns='urn:xmpp:openpgp:0'>" +
                    "<to jid='[email protected]'/>" +
                    "<time stamp='2014-07-10T15:06:00.000+00:00'/>" +
                    "<payload>" +
                    "<body xmlns='jabber:client' xml:lang='en'>This is a secret message.</body>" +
                    "</payload>" +
                    "<rpad>f0rm1l4n4-mT8y33j!Y%fRSrcd^ZE4Q7VDt1L%WEgR!kv</rpad>" +
                    "</signcrypt>";

    List<ExtensionElement> payload = new ArrayList<>();
    payload.add(new Message.Body("en", "This is a secret message."));
    Set<Jid> jids = new HashSet<>();
    jids.add(JidCreate.bareFrom("[email protected]"));
    SigncryptElement element = new SigncryptElement(jids,
            "f0rm1l4n4-mT8y33j!Y%fRSrcd^ZE4Q7VDt1L%WEgR!kv",
            testDate, payload);

    assertXmlSimilar(expected, element.toXML().toString());

    XmlPullParser parser = TestUtils.getParser(expected);
    SigncryptElement parsed = (SigncryptElement) OpenPgpContentElementProvider.parseOpenPgpContentElement(parser);

    assertEquals(element.getTimestamp(), parsed.getTimestamp());
    assertEquals(element.getTo(), parsed.getTo());
    assertEquals(element.getExtensions(), parsed.getExtensions());
    assertEquals(payload.get(0), element.getExtension(Message.Body.NAMESPACE));
    assertEquals(payload.get(0), element.getExtension(Message.Body.ELEMENT, Message.Body.NAMESPACE));
}
 
Example #30
Source File: XHTMLExtensionProviderTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Test
public void parsesWell() throws IOException, XmlPullParserException {
    InputStream inputStream = getClass().getResourceAsStream(XHTML_EXTENSION_SAMPLE_RESOURCE_NAME);
    XmlPullParser parser = PacketParserUtils.getParserFor(inputStream);
    parser.next();

    XHTMLExtensionProvider provider = new XHTMLExtensionProvider();
    ExtensionElement extension = provider.parse(parser, parser.getDepth(), null);

    assertThat(extension, instanceOf(XHTMLExtension.class));
    XHTMLExtension attachmentsInfo = (XHTMLExtension) extension;

    assertThat(sampleXhtml(), equalsCharSequence(attachmentsInfo.getBodies().get(0)));
}