001/**
002 *
003 * Copyright 2003-2007 Jive Software.
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package org.jivesoftware.smackx.iqprivate;
019
020import java.io.IOException;
021import java.util.Hashtable;
022import java.util.Map;
023import java.util.WeakHashMap;
024
025import org.jivesoftware.smack.Manager;
026import org.jivesoftware.smack.SmackException;
027import org.jivesoftware.smack.SmackException.NoResponseException;
028import org.jivesoftware.smack.SmackException.NotConnectedException;
029import org.jivesoftware.smack.XMPPConnection;
030import org.jivesoftware.smack.XMPPException.XMPPErrorException;
031import org.jivesoftware.smack.packet.IQ;
032import org.jivesoftware.smack.packet.StanzaError.Condition;
033import org.jivesoftware.smack.provider.IQProvider;
034
035import org.jivesoftware.smackx.iqprivate.packet.DefaultPrivateData;
036import org.jivesoftware.smackx.iqprivate.packet.PrivateData;
037import org.jivesoftware.smackx.iqprivate.packet.PrivateDataIQ;
038import org.jivesoftware.smackx.iqprivate.provider.PrivateDataProvider;
039
040import org.jxmpp.util.XmppStringUtils;
041import org.xmlpull.v1.XmlPullParser;
042import org.xmlpull.v1.XmlPullParserException;
043
044/**
045 * Manages private data, which is a mechanism to allow users to store arbitrary XML
046 * data on an XMPP server. Each private data chunk is defined by a element name and
047 * XML namespace. Example private data:
048 *
049 * <pre>
050 * &lt;color xmlns="http://example.com/xmpp/color"&gt;
051 *     &lt;favorite&gt;blue&lt;/blue&gt;
052 *     &lt;leastFavorite&gt;puce&lt;/leastFavorite&gt;
053 * &lt;/color&gt;
054 * </pre>
055 *
056 * {@link PrivateDataProvider} instances are responsible for translating the XML into objects.
057 * If no PrivateDataProvider is registered for a given element name and namespace, then
058 * a {@link DefaultPrivateData} instance will be returned.<p>
059 *
060 * Warning: this is an non-standard protocol documented by
061 * <a href="http://www.xmpp.org/extensions/jep-0049.html">XEP-49</a>. Because this is a
062 * non-standard protocol, it is subject to change.
063 *
064 * @author Matt Tucker
065 */
066public final class PrivateDataManager extends Manager {
067    private static final Map<XMPPConnection, PrivateDataManager> instances = new WeakHashMap<XMPPConnection, PrivateDataManager>();
068
069    public static synchronized PrivateDataManager getInstanceFor(XMPPConnection connection) {
070        PrivateDataManager privateDataManager = instances.get(connection);
071        if (privateDataManager == null) {
072            privateDataManager = new PrivateDataManager(connection);
073        }
074        return privateDataManager;
075    }
076
077    /**
078     * Map of provider instances.
079     */
080    private static final Map<String, PrivateDataProvider> privateDataProviders = new Hashtable<>();
081
082    /**
083     * Returns the private data provider registered to the specified XML element name and namespace.
084     * For example, if a provider was registered to the element name "prefs" and the
085     * namespace "http://www.xmppclient.com/prefs", then the following stanza would trigger
086     * the provider:
087     *
088     * <pre>
089     * &lt;iq type='result' to='joe@example.com' from='mary@example.com' id='time_1'&gt;
090     *     &lt;query xmlns='jabber:iq:private'&gt;
091     *         &lt;prefs xmlns='http://www.xmppclient.com/prefs'&gt;
092     *             &lt;value1&gt;ABC&lt;/value1&gt;
093     *             &lt;value2&gt;XYZ&lt;/value2&gt;
094     *         &lt;/prefs&gt;
095     *     &lt;/query&gt;
096     * &lt;/iq&gt;</pre>
097     *
098     * <p>Note: this method is generally only called by the internal Smack classes.
099     *
100     * @param elementName the XML element name.
101     * @param namespace the XML namespace.
102     * @return the PrivateData provider.
103     */
104    public static PrivateDataProvider getPrivateDataProvider(String elementName, String namespace) {
105        String key = XmppStringUtils.generateKey(elementName, namespace);
106        return privateDataProviders.get(key);
107    }
108
109    /**
110     * Adds a private data provider with the specified element name and name space. The provider
111     * will override any providers loaded through the classpath.
112     *
113     * @param elementName the XML element name.
114     * @param namespace the XML namespace.
115     * @param provider the private data provider.
116     */
117    public static void addPrivateDataProvider(String elementName, String namespace,
118            PrivateDataProvider provider) {
119        String key = XmppStringUtils.generateKey(elementName, namespace);
120        privateDataProviders.put(key, provider);
121    }
122
123    /**
124     * Removes a private data provider with the specified element name and namespace.
125     *
126     * @param elementName The XML element name.
127     * @param namespace The XML namespace.
128     */
129    public static void removePrivateDataProvider(String elementName, String namespace) {
130        String key = XmppStringUtils.generateKey(elementName, namespace);
131        privateDataProviders.remove(key);
132    }
133
134    /**
135     * Creates a new private data manager.
136     *
137     * @param connection an XMPP connection which must have already undergone a
138     *      successful login.
139     */
140    private PrivateDataManager(XMPPConnection connection) {
141        super(connection);
142        instances.put(connection, this);
143    }
144
145    /**
146     * Returns the private data specified by the given element name and namespace. Each chunk
147     * of private data is uniquely identified by an element name and namespace pair.<p>
148     *
149     * If a PrivateDataProvider is registered for the specified element name/namespace pair then
150     * that provider will determine the specific object type that is returned. If no provider
151     * is registered, a {@link DefaultPrivateData} instance will be returned.
152     *
153     * @param elementName the element name.
154     * @param namespace the namespace.
155     * @return the private data.
156     * @throws XMPPErrorException
157     * @throws NoResponseException
158     * @throws NotConnectedException
159     * @throws InterruptedException
160     */
161    public PrivateData getPrivateData(final String elementName, final String namespace) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
162        // Create an IQ packet to get the private data.
163        IQ privateDataGet = new PrivateDataIQ(elementName, namespace);
164
165        PrivateDataIQ response = connection().createStanzaCollectorAndSend(
166                        privateDataGet).nextResultOrThrow();
167        return response.getPrivateData();
168    }
169
170    /**
171     * Sets a private data value. Each chunk of private data is uniquely identified by an
172     * element name and namespace pair. If private data has already been set with the
173     * element name and namespace, then the new private data will overwrite the old value.
174     *
175     * @param privateData the private data.
176     * @throws XMPPErrorException
177     * @throws NoResponseException
178     * @throws NotConnectedException
179     * @throws InterruptedException
180     */
181    public void setPrivateData(final PrivateData privateData) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
182        // Create an IQ packet to set the private data.
183        IQ privateDataSet = new PrivateDataIQ(privateData);
184
185        connection().createStanzaCollectorAndSend(privateDataSet).nextResultOrThrow();
186    }
187
188    private static final PrivateData DUMMY_PRIVATE_DATA = new PrivateData() {
189        @Override
190        public String getElementName() {
191            return "smackDummyPrivateData";
192        }
193
194        @Override
195        public String getNamespace() {
196            return "https://igniterealtime.org/projects/smack/";
197        }
198
199        @Override
200        public CharSequence toXML() {
201            return '<' + getElementName() + " xmlns='" + getNamespace() + "'/>";
202        }
203    };
204
205    /**
206     * Check if the service supports private data.
207     *
208     * @return true if the service supports private data, false otherwise.
209     * @throws NoResponseException
210     * @throws NotConnectedException
211     * @throws InterruptedException
212     * @throws XMPPErrorException
213     * @since 4.2
214     */
215    public boolean isSupported() throws NoResponseException, NotConnectedException,
216                    InterruptedException, XMPPErrorException {
217        // This is just a primitive hack, since XEP-49 does not specify a way to determine if the
218        // service supports it
219        try {
220            setPrivateData(DUMMY_PRIVATE_DATA);
221            return true;
222        }
223        catch (XMPPErrorException e) {
224            if (e.getStanzaError().getCondition() == Condition.service_unavailable) {
225                return false;
226            }
227            else {
228                throw e;
229            }
230        }
231    }
232
233    /**
234     * An IQ provider to parse IQ results containing private data.
235     */
236    public static class PrivateDataIQProvider extends IQProvider<PrivateDataIQ> {
237
238        @Override
239        public PrivateDataIQ parse(XmlPullParser parser, int initialDepth)
240                        throws XmlPullParserException, IOException, SmackException {
241            PrivateData privateData = null;
242            boolean done = false;
243            while (!done) {
244                int eventType = parser.next();
245                if (eventType == XmlPullParser.START_TAG) {
246                    String elementName = parser.getName();
247                    String namespace = parser.getNamespace();
248                    // See if any objects are registered to handle this private data type.
249                    PrivateDataProvider provider = getPrivateDataProvider(elementName, namespace);
250                    // If there is a registered provider, use it.
251                    if (provider != null) {
252                        privateData = provider.parsePrivateData(parser);
253                    }
254                    // Otherwise, use a DefaultPrivateData instance to store the private data.
255                    else {
256                        DefaultPrivateData data = new DefaultPrivateData(elementName, namespace);
257                        boolean finished = false;
258                        while (!finished) {
259                            int event = parser.next();
260                            if (event == XmlPullParser.START_TAG) {
261                                String name = parser.getName();
262                                // If an empty element, set the value with the empty string.
263                                if (parser.isEmptyElementTag()) {
264                                    data.setValue(name,"");
265                                }
266                                // Otherwise, get the the element text.
267                                else {
268                                    event = parser.next();
269                                    if (event == XmlPullParser.TEXT) {
270                                        String value = parser.getText();
271                                        data.setValue(name, value);
272                                    }
273                                }
274                            }
275                            else if (event == XmlPullParser.END_TAG) {
276                                if (parser.getName().equals(elementName)) {
277                                    finished = true;
278                                }
279                            }
280                        }
281                        privateData = data;
282                    }
283                }
284                else if (eventType == XmlPullParser.END_TAG) {
285                    if (parser.getName().equals("query")) {
286                        done = true;
287                    }
288                }
289            }
290            return new PrivateDataIQ(privateData);
291        }
292    }
293}