82
Li Tak Sing COMPS311F

Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Embed Size (px)

Citation preview

Page 1: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Li Tak Sing

COMPS311F

Page 2: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

AppletsAn applet is any small application that

performs one specific task, sometimes running in the context of a larger program, perhaps as a plug-in.

A Java applet is an applet delivered to the users in the form of Java bytecode.

Applets are used to provide interactive features to web applications that cannot be provided by HTML alone.

They can capture mouse input and also have controls like buttons or check boxes.

Page 3: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

AppletsAn applet can also be a text area only,

providing, for instance, a cross platform command-line interface to some remote system.

However, applets have very little control over web page content outside the applet dedicated area, of they are less useful for improving the site appearance in general.

Applets can also play media in formats that are not natively supported by the browser.

Page 4: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

AppletsJava applets run at a speed that is comparable

to (but generally slower than) other compiled languages such as C++, but many times faster than JavaScript.

Java applets can use 3D hardware acceleration that is available from Java. This makes applets well suited for non trivial computation intensive visualizations.

HTML pages may embed parameters that are passed to the applet. Hence the same applet may appear differently depending on the parameters that were passed.

Page 5: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

AppletsThe same applet may appear differently

depending on the parameters that were passed.

Since Java's bytecode is platform independent, Java applets can be executed by broswers for many platforms, including Microsoft Windows, Unix, Mac OC and Linux.

Page 6: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Technical informationJava applets are executed ina sandbox by most

web browsers, preventing them from accessing local data like clipboard or file system.

The code of the applet is downloaded from a web server and the browser either embeds the applet into a web page or opens a new window showing the applet's user interface.

The domain from where the applet executable has been downloaded is the only domain to which the usual (unsigned) applet is allowed to communicate. The domain can be different from the domain where the surrounding HTML document is hosted.

Page 7: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

JAppletJava provides two classes for applets:

Applet and JApplet. JApplet .JApplet provides better look and control

than Applet.

Page 8: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Methods of JAppletWe do not use the JApple constructor to

create a JApplet. It is usually created by the Web browser.

When a web page requests for an applet, it will first download the code from the server, then the default constructor of the applet will be called to create an instance of the applet.

Therefore, it does not make sense to have an applet with non-default constructor.

After the applet has been created, its init() method will be called.

Page 9: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

init() of JAppletWhere should we put the initialization code

of an applet? The default constructor or init()?

You can do it both ways. However, when the constructor is called, the object may not have been created properly. For example, calling a method of the applet is limited to the current version of the method. If the applet is overridden further, then the version of the method will still be the one that is declared as the constructor.

Page 10: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

init() of JAppletIf in the constructor of A, it has invoked the

meth() method, the version to be invoked is that of A, not of B. It is because at that time, it is still an A, not a B.

On the other hand, if meth() is invoked in the init() method of A and init() has not been overriddent in B, then the version of meth() invoked would be that of B.

Actually, it is always advisable to avoid invoking a member function in a constructor of a class unless it is private or final.

Page 11: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

init()Therefore, it is better to put initialization

code in init() instead of the default constructor.

So there is usually no need to define the default constructor of JApplet.

Page 12: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

main()In all Java application, you need to have the

main() method to act as the main program. In JApplet, you do not need to define the main method. The brower will know how to instantiate the applet and execute the appropriate methods of the JApplet when it is executed in a browser.

Page 13: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

A simple appletimport javax.swing.*;import java.awt.*;

public class MyJApplet extends JApplet { public void init() { JPanel p = new JPanel() { public void paint(Graphics g) { super.paint(g); g.drawString("Hello World!", 10, 30); } }; this.getContentPane().add(p); }}

Page 14: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

The html file for the appletIn order to execute the applet in a browser,

we need an HTML file to tell the browser which applet we want to run.

The basic format is like this:<applet code="applet/MyJApplet.class" width="350" height="350"></applet>

Page 15: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

The simple appletYou can try the applet at:

http://plbpc001.ouhk.edu.hk/~mt311f/examples/mt3112010/build/classes/myjapplet.html

