1#// Usage: jjs -scripting gutenberg.js
2
3/*
4 * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 *   - Redistributions of source code must retain the above copyright
11 *     notice, this list of conditions and the following disclaimer.
12 *
13 *   - Redistributions in binary form must reproduce the above copyright
14 *     notice, this list of conditions and the following disclaimer in the
15 *     documentation and/or other materials provided with the distribution.
16 *
17 *   - Neither the name of Oracle nor the names of its
18 *     contributors may be used to endorse or promote products derived
19 *     from this software without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
22 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
23 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
25 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
26 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
27 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 */
33
34// Simple example that demonstrates reading XML Rss feed
35// to generate a HTML file from script and show it by browser
36
37// Java classes used
38var Characters = Java.type("javax.xml.stream.events.Characters");
39var Factory = Java.type("javax.xml.stream.XMLInputFactory");
40var File = Java.type("java.io.File");
41var FileWriter = Java.type("java.io.FileWriter");
42var PrintWriter = Java.type("java.io.PrintWriter");
43var URL = Java.type("java.net.URL");
44
45// read Rss feed from a URL. Returns an array
46// of objects having only title and link properties
47function readRssFeed(url) {
48    var fac = Factory.newInstance();
49    var reader = fac.createXMLEventReader(url.openStream());
50
51    // get text content from next event
52    function getChars() {
53        var result = "";
54        var e = reader.nextEvent();
55        if (e instanceof Characters) {
56            result = e.getData();
57        }
58        return result;
59    }
60
61    var items = [];
62    var title, link;
63    var inItem = false;
64    while (reader.hasNext()) {
65        var evt = reader.nextEvent();
66        if (evt.isStartElement()) {
67            var local = evt.name.localPart;
68            if (local == "item") {
69               // capture title, description now
70               inItem = true;
71            }
72
73            if (inItem) {
74                switch (local) {
75                    case 'title':
76                        title = getChars();
77                        break;
78                    case 'link':
79                        link = getChars();
80                        break;
81                }
82            }
83        } else if (evt.isEndElement()) {
84            var local = evt.name.localPart;
85            if (local == "item") {
86                // one item done, save it in result array
87                items.push({ title: title, link: link });
88                inItem = false;
89            }
90        }
91    }
92
93    return items;
94}
95
96// generate simple HTML for an RSS feed
97function getBooksHtml() {
98    var url = new URL("http://www.gutenberg.org/cache/epub/feeds/today.rss");
99    var items = readRssFeed(url);
100
101    var str = "<ul>";
102
103    // Nashorn's string interpolation and heredoc
104    // support is very handy in generating text content
105    // that is filled with elements from runtime objects.
106    // We insert title and link in <li> elements here.
107    for each (i in items) {
108        str += <<EOF
109<li>
110    <a href="${i.link}">${i.title}</a>
111</li>
112EOF
113    }
114    str += "</ul>";
115    return str;
116}
117
118// write the string to the given file
119function writeTo(file, str) {
120    var w = new PrintWriter(new FileWriter(file));
121    try {
122        w.print(str);
123    } finally {
124        w.close();
125    }
126}
127
128// generate books HTML
129var str = getBooksHtml();
130
131// write to file. __DIR__ is directory where
132// this script is stored.
133var file = new File(__DIR__ + "books.html");
134writeTo(file, str);
135
136// show it by desktop browser
137try {
138    var Desktop = Java.type("java.awt.Desktop");
139    Desktop.desktop.browse(file.toURI());
140} catch (e) {
141    print(e);
142}
143