b578646b6736781a5500b8cf3b2f17f4.ppt
- Количество слайдов: 176
Internet and Java Revolutions Impact on Education (c) Rajkumar School of Computing Queensland University of Technology Brisbane, Australia Email: rajkumar@fit. qut. edu. au URL: http: //www. fit. qut. edu. au/~rajkumar 1
Motivation (c) Rajkumar c Potential delivery sites are widely distributed c Information is rapidly changing c Connections to the Internet have become ubiquitous c Different learners have different needs 2
Agenda (c) Rajkumar c Internet and its Evolution c Internet Tools c Web and its Programming c Internet as a delivery Vehicle c Java for Internet Programming c Java Nuts and Bolts c Java Platform c Developing Applets and Applications c Challenges and Future Directions 3
What is the Internet ? (c) Rajkumar • It is a global network of computers that communicate with each other using a variety of protocols and overcoming various communication barriers. • It is like International Telephone System 4
Internet Technology Evolution (c) Rajkumar c Internet is much bigger than what we think c More than 25 years old c More than doubling every year c Technology effect c suddenly every body sees the need for a technology c like the radio or the TV c 10 terabytes flows everyday 5
Installed base and Growth rate for telephone lines, mobile phones, and Internet hots (c) Rajkumar Income Group/ Region Installed, 1995 Phone Mobile Internet Lines Phones Hosts 1994 -95 Growth Rates (%) Phone Mobile Internet Lines Phones Hosts Lower Income 2. 0 0. 12 1. 35 35. 7 135. 1 246. 0 Lower- Middle 9. 1 0. 33 73. 31 8. 7 105. 1 167. 0 Upper - Middle 14. 5 1. 34 380. 13 6. 4 66. 8 111. 9 High 53. 2 8. 70 10749. 23 3. 6 55. 6 97. 0 Africa 1. 7 0. 09 69. 14 7. 9 60. 5 81. 4 Americas 29. 0 5. 17 8359. 58 5. 4 42. 3 91. 5 Asia 5. 4 0. 62 121. 70 14. 7 108. 3 150. 0 Europe 33. 04 2732. 24 3. 6 59. 5 112. 2 Oceans 39. 7 9. 55 12845. 55 4. 0 85. 7 88. 8 World 12. 1 1. 56 1661. 89 7. 0 60. 4 97. 8 Source: ACM, Nov, 97 (phones, international telecommunication union, hosts, network Wizards 6
Internet (c) Rajkumar c Use of internet advertisement/elections/newspapers c information is public c Ubiquitous technology c Network is the computer c Intranets - internal TCP/IP nets c PC accounts for 55% of total IT c Applications tied to platform - API lock -in 7
Internet Evolution (c) Rajkumar File & mail TCP/IP Webpages Netscape 10% of Market On line connects to internet Secure payments Multi media Authoring Java VRML HTML 20% of Market Internet everywhere Internet appliances Price based services Live communities ? ? ? ? Total Market 8
Early Internet (c) Rajkumar • • Early Internet supported only email. File Transfer Protocol development - ftp sites. Network News was added to the Internet. Archie - A program to canvass anonymous ftp sites and create a database of what is available • Gopher- A menu-driven interface used to search for information. • Archie and Gopher could answer questions only like ‘what FTP server contains info about “xxxx” ‘ 9
World Wide Web (c) Rajkumar • World Wide Web conceptualized by Tim Berners-Lee at CERN in Switzerland • Concept of Hypertext led to the development of the Hypertext Markup Language (HTML) • Tim Berners-Lee proposed the ‘Browser’ program • Scientists at CERN designed a TCP/IP based protocol to share Hypertext information called HTTP. • WWW officially is described as a” Wide-area hypermedia information retrieval initiative aiming to give universal access to a large universe of documents. 10
Viewing WWW pages (c) Rajkumar c View text, graphics, pictures, sounds, video c Web Browser c Hyper. Text Markup Language (HTML) c Computer Independent c Operating System Independent 11
Web Browsers (c) Rajkumar c Netscape Navigator c Microsoft Internet Explorer c Omni Web c NCSA Mosaic c Lynx (text only) 12
Internet Organization (c) Rajkumar • Truly world-wide • Multiple communication media types 13
Internet Organization (c) Rajkumar Domains: . edu. org. com. mil. biz Computers: fife. engr. vt. edu www. engr. vt. edu 14
WWW Organization (c) Rajkumar Client Server Client 15
Generating Web Pages (c) Rajkumar c Simple Text Editor c Word Processor or other tool export c e. g. , Internet Assistant for Microsoft Word c HTML Editor c Open file in Netscape Composer c Last step is to put the file(s) on an HTML server 16
HTML (c) Rajkumar c Hypertext -A little Hype and a Little Text. c Hypertext point to information which can be local or remotely located. c HTML -Derivative of the SGML( Standard Generalized Markup Language). c HTML -information , commands for the Browser formatting documents. c HTML -The de-facto language for publishing on the Internet. c Hypermedia- Hyper-links to Multimedia. 17
Internet Tools (c) Rajkumar • Browsers- A tool used to view documents on the WWW • Web servers - Machines which run the HTTP-server Software that respond to HTTP requests which it receives • Authoring Tools - Editors specially made for editing HTML documents • Filters -Tools to convert legacy documents to HTML format • Scripting -Languages used for scripting • WAIS- Wide Area Information Servers (WAIS) for indexing and doing full text searches 18
How does the Web work ? (c) Rajkumar c Web -Designed around Client/Server Architecture c Web Clients ( Web Browsers ) -send requests for documents to any Web Server c Web Server -Program that responds to HTTP requests c Hyperlink c Web client connects to the specified Web Server c The server responds by sending the information asked for c The Browser formats the received HTML data and displays it 19
How does the Web Work (c) Rajkumar Send the “INFORMATION ABOUT C-DAC ACTS” HTTP The client sends an HTTP message to a computer running a Web Server program and asks for a document The information about C-DAC ACTS The web server sends the hypermedia HTML documents to the client. You end up seeing the document on your screen 20
(c) Rajkumar 22
URLs (c) Rajkumar c URLs- The Hypertext links we use today are known as Universal Resource Locator c URLs-Each name is unique across the Internet c An URL looks like this http: //system. domain. ext: 999/dir 1/dir 2/dir 3/file. html? blue# c Parts of a URL are, Service type, System Name, Port, Directory path, Filename, Search Components or Variables c Service type, System Name, Directory path are the required parts of the URL 23
CGI (Common Gateway Interface) (c) Rajkumar c CGI makes the Web a Two-way interface c CGI -lets the user run a script when a web page is accessed c Information from the Web Client is received through simple ‘fill-in-the-forms’ kind of interface c FORMS - Integrates data sheets, menus , check boxes c CGI makes the Web interactive c CGI -complicated to setup , requires PERL knowledge c HTML books talk less about CGI 24
Authoring tools and Filters (c) Rajkumar c Authoring tools- Editors for HTML documents c Editors similar to WYSIWYG word processing programs c Semi-WYSIWYG or completely WYSIWYG c Provide syntax checking and correction c Filters -Convert legacy documents to HTML format c Filters are useful when the documents already exist c Authoring tools- Ho. TMeta. L, HTML Assistant Shareware 25
Preconfigured v/s Integrated Internet Products (c) Rajkumar c Integrated Internet Products- From multiple vendors c Preconfigured Systems- Web Server and a Client ready to use c Sun’s Netra Internet Server c SGI’s Web. FORCE Indy and Web. FORCE Challenge S c Apple’s Internet Server Solution c DEC’s Internet Alpha. Server c Integraph’s Web Server 10 26
Future Directions (c) Rajkumar c Additions to HTML (Grammar, Maths, Display control) c VRML (Virtual Reality Markup Language) c Security - Using Scrambling and Encryption c Common Client Interface (CCI)- Allows Clients to pass information back and forth between the Browser and the External Viewer c Charge Mechanisms c Performance Enhancements- Sending a page and graphics for that page in one connection 27
Internet in Education (c) Rajkumar * Creating Your Own Page * Institution Web Site: HTML Tags (Title, Body, images, etc. ) - about the university Basic HTML code & file structure - faculties and department details Links and Anchors; - research facilities, area, and groups Linking it elsewhere: - faculty members details with their publications Moving around the WWW * Admission Process: Making it all Look ‘Pretty’ - course announcement, - making available details of course * Use components such as: - admission applications, - WWW Forms, Frames, Sound, Video, - announcement of selection - Animation, WWW Plugins * University Facilities: * - computing facilities, accommodation, recreation, etc. . Make web attractive through: Adding web applications: * Teaching Process: - customer enquiry - Use of WWW in the Curriculum - Free applications - Homework and Quizzes - Virtual Classroom - Virtual Lectures - Student Interaction -Q&A 28
Internet as a delivery Vehicle (c) Rajkumar 29
Interesting URLs (c) Rajkumar c http: //www. whitehouse. gov ( The White. House) c http: //www. w 3. org (Everything about the WWW) c http: //sunsite. unc. edu (Software on Sun) c http: //www. indnet. org (India Net Foundation Services) c telnet: //www. arbornet. org (Free Public Access Unix System) c http: //www. infoseek. com (Search engines, Add URL) c http: //www. infophil. com (World Alumni on the net) c http: //www. rocketmail. com (Free Email ) c http: //members. tripod. com (Free Website, 2 MB space) c http: //www. bangaloreonline. com (Offers virtual web servvices for compinies to host their website). c http: //www. prajavani. com (Kannada news paper on web) 30
Class Sites To Visit (c) Rajkumar c http: //truth. phil. vt. edu/wwwcourses. html c http: //fiddle. visc. ece. vt. edu/courses/ee 2504/ c http: //adept. stanford. edu/ c http: //www. aoe. vt. edu/aoe 5104. html c http: //nersp. nerdc. ufl. edu/~cgs 2422/ c http: //www. sloan. org/oakley/misc/IMNews. html c http: //www. eng. fsu. edu/net 98. html 31
API Bottleneck (c) Rajkumar MAC PC LAN Server SUN Network 32
The OS - Platform lock (c) Rajkumar ati on Ap pli c ati Ap pli c Application OS tied to Platform on Applications tied to OS OS Application 33
Ap pli * Seeded by HTML from CERN * Revolutionised by MOSAIC * Standardised, universal interface Ap to data pli ca tio n * Graphical ca tio Application (c) Rajkumar n The Web BROWSER OS Application OS OS OS Application * Broadcast capability publish once, reach millions 34
Making life easier! (c) Rajkumar c Data on the web c Browser platform independent c Click on application - run on any machine c Java the programming language of the 21 century 35
Java and Java Computing (c) Rajkumar 36
Java - An Introduction (c) Rajkumar c Java - The new programming language from Sun Microsystems c Java -Allows anyone to publish a web page with Java code in it c Java - CPU Independent language c Created for consumer electronics c Java - James , Arthur Van , and others c Java -The name that survived a patent search c Oak -The predecessor of Java c Java is “C++ -- ++ “ 37
Java From 10, 000 Ft. (c) Rajkumar c According to the world, Java is. . . c According to Sun, Java is. . . c On closer inspection, Java is 38
According to the World, Java Is. . . (c) Rajkumar c Snazzy Web pages c The cross-platform language we want c The rest-of-the-worlds answer to Bill c The C++ replacement we need c The C++ replacement we dont need c A bunch of hype 39
According to Sun, Java is. . . (c) Rajkumar c Simple and Powerful c Object Oriented c Portable c Architecture Neutral c Distributed c Multi-threaded c Robust, Secure/Safe c Interpreted c High Performance c Dynamic pogramming language/platform. Buzzword compliant! 40
On Closer Inspection, Java is. . . (c) Rajkumar c Simple c Pure c Portable c Surprisingly effective 41
As a whole, Java is a Comprehensive Programming Solution (c) Rajkumar c Object Oriented c Portable c High Performance c Geared for Distributed Environments c Secure 42
Java as Object Oriented (c) Rajkumar c “Objects all the way down” c Simple and Familiar: “C++ Lite” c No Pointers! c Garbage Collector c Dynamic Binding c Single Inheritance with “Interfaces” 43
Java as Portable (c) Rajkumar c Unlike other language compilers, Java complier generates code (byte codes) for Universal Machine. c Java Virtual Machine (JVM): Interprets bytecodes at runtime c Architecture Neutral c No Link Phase c Higher Level Portable Features: AWT, Unicode 44
Total Platform Independence (c) Rajkumar JAVA COMPILER (translator) JAVA BYTE CODE (same for all platforms) JAVA INTERPRETER (one for each different system) Windows 95 Macintosh Solaris Windows NT 45
(c) Rajkumar Java Write Once, Run Anywhere 46
Architecture Neutral & Portable (c) Rajkumar Compiler -Java source code to bytecode c Bytecode - an intermediate form, closer to machine representation c A virtual machine on any target platform interprets the bytecode c Porting the java system to any new platform involves writing an interpreter that supports the Java Virtual Machine c The interpreter will figure out what the equivalent machine dependent code to run c Java 47
Java as High Performance (c) Rajkumar c JVM uses “lean and mean” bytecodes c Small binary class filtes c Just-in-time Compilers c Multithreading c Native Methods 48
Java in the World of Distributed Computing (c) Rajkumar c Class Loader c Lightweight Binary Class Files c Multithreading c Dynamic c Good communication constructs c Secure 49
Java as Secure (c) Rajkumar c Language designed as safe c Strict compiler c Dynamic Runtime Loading (Verifier) c Runtime Security Manager 50
Object Oriented Languages -a Comparison (c) Rajkumar Feature Encapsulation Inheritance Multiple Inherit. Polymorphism Binding (Early/Late) Concurrency Garbage Collection Genericity Class Libraries C++ Yes Yes Both Poor No Yes Objective C Ada Java Yes Yes Both Poor Yes No No Yes Early Difficult No Yes Limited Yes No Yes Late Yes No Yes 51
Java better than C++ ? (c) Rajkumar c No Typedefs, Defines, or Preprocessor c No Global Variables c No Goto statements c No Pointers c No Unsafe Structures c No Multiple Inheritance c No Operator Overloading c No Automatic Coercions c No Fragile Data Types ? 52
Basic Data Types (c) Rajkumar c Types boolean either true of false char 16 bit Unicode 1. 1 byte 8 -bit integer (signed) short 16 -bit integer (signed) int 32 -bit integer (signed) long 64 -bit integer (singed) float 32 -bit floating point (IEEE 754 -1985) double 64 -bit floating point (IEEE 754 -1985) c String (class for manipulating strings) c Java uses Unicode to represent characters internally 53
(c) Rajkumar Java Integrates Power of Compiled Languages and Flexibility of Interpreted Languages 54
Two Types of Java. Applications (c) Rajkumar c Different ways to write/run a Java codes are: Application- A stand-alone program that can be invoked from command line. A program that has a “main” method main Applet- A program embedded in a web page , to be run when the page is browsed. A program that contains no “main” method c Application -Java interpreter c Applets- Java enabled web browser (Linked to HTML via
Java Environment/ Life Cycle of Java Code Runtime Environment (c) Rajkumar Compile-time Environment Bytecode Verifier Java Source (. java) Java Compiler Class Loader Java Bytecodes move locally or through network Java Interpreter Just in Time Compiler Java Class Libraries Java Virtual machine Runtime System Java Bytecode (. class ) Operating System Hardware 56
Java Development Kit (c) Rajkumar c javac - The Java Compiler c java - The Java Interpreter c jdb. The Java Debugger c appletviewer -Tool to run the applets c javap - to print the Java bytecodes c javaprof - Java profiler c javadoc - documentation generator c javah - creates C header files 57
Hello Internet (c) Rajkumar // hello. java: Hello Internet program class Hello. Internet { public static void main(String args[]) { System. out. println(“Hello Internet”); } } 58
Program Processing (c) Rajkumar c Compilation # javac hello. java results in Hello. Internet. class c Execution # java Hello. Internet Hello Internet # 59
Simple Java Applet (c) Rajkumar // Hello. World. java: A sample applet import java. applet. Applet; public class Hello. World extends Applet { public void paint(Graphics g) { g. draw. String(“Hello World !”, 25); } } 60
Calling an Applet (c) Rajkumar
Execution of Applets (c) Rajkumar 1 APPLET Development “hello. java” AT CDAC-India Hello Java 2 4 3 hello. class AT C-DAC’S WEB SERVER
Web Perspective (c) Rajkumar c How did Web interactions work? c How do they work with Java? c Distributed Java objects and the Web 63
Classical Web Perspective (c) Rajkumar 64
Java Web Perspective (c) Rajkumar 65
Significance of downloading Applets (c) Rajkumar c Interactive WWW c Flashy animation instead of static web pages c Applets react to users input and dynamically change c Display of dynamic data c WWW with Java - more than a document publishing medium http: //www. javasoft. com/applets/alpha/applets/Stock. Demo/standal one. html 66
Power of Java and the Web (c) Rajkumar Deliver applications, not just information ] Eliminate porting ] Eliminate end-user installation ] Slash software distribution costs ] Reach millions of customers - instantly ] 67
Lifecycle of Java Code (c) Rajkumar 68
Bytecode Verifier (c) Rajkumar c Called when class is first loaded in runtime environment c Verifies bytecodes meet certain set of properties c Verifier uses Theorem Prover c Verified code runs faster c After verification, interpreter defines memory layout 69
Class Loader (c) Rajkumar c Unique “Namespace” for each origin c Local namespace classes are called “built-ins” c Prevents class “spoofing” 70
Security Manager (c) Rajkumar c Prevents unauthorized disk read/writes c Restricts network access c Other access restrictions (native methods) c Implementation is browser dependent 71
General Language Features (c) Rajkumar c C/C++ like syntax c No pointers c Objects all the way down c Objects request services of other objects through messages c Messages result in invocation of class methods 72
Removed From C++ (c) Rajkumar c Operator overloading c Pointers and Array/pointers c Multiple-inheritance of implementation c Enum, typedef, #define c Copy constructors, destructors c Templates c And other stuff. . 73
Added or Improved over C++ (c) Rajkumar c Interfaces: type Vs. class c Garbage collection c Exceptions (More powerful than C++) c Strings c Instanceof c Package c Multi-threads 74
Declaring Classes (c) Rajkumar class Queue { Object data[]; Queue (int size) { // Constructor data = new Object[size]; } void add(Object o) { // add to array in class specific manner. . . } // … other methods… } 75
Inheritance in Java (c) Rajkumar class Priority. Queue extends Queue { Priority. Queue (int size) { // Constructor super(size); // Call Queue constructor: use data[] // Class specific initialization } void add(Object o) { // Overriden method // add to array in class specific manner. . . } // … other methods… } 76
Creating and Using Objects (c) Rajkumar Priority. Queue p = new Priority. Queue(10); // Q of size 10 String s = “This is a string”; p. add(s); // Add string to priority queue… p. add(this); // Add object calling this code to queue. . . 77
Class Methods and Variables (c) Rajkumar n int pi = Math. PI; n int the. Max = Math. max(x, 6); Definitions: n public final static double PI = 3. 14159265358979323846; n public static int max(int a, int b); 78
Access Rules (c) Rajkumar n public n private n protected n package (Default - no keyword) 79
Using Threads (c) Rajkumar n Define a Thread class public My. Thread extends Thread { public void run() { // Override default method while (true) { // do custom code… …. n Using the thread My. Thread t = new My. Thread(); t. start(); // Start the thread. . . Detailed discussion on Threads, later 80
Strings (c) Rajkumar c The language defines strings as objects c do. Something("abc" + "cde"); c do. Something(String s) {. . } c String abc = new String(“Hello”); c System. out. println(abc); 81
Exceptions (c) Rajkumar c Try, catch, throw, finally c try { failure_Prone_Call(); } c catch (File_Exception f) {. . Handle f. . } c finally { do_This_Regardless(); } c Exception signatures are checked: void foo() throws Type. C; c Exceptions must be caught or declared c Errors do not have to be caught c Surprisingly effective at producing robust code 82
Exception Handling (c) Rajkumar try { // … some code here. . . int x = y/z; } catch (Arithmetic. Exception e) { System. out. println(“Divide by zero error!”) } catch (Exception e) { System. out. println(“Some other error!”) } finally { // Optional. . . ++z; } 83
More about Exceptions (c) Rajkumar Very Strict Exception Handling Rules: n All methods that throw an exception must be caught or rethrown (except for runtime exceptions) n Hierarchy of Exception classes n Can create custom Exception classes n Cause own exception with “throw” clause 84
Interfaces (c) Rajkumar c Interfaces are a way to declare an Abstract type without implementation c Interfaces are like classes but without implementation c Interfaces are expressions of pure designs only c Example Interface interface sqrt{ int sqrt(int newint); } c Implementing an interface class myclass implements sqrt{. . } 85
Interface: Type and Sub-Type (c) Rajkumar c Pure type of a set of objects interface Observer { void update (Observable o); } c Interfaces can form a graph interface List_Observer extends Observer { void update. Item (int position); } 86
Class Implements Interface (c) Rajkumar c Complete type/class separation possible class Order implements Observer { public void update (Object o) { // do stuff toupdate } // data and other implementation } c c Any object can support multiple interfaces Client can see its types separately or conjoined A powerful approach to design, roles, distribution, design patterns Takes a little bit of getting used to 87
Implementation Inheritance (c) Rajkumar c Single inheritance of implementation class X extends W implements E, F { // Stuff in class X } 88
Interfaces and Classes! (c) Rajkumar 89
Uses of Interfaces (c) Rajkumar c. There are considerable problems due to Multiple Inheritance c. Interfaces in a way add multiple inheritance to Java c. Interfaces may be extended too, more than once 90
Garbage Collected (c) Rajkumar c No more manual memory management class Recycler { public void recycle () { Hashtable t; for (int i=0; i<100; i++) { t = new Hashtable(); } } } c Significant elimination of programming bugs 91
instanceof and casts (c) Rajkumar c Run-time type query void foo (Object x) { if (x instanceof Order) { Order o = (Order) x; //. . . Do stuff with o } } c Can query for an interface or a class 92
Packages (c) Rajkumar c No more #include package Shopper; import java. awt. *; // define Shopper interfaces and classes c Provides namespace and export features c class, sub-class, intra-package, and inter package control c Package typically maps to a directory 93
Packages and Utilities (c) Rajkumar c Packages - helps in organizeing classes i. e. , keep the class name space compartmentalized c For Naming and Visibility c Similar to C++ Class Libraries c Bring in classes from other packages with the import keyowrd c Ad hoc collection of utility classes: Storing collection of objects Interfacing with low-level system functions Math functions (java. lang. Math) 94
Rich Object Environment (c) Rajkumar c Core Classes language Utilities Input/Output Low-Level Networking Abstract Graphical User Interface c Internet Classes TCP/IP Networking WWW and HTML Distributed Programs 95
Main Packages (c) Rajkumar n java. lang n java. util n java. io n java. awt. image n java. applet n java. net 96
java. lang Core Classes (c) Rajkumar c Base Class: Object c String s = “This is number “ + 6; c Math. sqrt(4. 0); c System. out. println(“An error occurred”); System. exit(1); 97
java. lang Type Wrappers (c) Rajkumar c Literals: int, double, boolean, char … c Literals wrapped in Classes: Integer, Double, Boolean, Character c Literals used for high performance c Examples: int x = Integer. parse. Int(“ 6”); Integer I = new Integer(999); double dbl = I. double. Value(); //Returns 999. 000 98
java. io - Filtering input streams (c) Rajkumar try { // Open the file. . . Data. Input. Stream dis = new Data. Input. Stream( new Buffered. Input. Stream( new File. Input. Stream(“my. File”)) ); // Read lines until EOF is reached. . . String s; while((s = dis. read. Line()) != null) // Read CR delimited lines System. out. println(s); dis. close(); } // Handle any exceptions caused by the process. . . catch (IOException e) { System. out. println(e. get. Message()); } 99
(c) Rajkumar GUI Programming in Java (AWT and Event Handling) 100
AWT - Abstract Windowing Toolkit (c) Rajkumar c Single Windowing Interface on Multiple Platforms c Supports functions common to all window systems c Uses Underlying Native Window system c AWT provides c GUI widgets c Event Handling c Containers for widgets c Layout managers c Graphic operations 101
AWT - Abstract Window Toolkit (c) Rajkumar c Portable GUI - preserves native look & feel c Standard GUI Components (buttons…) c Containers - Panels, Frames, Dialogs c Graphics class for custom drawing c Layouts responsible for actual positioning of components: c Border. Layout, Grid. Layout, Flow. Layout, null layoit 102
Adding Components via Layouts (c) Rajkumar set. Layout(new Border. Layout()); // Add text field to top add("North", new Text. Field()); // Create the panel with buttons at the bottom. . . Panel p = new Panel(); // Flow. Layout p. add(new Button("OK")); p. add(new Button("Cancel")); add("South", p); 103
Adding Components via Layouts (c) Rajkumar 104
Popup Menu and Event Handling. . . (c) Rajkumar //popup. java: popup menu and event handling import java. applet. Applet; import java. awt. *; import java. awt. event. *; public class popup extends Frame implements Action. Listener, Mouse. Listener { Text. Field text 1; Popup. Menu popup; Menu. Item menuitem 1, menuitem 2, menuitem 3; public popup() { super( "Popup Menu" ); set. Layout(new Flow. Layout()); set. Bounds(10, 300, 200 ); set. Visible(true); init(); } public void init() { popup = new Popup. Menu("Resource Usage" ); 105
Popup Menu and Event Handling. . . (c) Rajkumar menuitem 1 = new Menu. Item("CPU"); menuitem 1. add. Action. Listener(this); menuitem 2 = new Menu. Item("Disk"); menuitem 2. add. Action. Listener(this); menuitem 3 = new Menu. Item("Memory"); menuitem 3. add. Action. Listener(this); popup. add(menuitem 1); popup. add(menuitem 2); popup. add(menuitem 3); add(popup); text 1 = new Text. Field(20); text 1. set. Bounds(20, 40, 120, 30 ); add(text 1); add. Mouse. Listener(this); } public void mouse. Pressed(Mouse. Event e ) { if( e. get. Modifiers() != 0 ) popup. show(this, e. get. X(), e. get. Y() ); } 106
Popup Menu and Event Handling (c) Rajkumar public void mouse. Released( Mouse. Event e ) { System. out. print("Mouse Releasedn" ); } public void mouse. Entered( Mouse. Event e ) { System. out. print("Mouse Enteredn" ); } public void mouse. Exited( Mouse. Event e ) { System. out. print("Mouse Exitedn" ); } public void action. Performed( Action. Event e ) { if( e. get. Source() == menuitem 1 ) { text 1. set. Text("CPU"); } if( e. get. Source() == menuitem 2 ) { text 1. set. Text("Disk"); } if( e. get. Source() == menuitem 3 ) { text 1. set. Text("Memory"); } } public static void main( String args[] ) { popup p = new popup(); } } 107
Custom Drawing (c) Rajkumar // My. Applet. java: draws rectangle with yellow color fill import java. applet. *; import java. awt. *; public class My. Applet extends Applet { public synchronized void paint(Graphics g) { int x, y, width, height; Dimension dm = size(); x = dm. width/4; y = dm. height / 4; width = dm. width / 2; height = dm. height / 2; // Draw the rectangle in the center with colors! g. set. Color(Color. blue); g. draw. Rect(x, y, width, height); g. set. Color(Color. yellow); g. fill. Rect(x + 1, y + 1, width - 2, height - 2); } } 108
java. applet (c) Rajkumar c Applet c Class representation of applet c init() method called when first loaded c start() when applet’s Web page becomes active c stop() when user leaves Web Page c Actually derived from AWT Panel c Applet. Context c Hooks into Browser environment c Can be used to link to another Web page 109
A sample Applet (c) Rajkumar // Hello. Applet. java: for processing applet methods import java. awt. *; import java. applet. *; public class Hello. Applet extends Applet { public void init() { System. out. println("init() method invoked"); } public void start() { System. out. println("start() method invoked"); } public void paint( Graphics g ) { System. out. println("paint() method invoked"); g. draw. String( "Hello World", 24, 25 ); } public void stop() { System. out. println("stop() method invoked"); } } 110
(c) Rajkumar Network/Socket Programming in Java 111
java. net (c) Rajkumar c Used to manage: c URL streams c Client/server sockets c Datagrams 112
Server side Socket Operations (c) Rajkumar 1. Open Server Socket: String server; Socket slink; Data. Output. Stream os; Data. Input. Stream is; server = new Server. Socket( PORT ); 2. Wait for Client Request: Socket client = server. accept(); 3. Create I/O streams for communicating to clients is = new Data. Input. Stream( client. get. Input. Stream() ); os = new Data. Output. Stream( client. get. Output. Stream() ); 4. Perform communication with client Receiive from client: String line = is. read. Line(); Send to client: os. write. Bytes("Hellon"); 5. Close sockets: client. close(); For multithreade server: while(true) { i. wait for client requests (step 2 above) ii. create a thread with “client” socket as parameter (the thread creates streams (as in step (3) and does communication as stated in (4). Remove thread once service is provided. } 113
Client side Socket Operations (c) Rajkumar 1. Get connection to server: client = new Socket( server, port_id ); 2. Create I/O streams for communicating to clients is = new Data. Input. Stream( client. get. Input. Stream() ); os = new Data. Output. Stream( client. get. Output. Stream() ); 3. Perform communication with client Receiive from client: String line = is. read. Line(); Send to client: os. write. Bytes("Hellon"); 4. Close sockets: client. close(); 114
Echo Server Client. . (c) Rajkumar //client. java: client interface to server import java. io. *; import java. net. *; public class client { int port_id; String server; Socket slink; Data. Output. Stream os; Data. Input. Stream is; Data. Input. Stream kbd; public client( String args[] ) { server = args[0]; port_id = Integer. value. Of(args[1]). int. Value(); try { slink = new Socket( server, port_id ); os = new Data. Output. Stream( slink. get. Output. Stream() ); is = new Data. Input. Stream( slink. get. Input. Stream() ); kbd = new Data. Input. Stream( System. in ); } 115
Echo Server Client. . (c) Rajkumar catch( Unknown. Host. Exception e ) { System. err. println( "Don't know about host: " ); System. exit(1); } catch( IOException e ) { System. err. println( "Could not get I/O for the connection to "+server); System. exit(1); } } void communicate() { while(true) { try { System. out. print("Enter Input
Echo Server Client. . if( line. equals("end") ) (c) Rajkumar { os. close(); is. close(); slink. close(); break; } String line 2 = is. read. Line(); System. out. println("Output: "+line 2); } catch( IOException e ) { System. out. println(e); } } } public static void main( String [] args ) { if( args. length < 2 ) { System. out. println("Usage: java client server_name port_id" ); System. exit(1); } client cln = new client( args ); cln. communicate(); } } 117
Echo Server. . . (c) Rajkumar // server. java: echo server import java. io. *; import java. net. *; public class server { // public final static int PORT = 4779; public static void main( String [] args ) { Server. Socket server = null; Data. Output. Stream os = null; Data. Input. Stream is = null; boolean shutdown = false; if( args. length < 1 ) { System. out. println( "Usage: java server port_num" ); System. exit( 1 ); } int PORT = Integer. value. Of(args[0]). int. Value(); try { server = new Server. Socket( PORT ); } 118
Echo Server. . . (c) Rajkumar catch( IOException e ) { System. err. println( "Could not get I/O for the connection to: "); } while(!shutdown) { if( server != null ) { try { Socket client = server. accept(); System. out. println("Connected"); Inet. Address cip = client. get. Inet. Address(); System. out. println( "Client IP Addr: "+cip. to. String()); is = new Data. Input. Stream( client. get. Input. Stream() ); os = new Data. Output. Stream( client. get. Output. Stream() ); for(; ; ) { String line = is. read. Line(); if( line == null ) break; 119
Echo Server. . . (c) Rajkumar if( line. starts. With("end" ) ) { shutdown = true; break; } os. write. Bytes(line. to. Upper. Case()); os. write. Bytes("n"); System. out. println(line); } is. close(); client. close(); } catch( Unknown. Host. Exception e ) { System. err. println( "Server Open fails" ); } catch( IOException e ) { System. err. println( "Could not get I/O for the connection to: "+args[0]); } } } 120
Echo Server System. out. println( "Server Down" ); (c) Rajkumar try { server. close(); } catch(IOException e) {} } } 121
(c) Rajkumar Multithreading in Java (A built-in feature in Java) 122
What are Threads? (c) Rajkumar Ø Thread is a piece of code that can execute in concurrence with other threads. Ø It is a schedule entity on a processor Hardware Context Registers Status Word 0 Local state 0 Global/ shared state 0 PC 0 Hard/Software Context Program Counter Running Thread Object 123
Single and Multithreaded Processes (c) Rajkumar Single-threaded Process Multiplethreaded Process Threads of Execution Multiple instruction stream Single instruction stream Common Address Space 124
OS: Multi-Processing, Multi-Threaded (c) Rajkumar Threaded Libraries, Multi-threaded I/O Application CPU CPU Better Response Times in Multiple Application Environments CPU CPU Higher Throughput for Parallelizeable Applications 125
Threaded Process Model (c) Rajkumar THREAD STACK SHARED MEMORY Threads within a process THREAD DATA THREAD TEXT l Independent executables l All threads are parts of a process hence communication easier and simpler. 126
Levels of Parallelism: Thread Granularity (c) Rajkumar Task i-l m Task m Control m Data m Multiple Issue func 1 ( ) {. . . . } a ( 0 ) =. . b ( 0 ) =. . + Task i func 2 ( ) {. . . . } a ( 1 )=. . b ( 1 )=. . x Task i+1 func 3 ( ) {. . . . } a ( 2 )=. . b ( 2 )=. . Load Code-Granularity Code Item Large grain (task level) Program Medium grain (control level) Function (thread) Fine grain (data level) Loop Very fine grain (multiple issue) With hardware 127
Multithreading - Uniprocessors (c) Rajkumar c Concurrency Vs Parallelism K Concurrency P 1 P 2 CPU P 3 time Number of Simulatneous execution units > no of CPUs 128
Multithreading Multiprocessors (c) Rajkumar Concurrency Vs Parallelism CPU P 1 CPU P 2 CPU P 3 time No of execution process = no of CPUs 129
Threads (c) Rajkumar c Java has built in thread support for Multithreading c Synchronization c Thread Scheduling c Inter-Thread Communication: current. Thread start set. Priority yield run get. Priority sleep stop suspend resume c Java Garbage Collector is a low-priority thread 130
Threading Mechanisms. . . (c) Rajkumar c c Create a class that extends the Thread class Create a class that implements the Runnable interface 131
1 st method: Extending Thread class (c) Rajkumar c 1 st Method: Extending the Thread class My. Thread extends Thread { public void run() { // thread body of execution } } c Creating thread: My. Thread thr 1 = new My. Thread(); c Start Execution: thr 1. start(); 132
2 nd method: Threads by implementing Runnable interface class (c) Rajkumar Class. Name implements Runnable {. . . public void run() { // thread body of execution } } c Creating Object: Class. Name my. Object = new Class. Name(); c Creating Thread Object: Thread thr 1 = new Thread( my. Object ); c Start Execution: thr 1. start(); 133
Multi-Threaded (c) Rajkumar c Thread and its subclasses run one thread per instance c class My. Thread extends Thread { public void run () {. . . Start running } } c Any Runnable object can wrap a thread around itself c class Server implements Runnable { Thread t; Server () { t = new Thread(this); . } c public void run () {. . . Start running } } c Thread control: Thread. start(), Thread. stop() 134
Manipulation of Current Thread // Current. Thread. Demo. java (c) Rajkumar class Current. Thread. Demo { public static void main(String arg[]) { Thread ct = Thread. current. Thread(); ct. set. Name( "My Thread" ); System. out. println("Current Thread : "+ct); try { for(int i=5; i>0; i--) { System. out. println(" " + i); Thread. sleep(1000); } } catch(Interrupted. Exception e) { System. out. println("Interrupted. "); } } } Run: Current Thread : Thread[My Thread, 5, main] 5 4 3 2 1 135
Creating new Thread. . . (c) Rajkumar // Thread. Demo. java class Thread. Demo implements Runnable { Thread. Demo() { Thread ct = Thread. current. Thread(); System. out. println("Current Thread : "+ct); Thread t = new Thread(this, "Demo Thread"); t. start(); try { Thread. sleep(3000); } catch(Interrupted. Exception e) { System. out. println("Interrupted. "); } System. out. println("Exiting main thread. "); } 136
. . . Creating new Thread. (c) Rajkumar public void run() { try { for(int i=5; i>0; i--) { System. out. println(" " + i); Thread. sleep(1000); } } catch(Interrupted. Exception e) { System. out. println("Child interrupted. "); System. out. println("Exiting child thread. "); } public static void main(String args[]) { new Thread. Demo(); } } Run: Current Thread : Thread[main, 5, main] 5 4 3 Exiting main thread. 2 1 Exiting child thread. } 137
Thread Priority. . . (c) Rajkumar // Hi. Lo. Pri. java class Clicker implements Runnable { int click = 0; private Thread t; private boolean running = true; public Clicker(int p) { t = new Thread(this); t. set. Priority(p); } public void run() { while(running) click++; } public void start() { t. start(); } public void stop() { running = false; } } 138
. . . Thread Priority (c) Rajkumar class Hi. Lo. Pri { public static void main(String args[]) { Thread. current. Thread(). set. Priority(Thread. MAX_PRIORITY); Clicker Hi = new Clicker(Thread. NORM_PRIORITY+2); Clicker Lo = new Clicker(Thread. NORM_PRIORITY-2); Lo. start(); Hi. start(); try { Thread. sleep(10000); } catch (Exception e) { } Lo. stop(); Hi. stop(); System. out. println(Lo. click + " vs. " + Hi. click); } } Run 1: (on Solaris) 0 vs. 956228 Run 2: (Window 95) 304300 vs. 4066666 139
Threads Need Synchronization (c) Rajkumar c Server instances lock themselves at method-level c class Buffer { // synchronize on buffer instance public synchronized void put (int i). . . c public synchronized int get (). void safe (). } c Client instance locks a server object before using it c synchronized (array_to_sort) {. . . }wait(); // within synchronized methodnotify(); c notifyall(); // wake up from a wait 140
Monitor model (for Syncronisation) (c) Rajkumar Method 1 Method 2 Key Block 1 Threads Monitor (synchronised) solves race-condition problem 141
Threads Synchronisation. . . (c) Rajkumar // Synch. java: race-condition without synchronisation class Callme { // Check synchronized and unsynchronized methods /* synchronized */ void call(String msg) { System. out. print("["+msg); try { Thread. sleep(1000); } catch(Exception e) { } System. out. println("]"); } } class Caller implements Runnable { String msg; Callme Target; public Caller(Callme t, String s) { Target = t; msg = s; new Thread(this). start(); } 142
. . . Threads Synchronisation. public void run() { (c) Rajkumar Target. call(msg); } } class Synch { public static void main(String args[]) { Callme Target = new Callme(); new Caller(Target, "Hello"); new Caller(Target, "Synchronized"); new Caller(Target, "World"); } } Run 1: With unsynchronized call method (race condition) [Hello[Synchronized[World] ] ] Run 2: With synchronized call method [Hello] [Synchronized] [World] Run 3: Synchronized object in run(): synchronized(Target){ Target. call(msg); } The output is the same as Run 2 143
Queue (no inter-threaded communication). . . // pc. java: produce and consumer (c) Rajkumar class Queue { int n; synchronized int get() { System. out. println("Got : "+n); return n; } synchronized void put(int n) { this. n = n; System. out. println("Put : "+n); } } class Producer implements Runnable { Queue Q; Producer(Queue q) { Q = q; new Thread( this, "Producer"). start(); } 144
Queue (no inter-threaded communication). . . (c) Rajkumar public void run() { int i = 0; while(true) Q. put(i++); } } class Consumer implements Runnable { Queue Q; Consumer(Queue q) { Q = q; new Thread( this, "Consumer"). start(); } public void run() { while(true) Q. get(); } } 145
. . . Queue (no inter-threaded communication). (c) Rajkumarclass PC { public static void main(String[] args) { Queue Q = new Queue(); new Producer(Q); new Consumer(Q); } } Run: Put: 1 Got: 1 Put: 2 Put: 3 Got: 3 ^C 146
Queue (interthread communication). . . (c) Rajkumar// PCnew. java: produce-consumenr with interthread communication class Queue { int n; boolean Value. Set = false; synchronized int get() { try { if(!Value. Set) wait(); } catch(Interrupted. Exception e) { } System. out. println("Got : "+n); Value. Set = false; notify(); return n; } 147
Queue (interthread communication). . . (c) Rajkumar synchronized void put(int n) { try { if(Value. Set) wait(); } catch(Interrupted. Exception e) { } this. n = n; System. out. println("Put : "+n); Value. Set = true; notify(); } } class Producer implements Runnable { Queue Q; Producer(Queue q) { Q = q; new Thread( this, "Producer"). start(); } 148
Queue (interthread communication). . . (c) Rajkumar public void run() { int i = 0; while(true) Q. put(i++); } } class Consumer implements Runnable { Queue Q; Consumer(Queue q) { Q = q; new Thread( this, "Consumer"). start(); } public void run() { while(true) Q. get(); } } 149
. . . Queue (no interthread communication). (c) Rajkumar class PCnew { public static void main(String[] args) { Queue Q = new Queue(); new Producer(Q); new Consumer(Q); } } Run: Put : 0 Got : 0 Put : 1 Got : 1 Put : 2 Got : 2 Put : 3 Got : 3 Put : 4 Got : 4 ^C 150
Deadlock. . . // Dead. Lock. java (c) Rajkumar class A { synchronized void foo(B b) { String name = Thread. current. Thread(). get. Name(); System. out. println(name + " entered A. foo"); try { Thread. sleep(1000); } catch(Exception e) { } System. out. println(name + " trying to call B. last()"); b. last(); } synchronized void last() { System. out. println("Inside A. last"); } } 151
Deadlock. . . class B { synchronized void bar(A a) (c) Rajkumar { String name = Thread. current. Thread(). get. Name(); System. out. println(name + " entered B. bar"); try { Thread. sleep(1000); } catch(Exception e) { } System. out. println(name + " trying to call A. last()"); a. last(); } synchronized void last() { System. out. println("Inside B. last"); } } 152
. . . Deadlock. class Dead. Lock implements Runnable { (c) Rajkumar A a = new A(); B b = new B(); Dead. Lock() { Thread. current. Thread(). set. Name("Main Thread"); new Thread(this). start(); a. foo(b); System. out. println("Back in the main thread. "); } public void run() { Thread. current. Thread(). set. Name("Racing Thread"); b. bar(a); System. out. println("Back in the other thread"); } public static void main(String args[]) { new Dead. Lock(); } } Run: Main Thread entered A. foo Racing Thread entered B. bar Main Thread trying to call B. last() Racing Thread trying to call A. last() ^C 153
Threads in Action. . . Cooperative threads - File Copy (c) Rajkumar reader() { - - - - lock(buff[i]); read(src, buff[i]); unlock(buff[i]); - - - - } buff[0] buff[1] writer() { - - - - - lock(buff[i]); write(src, buff[i]); unlock(buff[i]); - - - - - } Cooperative Parallel Synchronized Threads 154
Threads in Action. . . Multithreaded Server (c) Rajkumar Server Process Client Process Server Threads Client Process User Mode Kernel Mode Message Passing Facility 155
A Look Inside the Java Platform (c) Rajkumar Applets and Applications The Java Base Platform (in black) Java Base API Java Standard Extension API Java Base Classes Java Standard Extension Classes Java Virtual Machine Porting Interface Adapter Browser OS Hardware Adapter OS Adapter Java. OS OS Hardware Java on a Desktop OS Java on a Smaller OS Java on Java. OS Network Java on a Browser 156
Java Applications! (c) Rajkumar Java applications are now available c Cost of manfg zero, cost of distribution zero, cost of marketing zero! c Hot Java is lean - loads everything else from the net. c Java itself is small - 40 k to 225 k c New class of small machines will emerge c Java on cellular phones, credit cards, washing machines, and everywhere ? c 157
Universal Interface (c) Rajkumar Web Servers with JAVA applications Internet Clients running any OS on any platform 158
Java on my platform ? (c) Rajkumar c Sun (SPARC) ftp: //java. sun. com c Sun(x 86) ftp: //xm. com: /pub/ c IBM(Aix, OS/2)ftp: //ncc. hursley. ibm. com/javainfo c DEC(Alpha OSF/1) http: //www. gr. osf. org: 8001/projects/web/java/ c SGI http: //liawww. epfl. ch/~simon/java/irixjdk. html c HP http: //www. gr. osf. org: 8001/projects/web/java c Linux http: //www. blackdown. org c AT & T http: //www. gr. osf. org: 8001/projects/web/java c Windows 3. 1 http: //www. alphaworks. ibm. com 159
(c) Rajkumar Java Development Tools (Present and Planned) 160
Sun’s Java Work. Shop (c) Rajkumar c JDK: c Compiler and runtime environment c Class Libraries c Documentation c javadoc - Automated Documentation c Takes comments and converts to HTML c IDE: Visual Java, and integrated tools, Java. Beans c Other Products and API: Java. Help, Java Card, Java Blend, Java. OS, Java Mail, Java Management, Java Electronic Commerce Framework c Java Enterprise API: Java Naming and Directory Interface, Java IDL, JDBC, RMI and Object Serialization 161
Symantec Cafe 1. 0 (Released) (c) Rajkumar c Full IDE for Windows 95/NT c Graphic Development Tools c Two Compilers c Debugger c Class Browser 162
Microsoft Jakarta (Planned) (c) Rajkumar c Visual C++ type interface c Will Support Active. X/COM c Internet Explorer 3. 0 will have Just-In-Time Java compiler 163
Borland JBuilder (c) Rajkumar c Visual RAD workbench for maximum productivity. c Rapid Application Development (RAD) and Open Component Architecture patterned after Delphi. c 100+ Java. Bean components, with source code, for drag-and-drop applications. c Beans Express--easiest way to create industry-standard Java-Bean components. c Data. Express -- the fastest way to build business and database appplications. c Borland Data. Gateway for Java connectivity to all major database servers. c Multi-tier applications with integrated RMI and CORBA. c Versions: Standard, Professional, & Client/Server 164
Challenges & Possible Directions (c) Rajkumar Q Performance Q AWT - need better GUI! Q Maintaining Interoperability Q Security - current restrictions limit what can be done Q Native Compilers Q Is Portability that Important? 165
Comments (c) Rajkumar n Java is a fun and easy programming language n Portability = Mediocrity? n Java will become a programming language of choice, but may take on a final form that will surprise many! 166
JDBC (c) Rajkumar c Java API for Relational Databases c Being standardized by all major players 167
Javascript and Java (Preview) (c) Rajkumar c Javascript can control Java applets c Static data accessible as properties of applet c var i = Bank. Account c Public methods invocable on Java instances c Provided those instances are accessible through the Applet c Applet is accessible through document c document. applet_Name_Attribute. do_Stuff() 168
Java for HPC! (c) Rajkumar c Many efforts are in in progress for making java as a language for parallel programming. c Java computing frameworks (HPC, numeric, data parallel) c Java in distributed simulations and applications (e. g. , real-world HPC, grand chalenge) c Source to source translators (C, Fortran, C++ to Java) c Web based computation environment in Java c Java for HPC conference: http: //www. cs. ucsb. edu/conferences/java 98 c Java for Science and Engineering computing: subscribe java-for-cse to majordomo@npac. syr. edu c http: //www. jhpc. org 169
How to Convert Programs to AWT 1. 1. . . (c) Rajkumar 1. Change source code so that it import event package: import java. awt. event. *; 2. Figure out which component generates each event type: (1. 0 uses handle. Event() and action()) Button, List, Menu. Item, Text. Field: Interface: Action. Listener Method: action. Performed(Action. Event event) Checkbox, Checkbox. Menu. Item, Choice: Interface: Item. Listener Method: item. State. Changed(. . ) Dialog, Frame: Interface: Window. Listener Method: window. Closing(), window. Opened(), . . . 170
How to Convert Programs to AWT 1. 1. . . (c) Rajkumar 3. Change class declaration so that class implements public class My. Class extends Some. Component implements Action. Listener 4. Register action Listener new. Component. Object. add. Action. Listener(this); 5. Change event handling method: Old: public boolean action(Event e, Object arg) New: public void action. Performed(Action. Event e) 171
How to Convert Programs to AWT 1. 1 (c) Rajkumar 6. Delete the event handling code in this way (a) Delete all return statements (b) Change e. target to e. get. Source() (c) Delete all code the unnecessarily tests for which component the event come from (d) Perform any other modification require to make the program compile 172
Just to Summarize (c) Rajkumar n Java as a Comprehensive Programming Solution c Object Oriented c Portable c High Performance c Geared for Distributed Environments c Secure c Highly suitable for Internet programming 173
Summary (c) Rajkumar c Java is really very well poised c Incredible leverage from the Web c Will impact the C++ and Smalltalk markets c Rate of progress is astonishingly high Development environments – CORBA linkages – Components – c Fasten you seat-belts! 174
The End (c) Rajkumar Questions ? 175
Thank You. . . (c) Rajkumar ? 176