Page 16: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Things to noteThe MyJApplet is in the package applet.

Therefore, MyJApplet.class should be placed in a directory called applet. The HTML file for the applet should be placed in the root directory of applet.

The MyJApplet.class file should be refered to as "applet/MyJApplet.class" in the HTML file.

So, if you have an applet with the full path name, abc.def.GHI, then GHI.class should be placed in a directory abc/def/ and the html file should be placed in the parent directory of abc. The class should be referred as "abc/def/GHI.class".

Page 17: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Other attributes of the <applet> tag.codebase

This OPTIONAL attribute specifies the base URL of the applet--the directory that contains the applet's code. If this attribute is not specified, then the document's URL is used. With this option, the .class file and the .html file can be anywhere in the system or even in different computers.

For example, assume that abc.def.GHI.class is available at http://ahost.com/xxx/abc/def/GHI.class, then, we can specify the code base as http://ahost.com/xxx.

Page 18: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

The html file with codebase

<applet code="applet/MyJApplet.class" codebase="http://plbpc001.ouhk.edu.hk/

~mt311f/examples/mt3112010/build/classes"

width="350" height="350"></applet>

Page 19: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

ArchiveThis OPTIONAL attribute describes one or

more achives containing classes and other resources that will be "preloaded". The archives are sparated by ",". For security reasons, the applet's class loader can read only from the same codebase from which the applet was started. This means that archives must be in the same directory as, or in a subdirectory of, the codebase.

Entries like ../a/b.jar will not work unless explicitly allowed for in the security policy file.

Page 20: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

An example html file with the archive option.<applet code="applet/MyJApplet.class" archive="dir/code.jar"width="350" height="350"></applet>

Here, we assume that in the directory that contains the html file, there is a subdirectory called dir and in that subdirectory, there is a file called code.jar.

code.jar should then contain the .class file for applet.MyJApplet .

Page 21: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Width and Hight of an appletThis is done by specifying the width and

height attributes of the <applet> tag.The size is measured in terms of pixels.

Page 22: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

ParamWe can specify some parameters to be

passed to an applet. Then these parameters can be accessed through the getParameter() method of JApplet.

Page 23: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

An applet that draws a circle according to a parameterpublic class Circle extends JApplet { public void init() { final int x=Integer.parseInt(this.getParameter("x")); final int y=Integer.parseInt(this.getParameter("y")); final int r=Integer.parseInt(this.getParameter("r")); JPanel p=new JPanel() { public void paint(Graphics g) { super.paint(g); g.drawOval(x-r, y-r, 2*r, 2*r); } }; this.getContentPane().add(p); }}

Page 24: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Network communication of JAppletAs stated eariler, an applet is only allowed to

communicate with the host from which the applet was loaded.

We can use the getCodeBase() method of JApplet to get the code base.

Note that there is another method called getDocumentBase(). This method returns the location where the HTML file in which the applet is embeded.

The code base and document base can be different. An applet is only allowed to communicate with the computer at the codebase, not the document base.

Page 25: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

getCodeBase() method of JApletpublic URL getCodeBase()

This method return the URL from where the applet is loaded.

URL has the getHost() method that allow us to get the host of the URL.

Page 26: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Java Web startJava Web Start is a framework that allows users

to start application software for the Java Platform directly from the Internet using a web browser.

Unlike Java applets, Web Start applications do not run inside the browser, and the sandbox in which they run need not have as many restrictions, although this can be configured. Web Start has an advantage over applets in that it overcomes many compatibility problems with browsers' Java plugins and different JVM versions. On the other hand, Web Start programs cannot communicate with the browser as easily as applets.

Page 27: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Java Network Launching Protocol(JNLP)JNLP consists of a set of rules defining how

exactly to implement the launching mechanism. JNLP files include information such as the location of the jar package file and the name of the main class for the application, in addition to any other parameters for the program. A properly configured browser passes JNLP files to a Java Runtime Envvironment (JRE) which in turn downloads the application onto the user's machine and starts executing it.

