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 */
017package org.jivesoftware.smackx.jiveproperties.provider;
018
019import java.io.ByteArrayInputStream;
020import java.io.IOException;
021import java.io.ObjectInputStream;
022import java.util.HashMap;
023import java.util.Map;
024import java.util.logging.Level;
025import java.util.logging.Logger;
026
027import org.jivesoftware.smack.packet.XmlEnvironment;
028import org.jivesoftware.smack.provider.ExtensionElementProvider;
029import org.jivesoftware.smack.util.DoOnce;
030import org.jivesoftware.smack.util.stringencoder.Base64;
031import org.jivesoftware.smack.xml.XmlPullParser;
032import org.jivesoftware.smack.xml.XmlPullParserException;
033
034import org.jivesoftware.smackx.jiveproperties.JivePropertiesManager;
035import org.jivesoftware.smackx.jiveproperties.packet.JivePropertiesExtension;
036
037import org.jxmpp.JxmppContext;
038
039public class JivePropertiesExtensionProvider extends ExtensionElementProvider<JivePropertiesExtension> {
040
041    private static final DoOnce LOG_OBJECT_NOT_ENABLED = new DoOnce();
042
043    private static final Logger LOGGER = Logger.getLogger(JivePropertiesExtensionProvider.class.getName());
044
045    /**
046     * Parse a properties sub-packet. If any errors occur while de-serializing Java object
047     * properties, an exception will be printed and not thrown since a thrown exception will shut
048     * down the entire connection. ClassCastExceptions will occur when both the sender and receiver
049     * of the stanza don't have identical versions of the same class.
050     * <p>
051     * Note that you have to explicitly enabled Java object deserialization with
052     * {@link JivePropertiesManager#setJavaObjectEnabled(boolean)}
053     *
054     * @param parser the XML parser, positioned at the start of a properties sub-packet.
055     * @return a map of the properties.
056     * @throws IOException if an I/O error occurred.
057     * @throws XmlPullParserException if an error in the XML parser occurred.
058     */
059    @SuppressWarnings("BanSerializableRead")
060    @Override
061    public JivePropertiesExtension parse(XmlPullParser parser,
062                    int initialDepth, XmlEnvironment xmlEnvironment, JxmppContext jxmppContext) throws XmlPullParserException,
063                    IOException {
064        Map<String, Object> properties = new HashMap<>();
065        while (true) {
066            XmlPullParser.Event eventType = parser.next();
067            if (eventType == XmlPullParser.Event.START_ELEMENT && parser.getName().equals("property")) {
068                // Parse a property
069                boolean done = false;
070                String name = null;
071                String type = null;
072                String valueText = null;
073                Object value = null;
074                while (!done) {
075                    eventType = parser.next();
076                    if (eventType == XmlPullParser.Event.START_ELEMENT) {
077                        String elementName = parser.getName();
078                        if (elementName.equals("name")) {
079                            name = parser.nextText();
080                        }
081                        else if (elementName.equals("value")) {
082                            type = parser.getAttributeValue("", "type");
083                            valueText = parser.nextText();
084                        }
085                    }
086                    else if (eventType == XmlPullParser.Event.END_ELEMENT) {
087                        if (parser.getName().equals("property")) {
088                            if ("integer".equals(type)) {
089                                value = Integer.valueOf(valueText);
090                            }
091                            else if ("long".equals(type))  {
092                                value = Long.valueOf(valueText);
093                            }
094                            else if ("float".equals(type)) {
095                                value = Float.valueOf(valueText);
096                            }
097                            else if ("double".equals(type)) {
098                                value = Double.valueOf(valueText);
099                            }
100                            else if ("boolean".equals(type)) {
101                                // CHECKSTYLE:OFF
102                                value = Boolean.valueOf(valueText);
103                                // CHECKSTYLE:ON
104                            }
105                            else if ("string".equals(type)) {
106                                value = valueText;
107                            }
108                            else if ("java-object".equals(type)) {
109                                if (JivePropertiesManager.isJavaObjectEnabled()) {
110                                    try {
111                                        byte[] bytes = Base64.decode(valueText);
112                                        ObjectInputStream in = new ObjectInputStream(
113                                                        new ByteArrayInputStream(bytes));
114                                        value = in.readObject();
115                                    }
116                                    catch (Exception e) {
117                                        LOGGER.log(Level.SEVERE, "Error parsing java object", e);
118                                    }
119                                }
120                                else {
121                                    LOG_OBJECT_NOT_ENABLED.once(
122                                        () -> LOGGER.severe(
123                                            "JavaObject is not enabled. Enable with JivePropertiesManager.setJavaObjectEnabled(true)")
124                                    );
125                                }
126                            }
127                            if (name != null && value != null) {
128                                properties.put(name, value);
129                            }
130                            done = true;
131                        }
132                    }
133                }
134            }
135            else if (eventType == XmlPullParser.Event.END_ELEMENT) {
136                if (parser.getName().equals(JivePropertiesExtension.ELEMENT)) {
137                    break;
138                }
139            }
140        }
141        return new JivePropertiesExtension(properties);
142    }
143
144}