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