Presentation is loading. Please wait.

Presentation is loading. Please wait.

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,

Similar presentations


Presentation on theme: "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,"— Presentation transcript:

1 Li Tak Sing COMPS311F

2 Applets An 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.

3 Applets An 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.

4 Applets Java 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.

5 Applets The 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.

6 Technical information Java 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.

7 JApplet Java provides two classes for applets: Applet and JApplet. JApplet. JApplet provides better look and control than Applet.

8 Methods of JApplet We 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.

9 init() of JApplet Where 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.

10 init() of JApplet If 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.

11 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.

12 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.

13 A simple applet import 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); }

14 The html file for the applet In 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:

15 The simple applet You can try the applet at: http://plbpc001.ouhk.edu.hk/~mt311f/examples/mt311201 0/build/classes/myjapplet.html

16 Things to note The 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".

17 Other attributes of the 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.

18 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">

19 Archive This 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.

20 An example html file with the archive option. <applet code="applet/MyJApplet.class" archive="dir/code.jar" width="350" height="350"> 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.

21 Width and Hight of an applet This is done by specifying the width and height attributes of the tag. The size is measured in terms of pixels.

22 Param We can specify some parameters to be passed to an applet. Then these parameters can be accessed through the getParameter() method of JApplet.

23 An applet that draws a circle according to a parameter public 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); }

24 Network communication of JApplet As 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.

25 getCodeBase() method of JAplet public 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.

26 Java Web start Java 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.

27 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.

28 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.

29 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.

30 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.

31 To create a Java Web Start application in netbeans Create a normal Java project Select the properties of the project Click at Web Start in the Categories window. Select "Enable Web Start" In Codebase, select "Web Application Deployment" Select Self-signed.

32 To create a Java Web Start application in netbeans A 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.

33 To create a Java Web Start application in netbeans Then, create a normal Java application. Lets assume that we have create a Java class called WebStart.java Then, 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.

34 A simple Web Start Application You can try the program at: http://plbpc001.ouhk.edu.hk/~mt311f/examples/webstar t/dist/launch.html

35 A simple Web Start Application public 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); }

36 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(); }

37 Deployment of the Web Start Application After 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.

38 Deployment of the Web Start Application abc tsli abc

39 Deployment of the Web Start Application

40 XML Markup 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.

41 XML HTML 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. Sample HTML I am the first paragraph. I have two sentences. I am the second paragraph. I am longer than the first paragraph. I have three sentences.

42 HTML In the sample, we have the begin tags for level 3 heading, paragraph, bold font and italics font. There are corresponding end tags with an extra slash / like,, and. 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.

43 XML basics So 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.

44 XML basics An 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.

45 XML basics John 40 30 Mary Lou 30 35

46 Processing instructions The first line is a processing instruction enclosed with. 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.

47 Elements An element is enclosed in a pair of begin and end tags. For instance, in the previous XML document, we have a begin tag and an end tag. 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.

48 Elements This document has elements named employee-list, employee, name, hours and rate. Element names are case sensitive in XML. Therefore is not the proper end tag for the begin tag 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. Mary Lou Spaces are not permitted inside an element name. Therefore the following is not allowed. 30 After replacing spaces with hyphens or underscores, the following is allowed. 30

49 Empty elements You 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.

50 Whitespaces The 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. Oliver Au

51 Whitespaces On the other hand, whitespaces outside of a pair of begin and end tags are insignificant. 30 35 The above and the following are the same in XML. 30 35 In HTML however, two or more consecutive whitespaces are always treated the same as one whitespace.

52 Entity references Can you spot a problem with the following element? 3

53 Entity references The content of the element is a Boolean expression that makes use of the less than operator 3 U+003C 5

54 Entity references Characherunicode in XMLDTD name &U+0026& <U+003C< >U+003E> "U+0022" 'U+0027&apos;

55 XML attributes An element can have any number of attributes. The following is an element that captures the year of publication of an attribute. Wiley 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.

56 XML parsers The 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.

57 XML namespaces XML 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. Apples Oranges

58 We have another XML document holding the information of a piece of furniture. Oak Dining Table 100 220

59 XML namespaces If 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.

60 XML namespaces Apples Oranges Oak Dining Table 100 220

61 XML namespaces Prefixes 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.

62 Apples Oranges Oak Dining Table 100 220

63 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.

64 Default namespace Apples Oranges Oak Dining Table 100 220

65 An XML document of library books This 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.

66 An XML document of library books Complete idiot's guide to XML David Gulbransen Que Java developer's guide to e-commerce with XML and JSP William B. Brogden Chris

67 An XML document of library books Minnick Sybex XPath essentials Andrew Watt Wiley

68 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.

69 A comparison between HTML and XML XMLHTML Emphasizes data contentsEmphasizes data display Allows customized tagsOnly allow pre-defined tags Tages are case-sensitiveTages 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

70 Metalanguages A 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).

71 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.

72 Referring to a DTD file Following is anemployee-list with a 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.

73 Referring to a DTD file John 40 30 Mary 30 35

74 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.

75 Defining elements in DTD The following is the content of the employee.dtd file with five declarations. An 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.

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

77 Repetitions in DTD The following are the characters you can place after an element in an expression to denote repetitions. SymbolMeaning *Zero or more times +One or more times ?Zero or one time

78 Choices in DTD An 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.

79 Attributes in DTD The following is the PUBLISHED element you saw earlier with two attributes. Que We can use an 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.

80 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. OptionMeaning #REQUIREDAttribute values must specified in the XML element #IMPLIEDAttribute 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

81 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.

82 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.


Download ppt "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,"

Similar presentations


Ads by Google