Page 28: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Java Network Launching Protocol(JNLP)Important Web Start features include the

ability to automatically download and install a JRE in the case where the user dose not have Java installed, and for programmers to specify which JRE version a given program needs in order to execute.

Any computer user can use JNLP by simply installing a JNLP client (most commonly Java Web Start). The installation can occur automatically such that the end user sees the client launcher downloading and installing the Java application when first executed.

Page 29: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Java Network Launching Protocol(JNLP)JNLP works in a similar fashion to how HTTP/HTML

works for the web. For rendering a HTML webpage, after the user clicks on a weblink, the browser submits a URL to a webserver, which replies with an HTML file. The browser then requests the resources referred to by this file (images, css), and finally renders the page once it has received enough information. Page rendering usually starts before all resources have downloaded; some resources not critical to the layout of the page (such as images), can follow on afterwards — or on request if the "Load Images Automatically" browser-setting remains unset.

Page 30: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Java Network Launching Protocol(JNLP)JNLP mirrors this process; in the same way that a

Web browser renders a webpage, a JNLP client "renders" a Java app. After the user clicks on a weblink the browser submits a URL to a webserver, which replies with a JNLP file (instead of a HTML file) for the application. The JNLP client parses this file, requests the resources specified (jar files), waits for the retrieval of all required resources, and then launches the application. The JNLP file can list resources as "lazy", which informs the JNLP client that the application does not need those resources to start, but can retrieve them later on when/if the application requests them.

Page 31: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

To create a Java Web Start application in netbeansCreate a normal Java projectSelect the properties of the projectClick at Web Start in the Categories

window.Select "Enable Web Start"In Codebase, select "Web Application

Deployment"Select Self-signed.

Page 32: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

To create a Java Web Start application in netbeansA self-signed application is one that has a

self-signed certificate. Without a certificate, the Web Start application would have limited rights like an applet. With a certificate, a Web Start application would have rights like a local application.

Page 33: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

To create a Java Web Start application in netbeansThen, create a normal Java application.Lets assume that we have create a Java

class called WebStart.javaThen, netbeans will create the following

files for you in the dist directory:launch.html. This file is the html that that

has the Web Start application.launch.jnlp. This file is the configuration file

for the Web Start application.webstart.jar. This is the jar file that contains

the required resoruces like java code.

Page 34: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

A simple Web Start ApplicationYou can try the program at:

http://plbpc001.ouhk.edu.hk/~mt311f/examples/webstart/dist/launch.html

Page 35: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

A simple Web Start Applicationpublic class WebStart extends JFrame implements

ActionListener { JPanel p=new JPanel(); JTextField text=new JTextField(5); JButton button=new JButton("counter"); int count=0; public WebStart() { this.getContentPane().add(p); p.add(text); p.add(button); text.setEditable(false); pack(); setVisible(true); button.addActionListener(this); }

Page 36: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

A simple Web Start Application public void actionPerformed(ActionEvent e)

{ text.setText(Integer.toString(count++)); }

public static void main(String st[]) { WebStart s=new WebStart(); }}

Page 37: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Deployment of the Web Start ApplicationAfter the application has been tested

locally, you need to deploy the application to a Web server. What you do is to copy all the files in the dist folder of the project to somewhere in the Web server. Then, you need to edit the .jnlp file.

You need to change the codebase to point to the web server.

Page 38: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Deployment of the Web Start Application<?xml version="1.0" encoding="UTF-8"

standalone="no"?><jnlp

codebase="http://plbpc001.ouhk.edu.hk/~tsli/abc/" href="launch.jnlp" spec="1.0+">

<information> <title>abc</title> <vendor>tsli</vendor> <homepage href=""/> <description>abc</description> <description kind="short">abc</description>

Page 39: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Deployment of the Web Start Application </information><update check="always"/><security><all-permissions/></security> <resources><j2se version="1.5+"/><jar href="abc.jar" main="true"/>

Page 40: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

