@Test public void isNonLatsChunkParsedCorrectly() throws Exception { String base64Text = "iVBORw0KGgoAAAANSUhEUgAAASwAAAGQCAYAA"; String string = "<chunk xmlns='urn:xmpp:http' streamId='Stream0001' nr='0'>" + 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()); assertFalse(chunk.isLast()); assertEquals(base64Text, chunk.getText()); assertEquals(0, chunk.getNr()); }
@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()); }
@Override public final PE parse(XmlPullParser parser, int initialDepth) throws XmlPullParserException, IOException, SmackException { 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<>(); int event; do { event = parser.next(); if (event == XmlPullParser.START_TAG) PacketParserUtils.addExtensionElement(extensions, parser); } while (!(event == XmlPullParser.END_TAG && parser.getDepth() == initialDepth)); return createReturnExtension(name, namespace, attMap, extensions); }
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<ExtensionElement>(); } RSMSet resultRsmSet = PacketUtil.extensionElementFrom(returnedExtensions, RSMSet.ELEMENT, RSMSet.NAMESPACE); if (resultRsmSet == null) { throw new IllegalArgumentException("returnedExtensions did not contain a RSMset"); } RSMSet continePageRsmSet = new RSMSet(max, resultRsmSet.getLast(), PageDirection.after); additionalExtensions.add(continePageRsmSet); return additionalExtensions; }
private List<Subscription> getSubscriptions(List<ExtensionElement> additionalExtensions, Collection<ExtensionElement> returnedExtensions, PubSubNamespace pubSubNamespace) throws NoResponseException, XMPPErrorException, NotConnectedException { PubSub pubSub = createPubsubPacket(Type.get, new NodeExtension(PubSubElementType.SUBSCRIPTIONS, getId()), pubSubNamespace); if (additionalExtensions != null) { for (ExtensionElement pe : additionalExtensions) { pubSub.addExtension(pe); } } PubSub reply = sendPubsubPacket(pubSub); if (returnedExtensions != null) { returnedExtensions.addAll(reply.getExtensions()); } SubscriptionsExtension subElem = (SubscriptionsExtension) reply.getExtension(PubSubElementType.SUBSCRIPTIONS); return subElem.getSubscriptions(); }
/** * Get the affiliations of this node. * <p> * {@code additionalExtensions} can be used e.g. to add a "Result Set Management" extension. * {@code returnedExtensions} will be filled with the stanza(/packet) extensions found in the answer. * </p> * * @param additionalExtensions additional {@code PacketExtensions} add to the request * @param returnedExtensions a collection that will be filled with the returned packet * extensions * @return List of {@link Affiliation} * @throws NoResponseException * @throws XMPPErrorException * @throws NotConnectedException */ public List<Affiliation> getAffiliations(List<ExtensionElement> additionalExtensions, Collection<ExtensionElement> returnedExtensions) throws NoResponseException, XMPPErrorException, NotConnectedException { PubSub pubSub = createPubsubPacket(Type.get, new NodeExtension(PubSubElementType.AFFILIATIONS, getId())); if (additionalExtensions != null) { for (ExtensionElement pe : additionalExtensions) { pubSub.addExtension(pe); } } PubSub reply = sendPubsubPacket(pubSub); if (returnedExtensions != null) { returnedExtensions.addAll(reply.getExtensions()); } AffiliationsExtension affilElem = (AffiliationsExtension) reply.getExtension(PubSubElementType.AFFILIATIONS); return affilElem.getAffiliations(); }
public void processPacket(Stanza packet) { EventElement event = (EventElement)packet.getExtension("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<String>(pubItems.size()); for (RetractItem item : pubItems) { items.add(item.getId()); } ItemDeleteEvent eventItems = new ItemDeleteEvent(itemsElem.getNode(), items, getSubscriptionIds(packet)); listener.handleDeletedItems(eventItems); } }
public void processMessage(Chat chat, Message message) { ExtensionElement extension = message.getExtension(NAMESPACE); if (extension == null) { return; } ChatState state; try { state = ChatState.valueOf(extension.getElementName()); } catch (Exception ex) { return; } fireNewChatState(chat, state); }
/** * * @param info * @return true if the stanza(/packet) extensions is ill-formed */ protected static boolean verifyPacketExtensions(DiscoverInfo info) { List<FormField> foundFormTypes = new LinkedList<FormField>(); for (ExtensionElement pe : info.getExtensions()) { if (pe.getNamespace().equals(DataForm.NAMESPACE)) { DataForm df = (DataForm) pe; for (FormField f : df.getFields()) { if (f.getVariable().equals("FORM_TYPE")) { for (FormField fft : foundFormTypes) { if (f.equals(fft)) return true; } foundFormTypes.add(f); } } } } return false; }
/** * Parse a JingleDescription.Audio extension. */ @Override public ExtensionElement parse(XmlPullParser parser, int initialDepth) { 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; }
@Override protected void processWakefulStanza(Stanza packet) throws SmackException.NotConnectedException { org.jivesoftware.smack.packet.Message m = (org.jivesoftware.smack.packet.Message) packet; if (m.getType() == org.jivesoftware.smack.packet.Message.Type.chat) { ExtensionElement chatstate = processChatState(m); // non-active chat states are not to be processed as messages if (chatstate == null || chatstate.getElementName().equals(ChatState.active.name())) { processChatMessage(m); } } // error message else if (m.getType() == org.jivesoftware.smack.packet.Message.Type.error) { processErrorMessage(m); } }
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; }
/** Get XEP-0373 signcrypt plaintext as XML string. */ public static String getSignCryptElement(OutMessage message) { List<String> tos = message.getTransmissions().stream() .map(t -> t.getJID().string()) .collect(Collectors.toList()); int rpadLength = new SecureRandom().nextInt(RPAD_LENGTH_RANGE); List<ExtensionElement> contentElements = new ArrayList<>(); MessageContent content = message.getContent(); String text = content.getPlainText(); if (!text.isEmpty()) contentElements.add(new BodyElement(text)); contentElements.addAll(extensionsForContent(content, message.getChat(), true)); return new SignCryptElement(tos, new Date(), rpadLength, contentElements) .toXML().toString(); }
@Override protected Received createReturnExtension(String currentElement, String currentNamespace, Map<String, String> attributeMap, List<? extends ExtensionElement> content) { return new Received(attributeMap.get("id")); }
@Override protected Displayed createReturnExtension(String currentElement, String currentNamespace, Map<String, String> attributeMap, List<? extends ExtensionElement> content) { return new Displayed(attributeMap.get("id")); }
@Override protected Markable createReturnExtension(String currentElement, String currentNamespace, Map<String, String> attributeMap, List<? extends ExtensionElement> content) { return new Markable(); }
@Override protected DeliveredReceipt createReturnExtension(String currentElement, String currentNamespace, Map<String, String> attributeMap, List<? extends ExtensionElement> content) { return new DeliveredReceipt(attributeMap.get("id")); }
@Override protected ReadReceipt createReturnExtension(String currentElement, String currentNamespace, Map<String, String> attributeMap, List<? extends ExtensionElement> content) { return new ReadReceipt(attributeMap.get("id")); }
/** * Adds an extension provider with the specified element name and name space. The provider * will override any providers loaded through the classpath. The provider must be either * a PacketExtensionProvider instance, or a Class object of a Javabean. * * @param elementName the XML element name. * @param namespace the XML namespace. * @param provider the extension provider. */ @SuppressWarnings("unchecked") public static void addExtensionProvider(String elementName, String namespace, Object provider) { validate(elementName, namespace); // First remove existing providers String key = removeExtensionProvider(elementName, namespace); if (provider instanceof ExtensionElementProvider) { extensionProviders.put(key, (ExtensionElementProvider<ExtensionElement>) provider); } else { throw new IllegalArgumentException("Provider must be a PacketExtensionProvider"); } }
/** * Get a extension element from a collection * * @param collection * @param element * @param namespace * @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; }
/** * @deprecated use {@link #parseExtensionElement(String, String, XmlPullParser)} instead. */ @Deprecated public static ExtensionElement parsePacketExtension(String elementName, String namespace, XmlPullParser parser) throws XmlPullParserException, IOException, SmackException { return parseExtensionElement(elementName, namespace, parser); }
/** * Parses an extension element. * * @param elementName the XML element name of the extension element. * @param namespace the XML namespace of the stanza(/packet) extension. * @param parser the XML parser, positioned at the starting element of the extension. * @return an extension element. */ public static ExtensionElement parseExtensionElement(String elementName, String namespace, XmlPullParser parser) throws XmlPullParserException, IOException, SmackException { ParserUtils.assertAtStartTag(parser); // See if a provider is registered to handle the extension. ExtensionElementProvider<ExtensionElement> provider = ProviderManager.getExtensionProvider(elementName, namespace); if (provider != null) { return provider.parse(parser); } final int initialDepth = parser.getDepth(); // No providers registered, so use a default extension. DefaultExtensionElement extension = new DefaultExtensionElement(elementName, namespace); outerloop: while (true) { int eventType = parser.next(); switch (eventType) { case XmlPullParser.START_TAG: String name = parser.getName(); // If an empty element, set the value with the empty string. if (parser.isEmptyElementTag()) { extension.setValue(name,""); } // Otherwise, get the the element text. else { eventType = parser.next(); if (eventType == XmlPullParser.TEXT) { String value = parser.getText(); extension.setValue(name, value); } } break; case XmlPullParser.END_TAG: if (parser.getDepth() == initialDepth) { break outerloop; } } } return extension; }
@SuppressWarnings("unchecked") public static <EE extends ExtensionElement> EE parseExtensionElement(XmlPullParser parser) throws XmlPullParserException, IOException, SmackException { ParserUtils.assertAtStartTag(parser); final String elementName = parser.getName(); final String namespace = parser.getNamespace(); return (EE) PacketParserUtils.parseExtensionElement(elementName, namespace, parser); }
static PubSub sendPubsubPacket(XMPPConnection con, String to, Type type, List<ExtensionElement> extList, PubSubNamespace ns) throws NoResponseException, XMPPErrorException, NotConnectedException { PubSub pubSub = new PubSub(to, type, ns); for (ExtensionElement pe : extList) { pubSub.addExtension(pe); } return sendPubsubPacket(con ,pubSub); }
@Override public CharSequence toXML() { if ((items == null) || (items.size() == 0)) { return super.toXML(); } else { StringBuilder builder = new StringBuilder("<"); builder.append(getElementName()); builder.append(" node='"); builder.append(getNode()); if (notify != null) { builder.append("' "); builder.append(type.getElementAttribute()); builder.append("='"); builder.append(notify.equals(Boolean.TRUE) ? 1 : 0); builder.append("'>"); } else { builder.append("'>"); for (ExtensionElement item : items) { builder.append(item.toXML()); } } builder.append("</"); builder.append(getElementName()); builder.append(">"); return builder.toString(); } }
@SuppressWarnings("unchecked") private <T extends Item> List<T> getItems(PubSub request, List<ExtensionElement> returnedExtensions) throws NoResponseException, XMPPErrorException, NotConnectedException { PubSub result = con.createPacketCollectorAndSend(request).nextResultOrThrow(); ItemsExtension itemsElem = result.getExtension(PubSubElementType.ITEMS); if (returnedExtensions != null) { returnedExtensions.addAll(result.getExtensions()); } return (List<T>) itemsElem.getItems(); }
public boolean accept(Stanza packet) { if (!(packet instanceof Message)) return false; EventElement event = (EventElement)packet.getExtension("event", PubSubNamespace.EVENT.getXmlns()); if (event == null) return false; NodeExtension embedEvent = event.getEvent(); if (embedEvent == null) return false; if (embedEvent.getElementName().equals(firstElement)) { if (!embedEvent.getNode().equals(getId())) return false; if (secondElement == null) return true; if (embedEvent instanceof EmbeddedPacketExtension) { List<ExtensionElement> secondLevelList = ((EmbeddedPacketExtension)embedEvent).getExtensions(); if (secondLevelList.size() > 0 && secondLevelList.get(0).getElementName().equals(secondElement)) return true; } } return false; }
public List<ExtensionElement> getExtensions() { if (getConfiguration() == null) return Collections.emptyList(); else return Arrays.asList(((ExtensionElement)getConfiguration().getDataFormToSend())); }
@Override protected ConfigurationEvent createReturnExtension(String currentElement, String currentNamespace, Map<String, String> attMap, List<? extends ExtensionElement> content) { if (content.size() == 0) return new ConfigurationEvent(attMap.get("node")); else return new ConfigurationEvent(attMap.get("node"), new ConfigureForm((DataForm)content.iterator().next())); }
@Override public Item parse(XmlPullParser parser, int initialDepth) throws XmlPullParserException, IOException, SmackException { String id = parser.getAttributeValue(null, "id"); String node = parser.getAttributeValue(null, "node"); int tag = parser.next(); if (tag == XmlPullParser.END_TAG) { return new Item(id, node); } else { String payloadElemName = parser.getName(); String payloadNS = parser.getNamespace(); final ExtensionElementProvider<ExtensionElement> extensionProvider = ProviderManager.getExtensionProvider(payloadElemName, payloadNS); if (extensionProvider == null) { CharSequence payloadText = PacketParserUtils.parseElement(parser, true); return new PayloadItem<SimplePayload>(id, node, new SimplePayload(payloadElemName, payloadNS, payloadText)); } else { return new PayloadItem<ExtensionElement>(id, node, extensionProvider.parse(parser)); } } }
/** * Parses a PEPEvent stanza(/packet) and extracts a PEPItem from it. * (There is only one per <event>.) * * @param parser the XML parser, positioned at the starting element of the extension. * @return a PacketExtension. * @throws IOException * @throws XmlPullParserException * @throws SmackException */ @Override public ExtensionElement parse(XmlPullParser parser, int initialDepth) throws XmlPullParserException, IOException, SmackException { ExtensionElement pepItem = null; boolean done = false; while (!done) { int eventType = parser.next(); if (eventType == XmlPullParser.START_TAG) { if (parser.getName().equals("event")) { } else if (parser.getName().equals("items")) { // Figure out the node for this event. String node = parser.getAttributeValue("", "node"); // Get the parser for this kind of node, and if found then parse the node. ExtensionElementProvider<?> nodeParser = nodeParsers.get(node); if (nodeParser != null) { pepItem = nodeParser.parse(parser); } } } else if (eventType == XmlPullParser.END_TAG) { if (parser.getName().equals("event")) { done = true; } } } return pepItem; }
/** * Returns the data form as List of PacketExtensions, or null if no data form is set. * This representation is needed by some classes (e.g. EntityCapsManager, NodeInformationProvider) * * @return the data form as List of PacketExtensions */ public List<ExtensionElement> getExtendedInfoAsList() { List<ExtensionElement> res = null; if (extendedInfo != null) { res = new ArrayList<ExtensionElement>(1); res.add(extendedInfo); } return res; }
@Test public void parsesWell() throws IOException, XmlPullParserException { XmlPullParser parser = PacketParserUtils.newXmppParser(); parser.setInput(getClass().getResourceAsStream(XHTML_EXTENSION_SAMPLE_RESOURCE_NAME), "UTF-8"); parser.next(); XHTMLExtensionProvider provider = new XHTMLExtensionProvider(); ExtensionElement extension = provider.parse(parser, parser.getDepth()); assertThat(extension, instanceOf(XHTMLExtension.class)); XHTMLExtension attachmentsInfo = (XHTMLExtension) extension; assertThat(sampleXhtml(), equalsCharSequence(attachmentsInfo.getBodies().get(0))); }
@Test public void isCorrectFromXmlDeserialization() throws Exception { AMPExtensionProvider ampProvider = new AMPExtensionProvider(); XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser(); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true); parser.setInput(CORRECT_SENDING_STANZA_STREAM, "UTF-8"); assertEquals(XmlPullParser.START_TAG, parser.next()); assertEquals(AMPExtension.ELEMENT, parser.getName()); ExtensionElement extension = ampProvider.parse(parser); assertTrue(extension instanceof AMPExtension); AMPExtension amp = (AMPExtension) extension; assertEquals(9, amp.getRulesCount()); }
private Stanza createSubscribed(Presence p) { ExtensionElement _pkey = p.getExtension(PublicKeyPresence.ELEMENT_NAME, PublicKeyPresence.NAMESPACE); try { if (_pkey instanceof PublicKeyPresence) { PublicKeyPresence pkey = (PublicKeyPresence) _pkey; byte[] keydata = pkey.getKey(); // just to ensure it's valid data PGP.readPublicKeyring(keydata); String jid = p.getFrom().asBareJid().toString(); // store key to users table Keyring.setKey(getContext(), jid, keydata, MyUsers.Keys.TRUST_VERIFIED); } Presence p2 = new Presence(Presence.Type.subscribed); p2.setTo(p.getFrom()); return p2; } catch (Exception e) { Log.w(MessageCenterService.TAG, "unable to accept subscription from user", e); // TODO should we notify the user about this? // TODO throw new PGPException(...) return null; } }