Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
XML-Javascript
1. Administrative Stuff
Lab #4 due August 9
XML and JavaScript HW #4 due August 11
Lecture 10 Final exam
Friday, 8/13
cs193i – Internet Technologies Gates B03
Summer 2004 7-10pm
Stanford University
What is JSP? A JSP File
Separate computation from presentation
Presentation: JSP
Computation: Servlet
Mostly HTML page, with extension .jsp
Include JSP tags to enable dynamic content
creation
Translation: JSP → Servlet class
Compiled at request time
Expression Language EL Examples
Makes syntax short and readable, like JavaScript <input name=“firstName” value=“${customer.firstName}”>
${expression} <c:out value=“${order.amount + 5}”/>
Arithmetic ${order.amount + 5}
${1.2 + 2.3} → 3.5
{order['amount'] + 5}
Comparisons
${4.0 >= 3} → true
Implicit Objects
${param.foo} → JSP 2.0
${param["foo"]} → JSP 2.0
Functions
${my:reverse(my:reverse(param["foo"]))} → JSP 2.0
2. XML
XML → Extensible Markup Language
Just a text file, with tags, attributes, free text...
looks much like HTML
Purpose XML Describes Data
Used to create special-purpose markup DTD -- formal description of the class of XML
languages document your file adheres to (like file
Facilitates sharing of structured text and extension)
information across the Internet. Buzzword: DTD is one way to describe XML
"Schema" (grammar). There are other ways...
XML Structure Facilitates Parsing of Data
Two Apps still have to agree on what the
meaning of the "descriptive tags"
XML Nested Tags Apple Safari Bookmarks
Like a tree, each element is contained inside a parent
element
Each element may have any number of attributes
<book>…</book>
<chapter>…</chapter> <chapter>…</chapter> pages=“30”
<title>…</title> … <para>…</para> </br> <figure>…</figure>
This is some text!
3. Property List Editor Apple Bookmarks
Document Data Type XML Structure
Nested Tags
Here's some text <red>surrounded <important>by
tags</important></red>
Empty Tags
<tag></tag> → <tag/>
Attributes -- Variable Value Bindings in the Tag
<dot x="72" y="13"/>
Free Text
<dot x="1" y="1">I'm free!!!</dot>
Special Characters Organization Strategies
< < XML Text -- blocks of free text with tags to
> > mark sections
& & <foo>And here is some <b>text</b></foo>
" " XML Tree -- nested tags, only leaf-nodes have
free text
' '
4. XML Tree Sub-Tags vs. Attributes
<person> Sub-Tags
<name> <dot>
<first>Hans</first> <x>13</x>
<last>Gruber</last> <y>57</y>
</dot>
</name>
<id>123456</id> Attributes
<username>hans</username> <dot x="13" y="57"/>
</person>
When to use Attributes When to use Tags
Whenever Possible <parent>
<child>...</child>
Sub-Data is short & simple, and doesn't repeat <child>...</child>
<child>...</child>
<dot x="13" y="56"/>
</parent>
NOT: <dots>
<dot x="13" y="15"/>
<dots x1="13" y1="56" x2="14“ y2="67 x3="56"
<dot x="1" y="3"/>
y3="100" ... /> ...
</dots>
<description>This is a super long description that should be put
between tags, as opposed to in an attribute... </description>
XML Example - Dots XML and Java
<?xml version="1.0" encoding="UTF-8"?> Meaning
http://java.sun.com/xml/index.jsp
<dots>
<dot x="1" y="2" /> (1, 2)
(3, 4)
Java API for XML...
<dot x="3" y="4" />
Binding (JAXB) -- for working w/ Schemas
<flip>
<dot x="5" y="6" /> (6, 5) Processing (JAXP) -- for Parsing!
<flip>
<dot x="7" y="8" /> (7, 8)
</flip>
</flip>
<dot x="9" y="10" /> (9, 10)
</dots>
5. JAXP Parsing Strategies SAX
SAX -- Simple API for XML Subclass DefaultHandler
Simple Parser Implement Notification
Methods ("Callbacks")
DOM -- Document Object Model
startElement(...) // handles
Represent XML Doc as Tree of Nodes in Memory open tag <a_tag>
endElement(...) // handles
close tag </a_tag>
characters(...) // handles
http://sax.sourceforge.net/
stuff in between
Read in the XML File
http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPIntro.html
mydots.xml SAX Example
SAXParserFactory factory = SAXParserFactory.newInstance();
<dots>
SAXParser saxParser = factory.newSAXParser();
<dot x="81" y="67" /> saxParser.parse(
<dot x="175" y="122" /> new BufferedInputStream(new FileInputStream(
<flip> new File(argv[0]))), new XMLDotReader());
<dot x="175" y="122" />
<dot x="209" y="71" />
</flip>
XMLDotReader Class
<dot x="209" y="71" /> • Maintains flip state in boolean
<flip> • extends DefaultHandler
<flip><dot x="133" y="877">My Favorite Dot!</dot></flip> • overrides startElement(...)
<dot x="1" y="2"/> • Check if dot tag or flip tag
</flip>
</dots>
• Do stuff, accordingly
• overrides endElement(...)
• If flip tag... "unflip"
DOM DOM Example
// Step 1: create a DocumentBuilderFactory
Get a DocumentBuilder // and setNamespaceAware
DocumentBuilderFactory dbf =
Read in an XML File, DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
get a Document object
// Step 2: create a DocumentBuilder
Traverse the Document DocumentBuilder db = dbf.newDocumentBuilder();
object and do stuff // Step 3: parse the input file to get a Document object
Document doc = db.parse(new File(filename));
http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAX Node n = (Node) doc;
PDOM.html#wp79996 ...
int type = n.getNodeType();
for (Node child = n.getFirstChild(); child!=null;
child=child.getNextSibling()) {
...
}
http://java.sun.com/developer/earlyAccess/xml/examples/DOMEcho/DOMEcho.java
6. SAX vs. DOM Other Java Parsers
SAX -- Event Driven, Serial Access, Element by There are other free parsers out there, that use
Element either SAX or DOM strategies...
Preferred for Server Side Apps “nanoxml”
DOM -- Read in whole XML structure, CPU & “JDOM”
memory intensive
Ideal for interactive apps (Thick Clients); allows
interactive editing of XML structure in memory
XML Uses Strengths and Weaknesses
Config Files Strengths Weaknesses
Apple Property List Just Text: Compatible Verbose/Redundant
with Web/Internet Trouble modeling
Data Files Protocols overlapping data
SVG Human + Machine structures (non
Readable hierarchical)
Messages
SOAP Represents most CS
datastructures well
Strict Syntax → Parsing
Fast and Efficient
JavaScript
Invented by Netscape Communications
Cross Platform, Object-based, Scripting
Five Minute Break Language
ECMAScript (ECMA-262)
7. JavaScript JavaScript
All Client Side
HTTP Request Can
Adjust HTML
HTTP Response Open Windows, Resize Windows
Client runs
JavaScript HTML file with Animations, Play Sounds
embedded JavaScript
Cannot
Access File System
Do Networking
JavaScript JavaScript Basics
Advantages <script> section in HTML runs on document
Better User Experience load
(2X Latency) No type declarations
Disadvantages undefined if not given a value
Thicker Client Global variables by default
Possible Abuse var makes them local
Generate Dynamic HTML JavaScript and Browser
...
<BODY>
document – HTML document
...Regular HTML Here.... document.name – named element in document
<SCRIPT TYPE="text/javascript"> document.images – array of images
<!-- document.forms – array of forms
BUILD HTML HERE!!!
//--> Ways to access window, cookies, etc.
</SCRIPT>
...More Regular HTML....
</BODY>
9. Monitor User Events DOM
JavaScript is Object-Oriented
JavaScript Interacts with Document Object
Model of Browser
DOM Not Totally Standardized
www.devguru.com
Objects Arrays or Objects?
The Same!
a.foo <=> a["foo"] <=> a[x]
a[2] cannot be accessed as a.2
http://www.devguru.com
Global Functions Communicating with User
escape(string) Alert window.alert("Hello!");
unescape(string) Confirm window.confirm("Delete files? =D")
Safe Strings Status Bar window.status = "Hi!";
ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
1234567890
@*-_+./
Unsafe Strings => %20, %5c, etc...
10. <html>
<head> <body>
<title>JS Demo</title> <p>
<script language="JavaScript"> <button onClick="hello('hi there');" >Say Hello</button>
function hello(greeting) { <br><button onClick="upCount();" >Count</button>
var str = greeting + "!!!"; <br><a onClick="alert('holy ####!')">oops</a>
alert(str); <p>
} Thing you are afraid of...
count = 0; <form name=affirm>
function upCount() { <input type=text name=fear>
count++; <p><input type=button onClick="noFear();" value="No Fear">
alert(count); Mock mode:<input type=checkbox name=mockMode>
} <p><input type=text size=40 name=mock>
function noFear() { </form>
var fear = document.affirm.fear.value; </body>
if (!document.affirm.mockMode.checked) { </html>
alert("No " + fear + " to be seen around here!");
}
else {
var mock = "Being afraid of " + fear + " is stupid!";
window.status = mock
document.affirm.mock.value = mock;
}
}
</script>
</head>
Fear Example Quotes Example
Text Box
<form name=form1
onsubmit="setQuotes('form1'); return false;">
Search: <input type=text name=target >
<input type=submit value=Submit>
</form>
Text Box
<input type=text name=target
onKeyUp="setQuotes('form2');">
// Search for an element with the given id and set its innerHTML to
// the given text.
function setText(id, text) {
<script language="JavaScript"> var node = document.getElementById(id);
if (node != null) {
// We allocate a global array and fill it with the quote data. node.innerHTML = text;
lines = new Array(); //node.childNodes[0].data = text;
// alternative for some simple tags
lines.push("Everybody's always telling me one thing and out the }
other."); }
lines.push("Even a fish could stay out of trouble if it would // Given the name of a form, access the target field within that
just learn to keep its mouth shut."); // form and using its target text, generate the quote list and put
lines.push("Beware the lollipop of mediocrity -- lick it once // it into the result tag.
and you suck forever."); function setQuotes(form_name) {
lines.push("We don't have time to stop for gas -- we're already // cute: use [] instead of . to access the form by name
late."); var target = document[form_name].target.value;
lines.push("By doing just a little each day, I can gradually let var contents = "";
the task overwhelm me."); target = target.toLowerCase();
lines.push("Being powerful is like being a lady. If you have to for (var i in lines) {
tell people you are, you aren't."); if (lines[i].toLowerCase().indexOf(target)!=-1) {
lines.push("Never attribute to malice that which can contents = contents + "<li>" + lines[i] + "n";
satisfactorily be explained by incompetence."); }
}
setText("result", contents);
}
</script>
11. JavaScript Summary
Good For Simple Things
Save RT Latency
Bad when Abused
Popups!!!
Don't Always Rely on It
DOMs not standardized