XMLMarkup languages

Many people might not realize that there were markup languages even before computers were invented. What we refer to as a markup language consists of symbols used to annotate texts in documents. For example, in the early days of printing, authors prepared manuscripts of their books on papers. Proofreaders and editors marked on the manuscripts with a markup language that the people working in print shops understood. The symbols in this type of markup language would not actually appear in the resulting books, but they gave instructions on how to present the texts.

Page 41: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

XMLHTML is a modern markup language that

deals with how data should be displayed on a Web browser. HTML does this by enclosing texts in begin and end tags. This is a sample HTML document. <h3>Sample HTML</h3> <p>I am the <b>first</b> paragraph. I have two sentences.</p> <p>I am the <i>second</i> paragraph. I am longer than the first paragraph. I have three sentences.</p>

Page 42: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

HTMLIn the sample, we have the begin tags for

level 3 heading <h3>, paragraph <p>, bold font <b> and italics font <i>. There are corresponding end tags with an extra slash / like </h3>, </p>, </b> and </i>. Note that the tags may be nested. For example, the pair of bold tags can be placed inside paragraph tags. The sample HTML document displays on Mozilla Firefox as follows.

Page 43: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

XML basicsSo what exactly is XML? XML stands for

Extensible Markup Language. It has been defined by the World Wide Web Consortium (W3C) with design goals including, but not limited to, the following:

• Compatible with the Internet • Useful for a wide range of applications • Easy to create and process • Readable by humans.

Page 44: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

XML basicsAn XML document is very useful. It can hold

the data for a purchase order, an invoice, an employment application, a price list, a collection of music CDs or many other kinds of data. Below is a sample XML document, but keep in mind that XML documents found in the real world may be larger than the samples you see in this unit.

Page 45: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

XML basics<?xml version="1.0" encoding="ISO-8859-1"?> <employee-list> <employee> <name>John</name> <hours>40</hours> <rate>30</rate> </employee> <employee> <name>Mary Lou</name> <hours>30</hours> <rate>35</rate> </employee> </employee-list>

Page 46: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Processing instructionsThe first line is a processing instruction enclosed

with <? and ?>. It captures the XML version number and the character set used. If you are using an XML tool to assist your creation of XML documents, the tool will generate their values for you according to the tool’s current configuration.

Other processing instructions are allowed. In general, processing instructions provide information to applications to help them process XML documents. For example, stylesheet information may be provided to help applications correctly interpret the XML documents.

Page 47: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

ElementsAn element is enclosed in a pair of begin and

end tags. For instance, in the previous XML document, we have a begin tag <employee-list> and an end tag </employee-list>. The end tag looks just like the begin tag except for the extra slash. The employee-list element is the root element of this XML document. It has a child element employee which in turn has child elements name, hours and rate. The data can be used to calculate the weekly payroll. We see that elements in XML documents can nest and repeat.

Page 48: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

ElementsThis document has elements named employee-list,

employee, name, hours and rate. Element names are case sensitive in XML. Therefore </Rate> is not the proper end tag for the begin tag <rate> due to the unmatched case in the first character of the tag name.

The first character of an element name can be any letter from the alphabet or an underscore. The remaining characters can be alphanumeric, hyphens, underscores and even periods. Spaces are allowed in the content of an element as in the following element. <name>Mary Lou</name>

Spaces are not permitted inside an element name. Therefore the following is not allowed. <number of hours>30</number of hours>

After replacing spaces with hyphens or underscores, the following is allowed. <number_of_hours>30</number_of_hours>

Page 49: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Empty elementsYou can use an empty element to

represent that the item is unknown or not applicable. An empty element for a commission element can be represented in one of three ways. <commission></commission> <commission/> <commission />

Page 50: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

WhitespacesThe characters for spaces, line feeds, tabs

and carriage returns are collectively called whitespaces. In XML adjacent whitespaces inside a pair of begin and end tags are significant. The following three elements are different unless programmers make the decision to treat them the same. <name>Oliver Au</name> <name>Oliver Au</name> <name>Oliver

