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.XMPPError.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(/packet) 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    {
120        String key = XmppStringUtils.generateKey(elementName, namespace);
121        privateDataProviders.put(key, provider);
122    }
123
124    /**
125     * Removes a private data provider with the specified element name and namespace.
126     *
127     * @param elementName The XML element name.
128     * @param namespace The XML namespace.
129     */
130    public static void removePrivateDataProvider(String elementName, String namespace) {
131        String key = XmppStringUtils.generateKey(elementName, namespace);
132        privateDataProviders.remove(key);
133    }
134
135    /**
136     * Creates a new private data manager.
137     *
138     * @param connection an XMPP connection which must have already undergone a
139     *      successful login.
140     */
141    private PrivateDataManager(XMPPConnection connection) {
142        super(connection);
143        instances.put(connection, this);
144    }
145
146    /**
147     * Returns the private data specified by the given element name and namespace. Each chunk
148     * of private data is uniquely identified by an element name and namespace pair.<p>
149     *
150     * If a PrivateDataProvider is registered for the specified element name/namespace pair then
151     * that provider will determine the specific object type that is returned. If no provider
152     * is registered, a {@link DefaultPrivateData} instance will be returned.
153     *
154     * @param elementName the element name.
155     * @param namespace the namespace.
156     * @return the private data.
157     * @throws XMPPErrorException 
158     * @throws NoResponseException 
159     * @throws NotConnectedException 
160     * @throws InterruptedException 
161     */
162    public PrivateData getPrivateData(final String elementName, final String namespace) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException
163    {
164        // Create an IQ packet to get the private data.
165        IQ privateDataGet = new PrivateDataIQ(elementName, namespace);
166
167        PrivateDataIQ response = connection().createStanzaCollectorAndSend(
168                        privateDataGet).nextResultOrThrow();
169        return response.getPrivateData();
170    }
171
172    /**
173     * Sets a private data value. Each chunk of private data is uniquely identified by an
174     * element name and namespace pair. If private data has already been set with the
175     * element name and namespace, then the new private data will overwrite the old value.
176     *
177     * @param privateData the private data.
178     * @throws XMPPErrorException 
179     * @throws NoResponseException 
180     * @throws NotConnectedException 
181     * @throws InterruptedException 
182     */
183    public void setPrivateData(final PrivateData privateData) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
184        // Create an IQ packet to set the private data.
185        IQ privateDataSet = new PrivateDataIQ(privateData);
186
187        connection().createStanzaCollectorAndSend(privateDataSet).nextResultOrThrow();
188    }
189
190    private static final PrivateData DUMMY_PRIVATE_DATA = new PrivateData() {
191        @Override
192        public String getElementName() {
193            return "smackDummyPrivateData";
194        }
195
196        @Override
197        public String getNamespace() {
198            return "https://igniterealtime.org/projects/smack/";
199        }
200
201        @Override
202        public CharSequence toXML() {
203            return '<' + getElementName() + " xmlns='" + getNamespace() + "'/>";
204        }
205    };
206
207    /**
208     * Check if the service supports private data.
209     *
210     * @return true if the service supports private data, false otherwise.
211     * @throws NoResponseException
212     * @throws NotConnectedException
213     * @throws InterruptedException
214     * @throws XMPPErrorException
215     * @since 4.2
216     */
217    public boolean isSupported() throws NoResponseException, NotConnectedException,
218                    InterruptedException, XMPPErrorException {
219        // This is just a primitive hack, since XEP-49 does not specify a way to determine if the
220        // service supports it
221        try {
222            setPrivateData(DUMMY_PRIVATE_DATA);
223            return true;
224        }
225        catch (XMPPErrorException e) {
226            if (e.getXMPPError().getCondition() == Condition.service_unavailable) {
227                return false;
228            }
229            else {
230                throw e;
231            }
232        }
233    }
234
235    /**
236     * An IQ provider to parse IQ results containing private data.
237     */
238    public static class PrivateDataIQProvider extends IQProvider<PrivateDataIQ> {
239
240        @Override
241        public PrivateDataIQ parse(XmlPullParser parser, int initialDepth)
242                        throws XmlPullParserException, IOException, SmackException {
243            PrivateData privateData = null;
244            boolean done = false;
245            while (!done) {
246                int eventType = parser.next();
247                if (eventType == XmlPullParser.START_TAG) {
248                    String elementName = parser.getName();
249                    String namespace = parser.getNamespace();
250                    // See if any objects are registered to handle this private data type.
251                    PrivateDataProvider provider = getPrivateDataProvider(elementName, namespace);
252                    // If there is a registered provider, use it.
253                    if (provider != null) {
254                        privateData = provider.parsePrivateData(parser);
255                    }
256                    // Otherwise, use a DefaultPrivateData instance to store the private data.
257                    else {
258                        DefaultPrivateData data = new DefaultPrivateData(elementName, namespace);
259                        boolean finished = false;
260                        while (!finished) {
261                            int event = parser.next();
262                            if (event == XmlPullParser.START_TAG) {
263                                String name = parser.getName();
264                                // If an empty element, set the value with the empty string.
265                                if (parser.isEmptyElementTag()) {
266                                    data.setValue(name,"");
267                                }
268                                // Otherwise, get the the element text.
269                                else {
270                                    event = parser.next();
271                                    if (event == XmlPullParser.TEXT) {
272                                        String value = parser.getText();
273                                        data.setValue(name, value);
274                                    }
275                                }
276                            }
277                            else if (event == XmlPullParser.END_TAG) {
278                                if (parser.getName().equals(elementName)) {
279                                    finished = true;
280                                }
281                            }
282                        }
283                        privateData = data;
284                    }
285                }
286                else if (eventType == XmlPullParser.END_TAG) {
287                    if (parser.getName().equals("query")) {
288                        done = true;
289                    }
290                }
291            }
292            return new PrivateDataIQ(privateData);
293        }
294    }
295}