001/**
002 *
003 * Copyright 2017 Paul Schaub
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.omemo.provider;
018
019import static org.jivesoftware.smackx.omemo.element.OmemoDeviceListElement.DEVICE;
020import static org.jivesoftware.smackx.omemo.element.OmemoDeviceListElement.ID;
021import static org.jivesoftware.smackx.omemo.element.OmemoDeviceListElement.LIST;
022import static org.xmlpull.v1.XmlPullParser.END_TAG;
023import static org.xmlpull.v1.XmlPullParser.START_TAG;
024
025import java.util.HashSet;
026import java.util.Set;
027
028import org.jivesoftware.smack.provider.ExtensionElementProvider;
029
030import org.jivesoftware.smackx.omemo.element.OmemoDeviceListVAxolotlElement;
031
032import org.xmlpull.v1.XmlPullParser;
033
034/**
035 * Smack ExtensionProvider that parses OMEMO device list element into OmemoDeviceListElement objects.
036 *
037 * @author Paul Schaub
038 */
039public class OmemoDeviceListVAxolotlProvider extends ExtensionElementProvider<OmemoDeviceListVAxolotlElement> {
040
041    @Override
042    public OmemoDeviceListVAxolotlElement parse(XmlPullParser parser, int initialDepth) throws Exception {
043        Set<Integer> deviceListIds = new HashSet<>();
044        boolean stop = false;
045        while (!stop) {
046            int tag = parser.next();
047            String name = parser.getName();
048            switch (tag) {
049                case START_TAG:
050                    if (name.equals(DEVICE)) {
051                        for (int i = 0; i < parser.getAttributeCount(); i++) {
052                            if (parser.getAttributeName(i).equals(ID)) {
053                                Integer deviceId = Integer.parseInt(parser.getAttributeValue(i));
054                                deviceListIds.add(deviceId);
055                            }
056                        }
057                    }
058                    break;
059                case END_TAG:
060                    if (name.equals(LIST)) {
061                        stop = true;
062                    }
063                    break;
064            }
065        }
066        return new OmemoDeviceListVAxolotlElement(deviceListIds);
067    }
068}