001/**
002 *
003 * Copyright the original author or authors
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.delay.provider;
018
019import java.text.ParseException;
020import java.util.Date;
021
022import org.jivesoftware.smack.packet.PacketExtension;
023import org.jivesoftware.smack.provider.PacketExtensionProvider;
024import org.jivesoftware.smack.util.XmppDateTime;
025import org.jivesoftware.smackx.delay.packet.DelayInformation;
026import org.xmlpull.v1.XmlPullParser;
027
028/**
029 * The DelayInformationProvider parses DelayInformation packets.
030 * 
031 * @author Gaston Dombiak
032 * @author Henning Staib
033 */
034public class DelayInformationProvider implements PacketExtensionProvider {
035    
036    public PacketExtension parseExtension(XmlPullParser parser) throws Exception {
037        String stampString = (parser.getAttributeValue("", "stamp"));
038        Date stamp = null;
039        
040        try {
041            stamp = XmppDateTime.parseDate(stampString);
042        }
043        catch (ParseException parseExc) {
044            /*
045             * if date could not be parsed but XML is valid, don't shutdown
046             * connection by throwing an exception instead set timestamp to epoch 
047             * so that it is obviously wrong. 
048             */
049            if (stamp == null) {
050                stamp = new Date(0);
051            }
052        }
053        
054        
055        DelayInformation delayInformation = new DelayInformation(stamp);
056        delayInformation.setFrom(parser.getAttributeValue("", "from"));
057        String reason = parser.nextText();
058
059        /*
060         * parser.nextText() returns empty string if there is no reason.
061         * DelayInformation API specifies that null should be returned in that
062         * case.
063         */
064        reason = "".equals(reason) ? null : reason;
065        delayInformation.setReason(reason);
066        
067        return delayInformation;
068    }
069}