Au</name>

Page 51: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

WhitespacesOn the other hand, whitespaces outside of a

pair of begin and end tags are insignificant. <hours>30</hours>

<rate>35</rate>The above and the following are the same in

XML. <hours>30</hours> <rate>35</rate>

In HTML however, two or more consecutive whitespaces are always treated the same as one whitespace.

Page 52: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Entity referencesCan you spot a problem with the following

element? <condition> 3 < 5 </condition>

Page 53: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Entity referencesThe content of the element is a Boolean

expression that makes use of the less than operator < which is also the first character of a tag. XML processing applications are built to be precise. Using the same symbol < as the less than operator and the beginning character of a tag is a source of confusion. To avoid problems, we replace the character with its entity reference in the Boolean expression.

<condition> 3 U+003C 5 </condition>

Page 54: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Entity referencesCharacher unicode in XML DTD name

& U+0026 &amp;

< U+003C &lt;

> U+003E &gt;

" U+0022 &quot;

' U+0027 &apos;

Page 55: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

XML attributesAn element can have any number of

attributes. The following is an element that captures the year of publication of an attribute.

<PUBLISHED year="2002">Wiley</PUBLISHED>

This is another difference between HTML and XML. The double quotes around an attribute value, as in "2002", are optional in HTML but are compulsory in XML.

Page 56: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

XML parsersThe meaning of a sentence is not determined only

by the words used. We often have to determine the sentence structure before we can correctly understand the sentence. In computer science and linguistics, parsing is the process of recognizing the structure of a program, an HTML document, an XML document or an English sentence.

A program that performs this task is called a parser. All the popular Web browsers have a built-in XML parser. Even the programs that you write to process XML documents for a course assignment are also XML parsers. Fortunately, you don’t have to build the parsing capability from scratch as it comes with Java’s class library.

Page 57: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

XML namespacesXML elements have names. When an

application processes two or more kinds of XML documents, there may be element name conflicts. Suppose we have an XML document holding the information of some fruit. <table> <row> <column>Apples</column> <column>Oranges</column> </row> </table>

Page 58: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

We have another XML document holding the information of a piece of furniture. <table> <name>Oak Dining Table</name> <width>100</width> <length>220</length> </table>

Page 59: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

XML namespacesIf we were to merge the two XML documents as

one, XMP parsers trying to process the merged document will be confused. The element name table is used for different purposes under distinct structures. We can use qualified names to prevent confusion. In the following merged XML document, h and furn are local names. We qualify the local names with an optional prefix xmlns which stands for XML name space. Other prefixes are also allowed. The qualified name say xmlns:h is defined as a uniform resource identifier (URI) which is a character string identifying an Internet resource. An XML parser would not actually access the URI which just uniquely identifies a qualified name.

Page 60: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

XML namespaces<h:table

xmlns:h="http://www.mycompany.com/fruits"> <h:row> <h:column>Apples</h:column> <h:column>Oranges</h:column> </h:row> </h:table> <furn:table xmlns:furn="http://www.mycompany.com/furniture"> <furn:name>Oak Dining Table</furn:name> <furn:width>100</furn:width> <furn:length>220</furn:length> </furn:table>

Page 61: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

XML namespacesPrefixes and namespaces can be defined

for elements at any level. Once defined, the prefixes can be used in the child elements. You can also define two prefixes in one element as shown in the root element below.

Page 62: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

<?xml version="1.0" encoding="utf-8"?> <root xmlns:h=”http://www.mycompany.com/fruits” xmlns:furn="http://www.mycompany.com/furniture"> <h:table> <h:row> <h:column>Apples</h:column> <h:column>Oranges</h:column> </h:row> </h:table> <furn:table>

<furn:name>Oak Dining Table</furn:name> <furn:width>100</furn:width> <furn:length>220</furn:length> </furn:table> </root>

Page 63: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Default namespace Having to repeat the prefix on each tag is a

tedious chore. An alternative is to define a default namespace as follows without the local names of h or furn. Prefixes are not required for the distinction.

