001/*
002 *
003 * Copyright 2016-2019 Florian Schmaus
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.iot.discovery.provider;
018
019import java.io.IOException;
020import java.util.ArrayList;
021import java.util.List;
022
023import org.jivesoftware.smack.packet.IqData;
024import org.jivesoftware.smack.packet.XmlEnvironment;
025import org.jivesoftware.smack.provider.IqProvider;
026import org.jivesoftware.smack.util.ParserUtils;
027import org.jivesoftware.smack.xml.XmlPullParser;
028import org.jivesoftware.smack.xml.XmlPullParserException;
029
030import org.jivesoftware.smackx.iot.discovery.element.IoTRegister;
031import org.jivesoftware.smackx.iot.discovery.element.Tag;
032import org.jivesoftware.smackx.iot.element.NodeInfo;
033import org.jivesoftware.smackx.iot.parser.NodeInfoParser;
034
035import org.jxmpp.JxmppContext;
036
037public class IoTRegisterProvider extends IqProvider<IoTRegister> {
038
039    @Override
040    public IoTRegister parse(XmlPullParser parser, int initialDepth, IqData iqData, XmlEnvironment xmlEnvironment, JxmppContext jxmppContext) throws XmlPullParserException, IOException {
041        boolean selfOwned = ParserUtils.getBooleanAttribute(parser, "selfOwned", false);
042        NodeInfo nodeInfo = NodeInfoParser.parse(parser);
043        List<Tag> tags = new ArrayList<>();
044        while (parser.getDepth() != initialDepth) {
045            XmlPullParser.Event event = parser.next();
046            if (event != XmlPullParser.Event.START_ELEMENT) {
047                continue;
048            }
049            final String element = parser.getName();
050            Tag.Type type = null;
051            switch (element) {
052            case "str":
053                type = Tag.Type.str;
054                break;
055            case "num":
056                type = Tag.Type.num;
057                break;
058            }
059            if (type == null) {
060                continue;
061            }
062            String name = parser.getAttributeValue(null, "name");
063            String value = parser.getAttributeValue(null, "value");
064            tags.add(new Tag(name, type, value));
065        }
066        return new IoTRegister(tags, nodeInfo, selfOwned);
067    }
068
069}