summaryrefslogtreecommitdiff
path: root/test/files/jvm/xmlLiterals.scala
blob: 3548975fe11480d43653a0b466259cd957e7e472 (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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
//############################################################################
// XML Literals
//############################################################################
// $Id$

import scala.testing.UnitTest._ ;

import scala.xml._ ;
import scala.collection.immutable ;


object Test  {

    val e = Node.NoAttributes;

    /* a helper function to compare up to whitespace */

    def noWS(x:String):String = {
      val res = new StringBuffer();
      var i = 0; while( i < x.length() ) {
        val c = x.charAt( i );
        c match {
          case ' ' | '\n' | '\t' =>
            case _ => res.append( c )
        }
        i = i + 1;
      }
      res.toString();
    }


  object Test01Literals {



    /*                                             === tags, elements === */

    assertEquals( <hello></hello>.toString(),
                  <hello  ></hello>.toString());           /* ws in tags */

    assertEquals( <hello></hello>.toString(),
                  noWS(<hello  >   </hello>.toString()));

    val xx3 = <hello>
    <world></world>
    <test/>
    <mars></mars></hello>;

    val x3 = xx3.toString();          /* ws in element content */

    //Console.println("tmp1:"+x3);
    //Console.println("tmp2:"+Elem(null,"mars",e,TopScope).toString() );
    assertEquals( noWS( x3 ),
                  Elem(null,"hello",e,TopScope,
                       Elem(null,"world",e,TopScope),
                       Elem(null,"test",e,TopScope),
                       Elem(null,"mars",e,TopScope)).toString() );


    Console.println("ws trimming in patterns");

    assertEquals( true, <hello> <world/>    </hello> match {
      case <hello>    <world/> </hello>     => true;
      case _ => false;} );


  /*                                                === attributes === */

    val z = <html>
            <body background="#FFFFFF">
              <h1>Hello World</h1>
              <p>Check the <a href="scala.epfl.ch">scala</a> page!</p>
            </body>
          </html>.toString();

    assertEquals( noWS( z ), noWS(
      Elem(null,"html",e,TopScope,
           Elem(null,"body",e,TopScope,
                Elem(null,"h1",e,TopScope,Text("Hello World")),
                Elem(null,"p",e,TopScope,Text("Check the "),
                     Elem(null,"a", e,TopScope,Text("scala"))
                     % (new UnprefixedAttribute("href","scala.epfl.ch",Null)),
                     Text("page!"))
              ) % new UnprefixedAttribute("background","#FFFFFF",Null)
         ).toString()
    ));

    /*                                  === attributes are Scala expr === */

    val testValue = "This is a test.";
    val testValue2 = 42;
    val page = <testTag value={ testValue } ab="bkla" />;
    val page2 = <testTag value={testValue2.toString()} bla="foo"></testTag>;

    Console.println( page.toString() );
    Console.println( page2.toString() );

  }

  object Test02Embed {

    /*                                    === embedded Scala blocks  === */

    def computeDate() = {
      Elem(null,"date", e, TopScope, Text("now!"));
    }
    /* embedding Scala strings as text and elements  */
    val sc = <hello>{ "World" }{ Text("42") }{ computeDate() }</hello>;

    assertEquals( sc.child.elements.toList,
                 List( Text("World"), Text("42"), Elem(null, "date", e,TopScope, Text("now!") ) ) );

    assertEquals( sc.toString(),
                 Elem(null,"hello",e,TopScope,Text("World42"),Elem(null,"date",e,TopScope, Text("now!"))).toString() );

    def foo( m:Node ):String = m match {
      case <hello/> => "hello node"
      case <hallo ></hallo > => "hallo node"
      case <test>{ z }</test> => "test node:"+z
      case <list>{ e1:Node }{ e2:Node }{ _* }</list> => e1.toString() + e2.toString();
    }

    assertEquals( foo(<hello/>), "hello node" );
    assertEquals( foo(<hallo/>), "hallo node" );
    assertEquals( foo(<test>42</test>), "test node:42" );
    assertEquals( foo(<list><a/><b><c/></b><d/><d/></list>),
     	         <a/>.toString() + <b><c/></b>.toString() );

    val rows = <tr>
		<td>1.1</td><td>1.2</td>
             </tr>
             <tr>
		<td>2.1</td><td>2.2</td>
             </tr>;

    assertEquals( noWS( rows.toList.toString() ),
                 noWS( List(Elem(null,"tr",e,TopScope,
                                 Elem(null,"td",e,TopScope,Text("1.1")),Elem(null,"td",e,TopScope, Text("1.2"))
                               ),
		            Elem(null,"tr",e,TopScope,
                                 Elem(null,"td",e,TopScope,Text("2.1")),Elem(null,"td",e,TopScope,Text("2.2"))
                               )
                          ).toString() )
               );
    val rows2 = <tr><!-- an XML comment --><?pinotext?><?pi text?></tr>;
    val rows3 = <tr> a <!-- an XML comment --> b <?pinotext?> c <?pi text?> d </tr>;

    // these are not equal as comments are valid XML Info items.
    assertEquals( rows2, Elem(null,"tr",e,TopScope,Comment(" an XML comment "),ProcInstr("pinotext",""),ProcInstr("pi","text")));

    assertEquals( rows3, Elem(null,"tr",e,TopScope,Text("a"),Comment(" an XML comment "),Text("b"),ProcInstr("pinotext",""),Text("c"),ProcInstr("pi","text"),Text("d")));

  }

object Test03Servlet {

  val headerMsg = Text("What follows is an example of modular formatting.");
  val footerMsg = Text("Complicated layout tasks can be encapsulated and outsourced.");

  /** helper function for the main page, provides header and a footer
   */
  def page( ns:Seq[Node] ) = {
    <html>
      <head>
        <title>ModularFormatting</title>
      </head>
      <body>
        <h2>Welcome</h2>
        <p>
          {headerMsg }
        </p>
        <p>
          { ns }
        </p>
        <p>
          { 1 } {'a'} { 23.23 }
        </p>
        <p>
          { for(val n <- ns.toList)  yield { n::n::Nil } }
        </p>
        <hr/>
        <p>
          {footerMsg}
        </p>
        <h2>Bye!</h2>
      </body>
    </html>
  }

  /** applies beautify to every element in a sequence
   */
  def beautify( xs:Seq[Node] ):Seq[Node] = xs.toList.map { beautify }

  /** this is a recursive procedure that adds some attributes to the tree
   */
  def beautify( n:Node ):Node = n match {
    case <td>{xs @ _* }</td> =>
          <td bgcolor="#AAAAFF" color="#222255">{ xs }</td>

    case <table>{ xs @ _* }</table> =>
          <table align="center">{ beautify( xs )}</table>

    case Elem(null, label, _, _, xs @ _* ) =>
          new Elem(null, label, e, TopScope, beautify( xs ):_*)

    case _ => n
  }

  /** this function will take a node and put it in a table
   */
  def format( msg:Node ):Node = {
    <table>
      <tr>
        <td>{ msg }</td>
      </tr>
    </table>
  }

  /** returns a highlighted text node with the string given as arguemnt. if it
   *  is null, supplies a default string.
   */
  def getMessage( x:String ) = {
    if( x == null )
      <h1> This could be YOUR message ! </h1>
    else
      <h1> { Text( x ) } </h1>
  }

  /** the entry method
   */
  def doGetXML() = {
    beautify( page( List( format( getMessage( "message" ) )) ));
    //page( List( format( theMessage )));
  }

  def main( args:Array[String] ) = {
    val x = doGetXML();
    Console.println( x );
    Console.println( new PrettyPrinter( 80, 2 ).format( x ));
  }

}


  object Test04 {
    val sequence = <foo/>
                 <bar>Text</bar>
                 <foo/>;

    Console.println( sequence );

    val onlyOne = <foo/>;

    Console.println( onlyOne );

    val tryBrace = <try>Now escaped {{ braces } </try>;
    assertEquals( tryBrace, Elem(null,"try",e,TopScope,Text("Now escaped { braces }")));

    val tryBrace2 = <try myAttrib={(3+4).toString() }> cool ?</try>;
    assertEquals( tryBrace2.attribute("myAttrib"), "7" );

    /* Scala comments are not allowed in XML literals. see neg(2) */
    val zzz = <hello>/* no comment */</hello>;
    assertEquals( zzz, Elem(null,"hello", e,TopScope, Text("/* no comment */")));

  }


  def test05main = {
    val x1s = <foo>&#0123;</foo>.toString();
    Console.println( x1s );
    val x2 = <foo>&nbsp;&#x7b;<bar><baz/></bar><bar/></foo>.toString();
    Console.println( x2 );
  }

    def test06 = {

      val foo =
        <bar:foo xmlns:bar="www.bar.com" xmlns="www.baz.com">
          <baz/>
      </bar:foo>;

      Console.println( foo );

    }


  def main( args:Array[String] ):Unit = {
    Console.println("Test01Literals");
    Test01Literals;
    Console.println("Test02Embed");
    Test02Embed;
    Console.println("Test03Servlet");
    Test03Servlet.main( args );
    Console.println("Test04");
    Test04;
    Console.println("Test05Ref");
    test05main;
    Console.println("namespace");
    test06;{
    }
  }


}