summaryrefslogtreecommitdiff
path: root/src/library/scala/xml/parsing/ExternalSources.scala
blob: 3289d3628d4ef4e5cf8986c2d6995d8366d51c0d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*                     __                                               *\
**     ________ ___   / /  ___     Scala API                            **
**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
\*                                                                      */

// $Id$


package scala.xml.parsing

import java.net.URL

import scala.io.Source

/**
 *  @author  Burak Emir
 *  @version 1.0
 */
trait ExternalSources { self: ExternalSources with MarkupParser with MarkupHandler =>

  private def externalSourceFromURL(url: URL): Source = {
    import java.io.{BufferedReader, InputStreamReader}
    val in =
      new BufferedReader(
        new InputStreamReader(
	  url.openStream()))

    //@todo: replace this hack with proper Source implementation

    val str = new StringBuilder()
    var inputLine: String = null

    //while (inputLine = in.readLine()) != null) {
    while ({inputLine = in.readLine(); inputLine} ne null) {
      // Console.println(inputLine)  // DEBUG
      str.append(inputLine)
      str.append('\n')  // readable output
    }
    in.close()

    class MyClass extends Source {

      def newIter = new Iterator[Char] {
        var i = -1
        private val len = str.length-1
        def hasNext = i < len
        def next = { i += 1; str.charAt(i) }
      }

      val iter = newIter

      def reset: Source = new MyClass

      /*override var*/ descr = url.toExternalForm()
    }

    new MyClass
  }

  /** ...
   *
   *  @param systemId ...
   *  @return         ...
   */
  def externalSource(systemId: String): Source = {
    if (systemId startsWith "http:")
      return externalSourceFromURL(new URL(systemId))

    var fileStr = input.descr

    if (input.descr startsWith "file:") {
      fileStr = input.descr.substring(5, input.descr.length)
    } else
      fileStr = fileStr.substring(0,
                                  fileStr.lastIndexOf(java.io.File.separator)+1)
    Source.fromFile(fileStr + systemId)
  }

}