AtomFeed.cs :  » RSS-RDF » GtkSharpRSS » Atom » Core » C# / CSharp Open Source

Home
C# / CSharp Open Source
1.2.6.4 mono .net core
2.2.6.4 mono core
3.Aspect Oriented Frameworks
4.Bloggers
5.Build Systems
6.Business Application
7.Charting Reporting Tools
8.Chat Servers
9.Code Coverage Tools
10.Content Management Systems CMS
11.CRM ERP
12.Database
13.Development
14.Email
15.Forum
16.Game
17.GIS
18.GUI
19.IDEs
20.Installers Generators
21.Inversion of Control Dependency Injection
22.Issue Tracking
23.Logging Tools
24.Message
25.Mobile
26.Network Clients
27.Network Servers
28.Office
29.PDF
30.Persistence Frameworks
31.Portals
32.Profilers
33.Project Management
34.RSS RDF
35.Rule Engines
36.Script
37.Search Engines
38.Sound Audio
39.Source Control
40.SQL Clients
41.Template Engines
42.Testing
43.UML
44.Web Frameworks
45.Web Service
46.Web Testing
47.Wiki Engines
48.Windows Presentation Foundation
49.Workflows
50.XML Parsers
C# / C Sharp
C# / C Sharp by API
C# / CSharp Tutorial
C# / CSharp Open Source » RSS RDF » GtkSharpRSS 
GtkSharpRSS » Atom » Core » AtomFeed.cs
/* 
    * AtomFeed.cs
  * [ part of Atom.NET library: http://atomnet.sourceforge.net ]
  * Author: Lawrence Oluyede
  * License: BSD-License (see below)
    
  Copyright (c) 2003, 2004 Lawrence Oluyede
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
    * this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
    * notice, this list of conditions and the following disclaimer in the
    * documentation and/or other materials provided with the distribution.
    * Neither the name of the copyright owner nor the names of its
    * contributors may be used to endorse or promote products derived from
    * this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
    AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
    LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
    CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Xml;
using System.Xml.XPath;
using Atom.Core.Collections;
using Atom.AdditionalElements;
using Atom.Utils;

namespace Atom.Core{
  /// <summary>
  /// The Atom feed.
  /// <seealso cref="AtomEntry"/>
  /// </summary>
  [Serializable]
  public class AtomFeed : AtomElement
  {
    private AtomContentConstruct _title = null;
    private AtomLinkCollection _links = new AtomLinkCollection();
    private AtomPersonConstruct _author = null;
    private AtomPersonConstructCollection _contributors = new AtomPersonConstructCollection();
    private AtomContentConstruct _tagline = null;
    private Uri _id = DefaultValues.Uri;
    private AtomGenerator _generator = new AtomGenerator();
    private AtomContentConstruct _copyright = null;
    private AtomContentConstruct _info = null;
    private AtomDateConstruct _modified = null;
    private AtomEntryCollection _entries = new AtomEntryCollection();
    private ScopedElementCollection _additionalElements = new ScopedElementCollection();
    private Encoding _encoding = DefaultValues.Encoding;

    /// <summary>
    /// Initialize a new instance of the <see cref="AtomFeed"/> class.
    /// </summary>
    public AtomFeed() {}

    #region Properties
    /// <summary>
    /// The version of the Atom specification.
    /// </summary>
    public string Version
    {
      get { return DefaultValues.AtomVersion; }
    }

    /// <summary>
    /// The title of the feed.
    /// </summary>
    public AtomContentConstruct Title
    {
      get { return _title; }
      set { _title = value; }
    }

    /// <summary>
    /// The links of the feed.
    /// </summary>
    public AtomLinkCollection Links
    {
      get { return _links; }
    }

    /// <summary>
    /// The author of the feed.
    /// </summary>
    public AtomPersonConstruct Author
    {
      get { return _author; }
      set { _author = value; }
    }

    /// <summary>
    /// The contributors of the feed.
    /// </summary>
    public AtomPersonConstructCollection Contributors
    {
      get { return _contributors; }
    }

    /// <summary>
    /// The tagline of the feed.
    /// </summary>
    public AtomContentConstruct Tagline
    {
      get { return _tagline; }
      set { _tagline = value; }
    }

    /// <summary>
    /// The global unique identifier of the feed.
    /// </summary>
    public Uri Id
    {
      get { return _id; }
      set { _id = value; }
    }

    /// <summary>
    /// The copyright of the feed.
    /// </summary>
    public AtomContentConstruct Copyright
    {
      get { return _copyright; }
      set { _copyright = value; }
    }

    /// <summary>
    /// The info of the feed.
    /// </summary>
    public AtomContentConstruct Info
    {
      get { return _info; }
      set { _info = value; }
    }

    /// <summary>
    /// The last time when the feed has been modified.
    /// </summary>
    public AtomDateConstruct Modified
    {
      get { return _modified; }
      set { _modified = value; }
    }

    /// <summary>
    /// The entries of the feed.
    /// </summary>
    public AtomEntryCollection Entries
    {
      get { return _entries; }
    }

    /// <summary>
    /// The encoding of the feed.
    /// </summary>
    public Encoding Encoding
    {
      get { return _encoding; }
      set { _encoding = value; }
    }

    /// <summary>
    /// The additional elements of the feed.
    /// </summary>
    public ScopedElementCollection AdditionalElements
    {
      get { return _additionalElements; }
    }

    /// <summary>
    /// Gets the local name of the feed element.
    /// </summary>
    public override string LocalName
    {
      get { return "feed"; }
    }
    #endregion Properties

    #region ToString method

    /// <summary>
    /// Converts the <see cref="AtomEntry"/> in a series of xml nodes.
    /// </summary>
    /// <returns>The string representation of <see cref="AtomEntry"/> class.</returns>
    public override string ToString()
    {
      this.Buffer.AppendFormat("<{0}", this.LocalName);

      this.WriteAttribute("version", DefaultValues.AtomVersion, false, null);
            this.WriteAttribute("xml:lang", Utils.Utils.ParseLanguage(this.XmlLang), false, null);
      this.WriteAttribute("xmlns", this.NamespaceUri, false, null);

      this.Buffer.Append(">");
      this.Buffer.Append(Environment.NewLine);
      
      #region AtomTitle

      if(this.Title == null)
        throw new RequiredElementNotFoundException("The title element must be specified.");

      this.Buffer.Append(this.Title.ToString());

      #endregion

      #region AtomLink

      foreach(AtomLink link in this.Links)
        this.Buffer.Append(link.ToString());

      #endregion

      #region AtomAuthor

      // check if all the contained entries have an author
      foreach(AtomEntry entry in this.Entries)
      {
        if(!entry.doAuthor)
        {
          if(this.Author == null)
            throw new RequiredElementNotFoundException("The author element must be specified.");

          this.Buffer.Append(this.Author.ToString());
          break;
        }
        else
          break;
      }

      #endregion

      #region AtomContributor

      foreach(AtomPersonConstruct contributor in this.Contributors)
        this.Buffer.Append(contributor.ToString());

      #endregion

      #region AtomTagline

      if(this.Tagline != null)
        this.Buffer.Append(this.Tagline.ToString());

      #endregion

      #region Id

      if(this.Id != DefaultValues.Uri)
        this.WriteElement("id", this.Id, false, null);

      #endregion

      #region AtomGenerator

      this.Buffer.Append(this._generator.ToString());
            
      #endregion

      #region AtomCopyright

      if(this.Copyright != null)
        this.Buffer.Append(this.Copyright.ToString());

      #endregion

      #region AtomInfo

      if(this.Info != null)
        this.Buffer.Append(this.Info.ToString());

      #endregion

      #region AtomModified

      if(this.Modified == null)
        throw new RequiredElementNotFoundException("The modified element must be specified.");

      this.Buffer.Append(this.Modified.ToString());

      #endregion

      #region AdditionalElements
      foreach(ScopedElement element in AdditionalElements)
        this.Buffer.Append(element.ToString());
      #endregion

      #region AtomEntry

      foreach(AtomEntry entry in this.Entries)
        this.Buffer.Append(entry.ToString());

      #endregion

      this.Buffer.AppendFormat("</{0}>", this.LocalName);
      this.Buffer.Append(Environment.NewLine);

      string output = this.Buffer.ToString();
      this.Buffer.Length = 0;

      return output;
    }

    #endregion

    #region Save methods

    /// <summary>
    /// Saves the <see cref="AtomFeed"/> to the specified <see cref="Stream"/>.
    /// </summary>
    /// <param name="stream">The <see cref="Stream"/> to write to.</param>
    /// <exception cref="ArgumentException">The encoding is not supported or the stream cannot be written to.</exception>
    /// <exception cref="ArgumentNullException">stream is null.</exception>
    /// <exception cref="RequiredElementNotFoundException">A required element is not found.</exception>
    /// <exception cref="InvalidOperationException">The internal writ</exception>
    public void Save(Stream stream)
    {
      AtomWriter writer = new AtomWriter(stream, this.Encoding);
      writer.Write(this);
    }

    /// <summary>
    /// Saves the <see cref="AtomFeed"/> to the specified filename.
    /// </summary>
    /// <exception cref="ArgumentException">The encoding is not supported; the filename is empty, contains only white space, or contains one or more invalid characters.</exception>
    /// <exception cref="UnauthorizedAccessException">Access is denied.</exception>
    /// <exception cref="ArgumentNullException">The filename is a null reference.</exception>
    /// <exception cref="DirectoryNotFoundException">The directory to write to is not found.</exception>
    /// <exception cref="IOException">The filename includes an incorrect or invalid syntax for file name, directory name, or volume label syntax.</exception>
    /// <exception cref="System.Security.SecurityException">The caller does not have the required permission.</exception>
    /// <param name="filename">The file name to write to.</param>
    public void Save(string filename)
    {
      AtomWriter writer = new AtomWriter(filename, this.Encoding);
      writer.Write(this);
    }

    /// <summary>
    /// Saves the <see cref="AtomFeed"/> to the specified <see cref="TextWriter"/>.
    /// </summary>
    /// <param name="tw">The <see cref="TextWriter"/> to write to.</param>
    public void Save(TextWriter tw)
    {
      AtomWriter writer = new AtomWriter(tw);
      writer.Write(this);
    }

    /// <summary>
    /// Saves the <see cref="AtomFeed"/> to the specified <see cref="HttpWebResponse"/>.
    /// </summary>
    /// <param name="response">The <see cref="HttpWebResponse"/> to write to.</param>
    public void Save(HttpWebResponse response)
    {
      AtomWriter writer = new AtomWriter(response.ResponseUri.ToString(), this.Encoding);
      writer.Write(this);
    }

    #endregion

    #region Load methods

    /// <summary>
    /// Loads the <see cref="AtomFeed"/> from the specified URI.
    /// </summary>
    /// <returns>An <see cref="AtomFeed"/> instance.</returns>
    /// <param name="uri">The URI of the resource containing the Atom xml data.</param>
    /// <exception cref="XmlException">Invalid xml syntax in Atom resource or uri is null.</exception>
    /// <exception cref="ArgumentException">The resource cannot be find.</exception>
    /// <exception cref="InvalidOperationException"><see cref="AtomReader"/> has been closed, and can not be read.</exception>
    /// <exception cref="FileNotFoundException">Atom xml resource not found.</exception>
    public static AtomFeed Load(string uri)
    {
      AtomReader reader = new AtomReader(uri);
      return Parse(reader.Navigator);
    }

    /// <summary>
    /// Loads the <see cref="AtomFeed"/> from the specified <see cref="Stream"/>.
    /// </summary>
    /// <returns>An <see cref="AtomFeed"/> instance.</returns>
    /// <param name="stream">The <see cref="Stream"/> containing the Atom xml data.</param>
    /// <exception cref="XmlException">Invalid xml syntax in Atom resource or uri is null.</exception>
    /// <exception cref="ArgumentException">The resource cannot be find.</exception>
    /// <exception cref="InvalidOperationException"><see cref="AtomReader"/> has been closed, and can not be read.</exception>
    /// <exception cref="FileNotFoundException">Atom xml resource not found.</exception>
    public static AtomFeed Load(Stream stream)
    {
      AtomReader reader = new AtomReader(stream);
      return Parse(reader.Navigator);
    }

    /// <summary>
    /// Loads the <see cref="AtomFeed"/> from the specified <see cref="TextReader"/>.
    /// </summary>
    /// <returns>An <see cref="AtomFeed"/> instance.</returns>
    /// <param name="tr">The <see cref="TextReader"/> from which read the Atom xml data.</param>
    /// <exception cref="XmlException">Invalid xml syntax in Atom resource or uri is null.</exception>
    /// <exception cref="ArgumentException">The resource cannot be find.</exception>
    /// <exception cref="InvalidOperationException"><see cref="AtomReader"/> has been closed, and can not be read.</exception>
    /// <exception cref="FileNotFoundException">Atom xml resource not found.</exception>
    public static AtomFeed Load(TextReader tr)
    {
      AtomReader reader = new AtomReader(tr);
      return Parse(reader.Navigator);
    }

    /// <summary>
    /// Loads the <see cref="AtomFeed"/> from the specified <see cref="HttpWebRequest"/>.
    /// </summary>
    /// <returns>An <see cref="AtomFeed"/> instance.</returns>
    /// <param name="request">The <see cref="HttpWebRequest"/> from which read the Atom xml data.</param>
    /// <exception cref="XmlException">Invalid xml syntax in Atom resource or uri is null.</exception>
    /// <exception cref="ArgumentException">The resource cannot be find.</exception>
    /// <exception cref="InvalidOperationException"><see cref="AtomReader"/> has been closed, and can not be read.</exception>
    /// <exception cref="FileNotFoundException">Atom xml resource not found.</exception>
    public static AtomFeed Load(HttpWebRequest request)
    {
      AtomReader reader = new AtomReader(request.RequestUri.ToString());
      return Parse(reader.Navigator);
    }

    /// <summary>
    /// Loads the <see cref="AtomFeed"/> from the specified xml fragment.
    /// </summary>
    /// <returns>An <see cref="AtomFeed"/> instance.</returns>
    /// <param name="xmlFragment">The string containing the Atom xml data.</param>
    /// <exception cref="XmlException">Invalid xml syntax in Atom resource or uri is null.</exception>
    /// <exception cref="ArgumentException">The resource cannot be find.</exception>
    /// <exception cref="InvalidOperationException"><see cref="AtomReader"/> has been closed, and can not be read.</exception>
    /// <exception cref="FileNotFoundException">Atom xml resource not found.</exception>
    public static AtomFeed LoadXml(string xmlFragment)
    {
      XmlTextReader xmlReader = new XmlTextReader(xmlFragment, XmlNodeType.Element, null);
      AtomReader reader = new AtomReader(xmlReader);
      return Parse(reader.Navigator);
    }

    #endregion

    #region XPath parsing stuff
    internal static AtomFeed Parse(XPathNavigator navigator)
    {
      AtomFeed feed = new AtomFeed();

      XPathNavigator nav = navigator.Clone();
      XPathNodeIterator iter = nav.SelectChildren(XPathNodeType.All);
      
      do
      {
        string name = iter.Current.Name.ToLower();
        int idx = name.IndexOf(":");
        if(idx != -1)
          name = name.Split(new char[] {':'}, 2)[1];

        switch(name)
        {
          case "feed":
          {
            try
            {
              feed.XmlLang = Utils.Utils.ParseLanguage(iter.Current.XmlLang);
            }
            catch {}

            XPathNodeIterator attrIterator = nav.Select("@version");
            while(attrIterator.MoveNext())
            {
              if(attrIterator.Current.Name.ToLower() == "version")
              {
                if(attrIterator.Current.Value != DefaultValues.AtomVersion)
                {
                  string msg = String.Format("Atom {0} version is not supported!", iter.Current.Value);
                  throw new InvalidOperationException(msg);
                }
              }
            }
            break;
          }

          case "title":
            AtomContentConstruct content = AtomContentConstruct.Parse(iter.Current);
            feed.Title = content;
            break;

          case "link":
            feed.Links.Add(AtomLink.Parse(iter.Current));
            break;

          case "author":
            feed.Author = AtomPersonConstruct.Parse(iter.Current);
            break;

          case "contributor":
            feed.Contributors.Add(AtomPersonConstruct.Parse(iter.Current));
            break;

          case "tagline":
            feed.Tagline = AtomContentConstruct.Parse(iter.Current);
            break;

          case "id":
            feed.Id = new Uri(iter.Current.Value);
            break;
      
          case "copyright":
            feed.Copyright = AtomContentConstruct.Parse(iter.Current);
            break;

          case "info":
            feed.Info = AtomContentConstruct.Parse(iter.Current);
            break;

          case "modified":
            feed.Modified = AtomDateConstruct.Parse(iter.Current);
            break;

          case "entry":
            feed.Entries.Add(AtomEntry.Parse(iter.Current));
            break;

        }
      } while(iter.MoveNext());

      return feed;
    }
    #endregion
  }
}
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.