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