Page 64: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Default namespace <?xml version="1.0" encoding="utf-8"?>

<root> <table xmlns="http://www.mycompany.com/fruits"> <row> <column>Apples</column> <column>Oranges</column> </row> </table> <table xmlns="http://www.mycompany.com/furniture"> <name>Oak Dining Table</name> <width>100</width> <length>220</length> </table> </root>

Page 65: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

An XML document of library booksThis XML document uses a popular and

space efficient character set utf-8 which employs 1 byte to represent commonly used characters and more bytes for others like Chinese characters. It has the advantage of being backward compatible with the original ASCII character set. The document demonstrates the use of attributes and comments.

Page 66: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

An XML document of library books <LIBRARY>

<BOOK> <TITLE>Complete idiot's guide to XML</TITLE> <AUTHOR> <FIRST-NAME>David</FIRST-NAME> <LAST-NAME>Gulbransen</LAST-NAME> </AUTHOR> <PUBLISHED place="Indianapolis" year="2000">Que</PUBLISHED> </BOOK> <!-- Note that the following book has two authors --> <BOOK> <TITLE>Java developer's guide to e-commerce with XML and JSP</TITLE> <AUTHOR> <FIRST-NAME>William B.</FIRST-NAME> <LAST-NAME>Brogden</LAST-NAME> </AUTHOR> <AUTHOR> <FIRST-NAME>Chris</FIRST-NAME>

Page 67: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

An XML document of library books <LAST-NAME>Minnick</LAST-NAME> </AUTHOR>

<PUBLISHED place="" year="2001">Sybex</PUBLISHED> </BOOK> <BOOK> <TITLE>XPath essentials</TITLE> <AUTHOR> <FIRST-NAME>Andrew</FIRST-NAME> <LAST-NAME>Watt</LAST-NAME> </AUTHOR> <PUBLISHED place="New York" year="2002">Wiley</PUBLISHED> </BOOK> </LIBRARY>

Page 68: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

XML versus HTML Due to their similar appearance and shared

lineage, people often like to compare XML with HTML. It is true that both are captured in plain texts that can be edited with an ordinary editor and that their elements are enclosed in begin and end tags. But they also have important differences. The following table summarizes the differences between the two.

Page 69: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

A comparison between HTML and XMLXML HTML

Emphasizes data contents Emphasizes data display

Allows customized tags Only allow pre-defined tags

Tages are case-sensitive Tages are not case-sensitive

Multiple adjacent whitespaces in an element content are different from a single whitespace

Multiple adjacent whitespaces in an element content are the same as a single whitespace

Double quotes around attribute values are compulsory

Double quotes around attribute values are optional

Processed by tailor-made programs as well as generic XML parsers

Processed mainly by standard Web browsers

Page 70: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

MetalanguagesA metalanguage is a language used to describe

another language. Though XML is precise, it is also generic enough to allow many different documents to be syntactically correct. These documents are said to be well formed. For different applications, XML documents hold different kinds of data in different document structures. If one computer program produces XML documents for another program to process, the two programs must agree on the same document structure. A metalanguage

builds on top of XML syntax to further describe the structure of the documents for the two programs to share. Starting in the next section, we will study two representative metalanguages Document Type Definition

(DTD) and XML Schema Definition (XSD).

Page 71: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Document Type Definition (DTD) Many metalanguages have been used to

specify XML document structures. DTD was the first such language proposed and it is still taught and used today. However, the popularity of DTD has been overtaken by a more powerful alternative called XML Schema. Our coverage on DTD will therefore be relatively brief.

Page 72: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Referring to a DTD file Following is anemployee-list with a <!

DOCTYPE> declaration added. The first word after the DOCTYPE keyword must be the name of the root element which in our case is employee-list. In this declaration, we specify "employee-list.dtd" as the file to hold the allowed syntax for the employee-list element. We use the SYSTEM keyword to indicate that the DTD file is defined by ourselves. An alternative PUBLIC keyword may be used but it is not applicable to us in this course.

