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