001/**
002 *
003 * Copyright 2013-2014 Georg Lukas
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.carbons.provider;
018
019import org.jivesoftware.smack.SmackException;
020import org.jivesoftware.smack.provider.ExtensionElementProvider;
021
022import org.jivesoftware.smackx.carbons.packet.CarbonExtension;
023import org.jivesoftware.smackx.carbons.packet.CarbonExtension.Direction;
024import org.jivesoftware.smackx.forward.packet.Forwarded;
025import org.jivesoftware.smackx.forward.provider.ForwardedProvider;
026
027import org.xmlpull.v1.XmlPullParser;
028
029/**
030 * This class implements the {@link ExtensionElementProvider} to parse
031 * carbon copied messages from a packet.  It will return a {@link CarbonExtension} stanza extension.
032 *
033 * @author Georg Lukas
034 *
035 */
036public class CarbonManagerProvider extends ExtensionElementProvider<CarbonExtension> {
037
038    private static final ForwardedProvider FORWARDED_PROVIDER = new ForwardedProvider();
039
040    @Override
041    public CarbonExtension parse(XmlPullParser parser, int initialDepth)
042                    throws Exception {
043        Direction dir = Direction.valueOf(parser.getName());
044        Forwarded fwd = null;
045
046        boolean done = false;
047        while (!done) {
048            int eventType = parser.next();
049            if (eventType == XmlPullParser.START_TAG && parser.getName().equals("forwarded")) {
050                fwd = FORWARDED_PROVIDER.parse(parser);
051            }
052            else if (eventType == XmlPullParser.END_TAG && dir == Direction.valueOf(parser.getName()))
053                done = true;
054        }
055        if (fwd == null)
056            throw new SmackException("sent/received must contain exactly one <forwarded> tag");
057        return new CarbonExtension(dir, fwd);
058    }
059}