Page 73: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Referring to a DTD file <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE employee-list SYSTEM

"employee-list.dtd"> <employee-list> <employee> <name>John</name>

<hours>40</hours> <rate>30</rate> </employee> <employee> <name>Mary</name>

<hours>30</hours> <rate>35</rate> </employee> </employee-list>

Page 74: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Referring to a DTD file Without any path information, the DTD file is

assumed to be in the same directory as the XML file. We could use one of the following declarations which specify a DTD file with a relative path, an absolute path and a URL respectively. The double-dot .. in the relative path stands for the parent directory.

<!DOCTYPE employee-list SYSTEM "../employee-list.dtd"> <!DOCTYPE employee-list SYSTEM "c:/MT311 Development/employee-list.dtd"> <!DOCTYPE employee-list SYSTEM "http://www.mysite.com/files/employee-list.dtd">

Page 75: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Defining elements in DTD The following is the content of the

employee.dtd file with five declarations. An <!ELEMENT> declaration has two pieces of information. The first one is the name of the element being defined. The second one is an expression that defines the element. <?xml version="1.0" encoding="utf-8"?> <!ELEMENT employee-list (employee*)> <!ELEMENT employee (name, hours, rate)> <!ELEMENT name (#PCDATA)> <!ELEMENT hours (#PCDATA)> <!ELEMENT rate (#PCDATA)>

Page 76: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Defining elements in DTD The first <!ELEMENT> declaration in

employee.dtd defines an employee-list as zero or more employee elements using a trailing asterisk. (employee*) The second <!ELEMENT> declaration defines employee as a sequence of name, hours and rate with commas. (name, hours, rate) The remaining <!ELEMENT> declarations define individual elements name, hours and rate as parsed character data denoted by #PCDATA.

Page 77: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Repetitions in DTD The following are the characters you can

place after an element in an expression to denote repetitions.

Symbol Meaning

* Zero or more times

+ One or more times

? Zero or one time

Page 78: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Choices in DTDAn element can be defined as one of

several things. For example, a vehicle element may be defined as a motorcycle, car, van or truck. We use vertical strokes to separate choices. <!ELEMENT vehicle (motorcycle | car | van | truck)>

Page 79: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Attributes in DTDThe following is the PUBLISHED element you

saw earlier with two attributes.

<PUBLISHED place="Indianapolis" year="2000">Que</PUBLISHED> We can use an <!ATTLIST> declaration to define the list of attributes allowed in an element. If we want to allow two attributes place and year in the PUBLISHED element, we use the following declaration. <!ATTLIST PUBLISHED place CDATA #REQUIRED year CDATA "2000">

Page 80: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Both attributes hold CDATA which stands for character data. The place attribute is required in the PUBLISHED element thus we use #REQUIRED. The year attribute has a default value of "2000" if not specified. Here are some additional options for attributes that could be used.

Option Meaning

#REQUIRED Attribute values must specified in the XML element

#IMPLIED Attribute values are optional in the XML element

"default value" Attributes will have the default value if ommitted.

#FIXED "fixed value" Attributes have the fixed values

Page 81: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Drawbacks of DTD DTD itself does not follow XML syntax, which

means that people using DTD have to learn a separate set of rules in addition to the XML rules. In addition, DTD has a rather limited set of data types. We cannot allow data more details than #PCDATA. For example, even integer data can only be defined as #PCDATA. The ways to construct complex elements are limited to simple sequence, repetitions and choices. For example, we will have an awkward definition to specify the course workload of a full-time student as three to six courses.

Page 82: Li Tak Sing COMPS311F. Applets An applet is any small application that performs one specific task, sometimes running in the context of a larger program,

Drawbacks of DTD Finally, DTD does not support reuse. If two

elements have a similar structure, their structures must be repeated at the top-level as follows. <!ELEMENT Student (Name, Id, Address, Phone, Courses+)> <!ELEMENT Tutor (Name, Id, Address, Phone, Courses+)>