Internet and Java Revolutions Impact on Education (c) Rajkumar 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 Potential delivery sites are widely distributed Information is rapidly changing Connections to the Internet have become ubiquitous Different learners have different needs 2 Agenda (c) Rajkumar Internet and its Evolution Internet Tools Web and its Programming Internet as a delivery Vehicle Java for Internet Programming Java Nuts and Bolts Java Platform Developing Applets and Applications 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 Internet is much bigger than what we think More than 25 years old More than doubling every year Technology effect suddenly every body sees the need for a technology like the radio or the TV 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.0 3.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 Use of internet advertisement/elections/newspapers information is public Ubiquitous technology Network is the computer Intranets - internal TCP/IP nets PC accounts for 55% of total IT 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 View text, graphics, pictures, sounds, video Web Browser HyperText Markup Language (HTML) Computer Independent Operating System Independent 11 Web Browsers (c) Rajkumar Netscape Navigator Microsoft Internet Explorer Omni Web NCSA Mosaic 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 Client Server Server Server Client Server Client Client 15 Generating Web Pages (c) Rajkumar Simple Text Editor Word Processor or other tool export e.g., Internet Assistant for Microsoft Word HTML Editor Open file in Netscape Composer Last step is to put the file(s) on an HTML server 16 HTML (c) Rajkumar Hypertext -A little Hype and a Little Text. Hypertext point to information which can be local or remotely located. HTML -Derivative of the SGML( Standard Generalized Markup Language). HTML -information , commands for the Browser for formatting documents. HTML -The de-facto language for publishing on the Internet. 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 Web -Designed around Client/Server Architecture Web Clients ( Web Browsers ) -send requests for documents to any Web Server Web Server -Program that responds to HTTP requests Hyperlink Web client connects to the specified Web Server The server responds by sending the information asked for 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 HTML document (c) Rajkumar <HTML> <TITLE>Centre for Development of Advanced Computing </TITLE> <BODY BGCOLOR=“#E7CCCC” TEXT=“#000000” LINK=“#0000FF”> ... ... <A HREF=“mailto:webmaster@cdacb.ernet.in> webmaster</A> </BODY> </HTML> 21 (c) Rajkumar 22 URLs (c) Rajkumar URLs- The Hypertext links we use today are known as Universal Resource Locator URLs-Each name is unique across the Internet An URL looks like this http://system.domain.ext:999/dir1/dir2/dir3/file.html?blue# Parts of a URL are, Service type, System Name, Port, Directory path, Filename,Search Components or Variables Service type, System Name, Directory path are the required parts of the URL 23 CGI (Common Gateway Interface) (c) Rajkumar CGI makes the Web a Two-way interface CGI -lets the user run a script when a web page is accessed Information from the Web Client is received through simple ‘fill-in-the-forms’ kind of interface FORMS - Integrates data sheets, menus , check boxes CGI makes the Web interactive CGI -complicated to setup ,requires PERL knowledge HTML books talk less about CGI 24 Authoring tools and Filters (c) Rajkumar Authoring tools- Editors for HTML documents Editors similar to WYSIWYG word processing programs Semi-WYSIWYG or completely WYSIWYG Provide syntax checking and correction Filters -Convert legacy documents to HTML format Filters are useful when the documents already exist Authoring tools- HoTMetaL, HTML Assistant Shareware 25 Preconfigured v/s Integrated Internet Products (c) Rajkumar Integrated Internet Products- From multiple vendors Preconfigured Systems- Web Server and a Client ready to use Sun’s Netra Internet Server SGI’s WebFORCE Indy and WebFORCE Challenge S Apple’s Internet Server Solution DEC’s Internet AlphaServer Integraph’s Web Server 10 26 Future Directions (c) Rajkumar Additions to HTML (Grammar, Maths, Display control) VRML (Virtual Reality Markup Language) Security - Using Scrambling and Encryption Common Client Interface (CCI)- Allows Clients to pass information back and forth between the Browser and the External Viewer Charge Mechanisms 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: * Make web attractive through: - computing facilities, accommodation, recreation, etc.. 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 http://www.whitehouse.gov ( The WhiteHouse) http://www.w3.org (Everything about the WWW) http://sunsite.unc.edu (Software on Sun) http://www.indnet.org (India Net Foundation Services) telnet://www.arbornet.org (Free Public Access Unix System) http://www.infoseek.com (Search engines, Add URL) http://www.infophil.com (World Alumni on the net) http://www.rocketmail.com (Free Email ) http://members.tripod.com (Free Website,2MB space) http://www.bangaloreonline.com (Offers virtual web servvices for compinies to host their website). http://www.prajavani.com (Kannada news paper on web) 30 Class Sites To Visit (c) Rajkumar http://truth.phil.vt.edu/wwwcourses.html http://http://fiddle.visc.ece.vt.edu/courses/ee2504/ http://adept.stanford.edu/ http://www.aoe.vt.edu/aoe5104.html http://nersp.nerdc.ufl.edu/~cgs2422/ http://www.sloan.org/oakley/misc/IMNews.html http://www.eng.fsu.edu/net98.html 31 API Bottleneck (c) Rajkumar MAC PC LAN LAN Server SUN Network 32 The OS - Platform lock (c) Rajkumar Applications tied to OS Application OS tied to Platform OS Application Application 33 The Web Application (c) Rajkumar * Seeded by HTML from CERN * Revolutionised by MOSAIC * Standardised, universal interface to data * Graphical BROWSER OS Application OS OS OS Application * Broadcast capability publish once, reach millions 34 Making life easier! (c) Rajkumar Data on the web Browser platform independent Click on application - run on any machine Java the programming language of the 21 century 35 Java and Java Computing (c) Rajkumar 36 Java - An Introduction (c) Rajkumar Java - The new programming language from Sun Microsystems Java -Allows anyone to publish a web page with Java code in it Java - CPU Independent language Created for consumer electronics Java - James , Arthur Van , and others Java -The name that survived a patent search Oak -The predecessor of Java Java is “C++ -- ++ “ 37 Java From 10,000 Ft. (c) Rajkumar According to the world, Java is... According to Sun, Java is... On closer inspection, Java is 38 According to the World, Java Is... (c) Rajkumar Snazzy Web pages The cross-platform language we want The rest-of-the-worlds answer to Bill The C++ replacement we need The C++ replacement we dont need A bunch of hype 39 According to Sun, Java is... (c) Rajkumar Simple and Powerful Object Oriented Portable Architecture Neutral Distributed Multi-threaded Robust, Secure/Safe Interpreted High Performance Dynamic pogramming language/platform. Buzzword compliant! 40 On Closer Inspection, Java is... (c) Rajkumar Simple Pure Portable Surprisingly effective 41 As a whole, Java is a Comprehensive Programming Solution (c) Rajkumar Object Oriented Portable High Performance Geared for Distributed Environments Secure 42 Java as Object Oriented (c) Rajkumar “Objects all the way down” Simple and Familiar: “C++ Lite” No Pointers! Garbage Collector Dynamic Binding Single Inheritance with “Interfaces” 43 Java as Portable (c) Rajkumar Unlike other language compilers, Java complier generates code (byte codes) for Universal Machine. Java Virtual Machine (JVM): Interprets bytecodes at runtime Architecture Neutral No Link Phase 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 NT45 (c) Rajkumar Java Write Once, Run Anywhere 46 Architecture Neutral & Portable (c) Rajkumar Java Compiler -Java source code to bytecode Bytecode - an intermediate form, closer to machine representation A virtual machine on any target platform interprets the bytecode Porting the java system to any new platform involves writing an interpreter that supports the Java Virtual Machine The interpreter will figure out what the equivalent machine dependent code to run 47 Java as High Performance (c) Rajkumar JVM uses “lean and mean” bytecodes Small binary class filtes Just-in-time Compilers Multithreading Native Methods 48 Java in the World of Distributed Computing (c) Rajkumar Class Loader Lightweight Binary Class Files Multithreading Dynamic Good communication constructs Secure 49 Java as Secure (c) Rajkumar Language designed as safe Strict compiler Dynamic Runtime Loading (Verifier) 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 Yes Yes Both Poor No Yes Yes Objective C Ada Java Yes Yes Yes Yes Both Poor Yes No Yes Yes No No Yes Early Difficult No Yes Limited Yes Yes No Yes Late Yes Yes No Yes 51 Java better than C++ ? (c) Rajkumar No Typedefs, Defines, or Preprocessor No Global Variables No Goto statements No Pointers No Unsafe Structures No Multiple Inheritance No Operator Overloading No Automatic Coercions No Fragile Data Types 52 Basic Data Types (c) Rajkumar 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) String (class for manipulating strings) 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 JavaApplications (c) Rajkumar 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 Applet- A program embedded in a web page , to be run when the page is browsed . A program that contains no “main” method Application -Java interpreter Applets- Java enabled web browser (Linked to HTML via <APPLET> tag. in html file) 55 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 javac - The Java Compiler java - The Java Interpreter jdbThe Java Debugger appletviewer -Tool to run the applets javap - to print the Java bytecodes javaprof - Java profiler javadoc - documentation generator javah - creates C header files 57 Hello Internet (c) Rajkumar // hello.java: Hello Internet program class HelloInternet { public static void main(String args[]) { System.out.println(“Hello Internet”); } } 58 Program Processing (c) Rajkumar Compilation # javac hello.java results in HelloInternet.class Execution # java HelloInternet Hello Internet # 59 Simple Java Applet (c) Rajkumar // HelloWorld.java: A sample applet import java.applet.Applet; public class HelloWorld extends Applet { public void paint(Graphics g) { g.drawString(“Hello World !”,25,25); } } 60 Calling an Applet (c) Rajkumar <HTML> <TITLE> Hello Worls Applet </TITLE> <APPLET code=“HelloWorld.class” width=500 height=500> </APPLET> </HTML> 61 Execution of Applets (c) Rajkumar 1 APPLET Development “hello.java” AT CDAC-India 2 4 3 hello.class AT C-DAC’S WEB SERVER Create Applet tag in HTML document Accessing from CRAY Corp. (USA) 5 The browser creates a new window and a new thread and then runs the code Hello Java <app= “Hello”> The Internet Hello 62 Web Perspective (c) Rajkumar How did Web interactions work? How do they work with Java? 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 Interactive WWW Flashy animation instead of static web pages Applets react to users input and dynamically change Display of dynamic data WWW with Java - more than a document publishing medium http://www.javasoft.com/applets/alpha/applets/StockDemo/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 Called when class is first loaded in runtime environment Verifies bytecodes meet certain set of properties Verifier uses Theorem Prover Verified code runs faster After verification, interpreter defines memory layout 69 Class Loader (c) Rajkumar Unique “Namespace” for each origin Local namespace classes are called “built-ins” Prevents class “spoofing” 70 Security Manager (c) Rajkumar Prevents unauthorized disk read/writes Restricts network access Other access restrictions (native methods) Implementation is browser dependent 71 General Language Features (c) Rajkumar C/C++ like syntax No pointers Objects all the way down Objects request services of other objects through messages Messages result in invocation of class methods 72 Removed From C++ (c) Rajkumar Operator overloading Pointers and Array/pointers Multiple-inheritance of implementation Enum, typedef, #define Copy constructors, destructors Templates And other stuff.... 73 Added or Improved over C++ (c) Rajkumar Interfaces: type Vs. class Garbage collection Exceptions (More powerful than C++) Strings Instanceof Package 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 PriorityQueue extends Queue { PriorityQueue (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 PriorityQueue p = new PriorityQueue(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 int pi = Math.PI; int theMax = Math.max(x,6); Definitions: public final static double PI = 3.14159265358979323846; public static int max(int a, int b); 78 Access Rules (c) Rajkumar public private protected package (Default - no keyword) 79 Using Threads (c) Rajkumar Define a Thread class public MyThread extends Thread { public void run() { // Override default method while (true) { // do custom code… …. Using the thread MyThread t = new MyThread(); t.start(); // Start the thread... Detailed discussion on Threads, later 80 Strings (c) Rajkumar The language defines strings as objects doSomething("abc" + "cde"); doSomething(String s) { ..} String abc = new String(“Hello”); System.out.println(abc); 81 Exceptions (c) Rajkumar Try, catch, throw, finally try { failure_Prone_Call(); } catch (File_Exception f) { ....Handle f.... } finally { do_This_Regardless(); } Exception signatures are checked: void foo() throws TypeC; Exceptions must be caught or declared Errors do not have to be caught Surprisingly effective at producing robust code 82 Exception Handling (c) Rajkumar try { // … some code here... int x = y/z; } catch (ArithmeticException 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: All methods that throw an exception must be caught or rethrown (except for runtime exceptions) Hierarchy of Exception classes Can create custom Exception classes Cause own exception with “throw” clause 84 Interfaces (c) Rajkumar Interfaces are a way to declare an Abstract type without implementation Interfaces are like classes but without implementation Interfaces are expressions of pure designs only Example Interface interface sqrt{ int sqrt(int newint); } Implementing an interface class myclass implements sqrt{ ..........} 85 Interface: Type and Sub-Type (c) Rajkumar Pure type of a set of objects interface Observer { void update (Observable o); } Interfaces can form a graph interface List_Observer extends Observer { void updateItem (int position); } 86 Class Implements Interface (c) Rajkumar Complete type/class separation possible class Order implements Observer { public void update (Object o) { // do stuff toupdate } // data and other implementation } 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 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 There are considerable problems due to Multiple Inheritance Interfaces in a way add multiple inheritance to Java Interfaces may be extended too, more than once 90 Garbage Collected (c) Rajkumar No more manual memory management class Recycler { public void recycle () { Hashtable t; for (int i=0; i<100; i++) { t = new Hashtable(); } } } Significant elimination of programming bugs 91 instanceof and casts (c) Rajkumar Run-time type query void foo (Object x) { if (x instanceof Order) { Order o = (Order) x; // ...Do stuff with o } } Can query for an interface or a class 92 Packages (c) Rajkumar No more #include package Shopper; import java.awt.*; // define Shopper interfaces and classes Provides namespace and export features class, sub-class, intra-package, and inter package control Package typically maps to a directory 93 Packages and Utilities (c) Rajkumar Packages - helps in organizeing classes i.e., keep the class name space compartmentalized For Naming and Visibility Similar to C++ Class Libraries Bring in classes from other packages with the import keyowrd 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 Core Classes language Utilities Input/Output Low-Level Networking Abstract Graphical User Interface Internet Classes TCP/IP Networking WWW and HTML Distributed Programs 95 Main Packages (c) Rajkumar java.lang java.util java.io java.awt java.awt.image java.applet java.net 96 java.lang Core Classes (c) Rajkumar Base Class: Object String String s = “This is number “ + 6; Math Math.sqrt(4.0); System System.out.println(“An error occurred”); System.exit(1); 97 java.lang Type Wrappers (c) Rajkumar Literals: int, double, boolean, char … Literals wrapped in Classes: Integer, Double, Boolean, Character Literals used for high performance Examples: int x = Integer.parseInt(“6”); Integer I = new Integer(999); double dbl = I.doubleValue();//Returns 999.000 98 java.io - Filtering input streams (c) Rajkumar try { // Open the file... DataInputStream dis = new DataInputStream( new BufferedInputStream( new FileInputStream(“myFile”)) ); // Read lines until EOF is reached... String s; while((s = dis.readLine()) != 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.getMessage()); } 99 (c) Rajkumar GUI Programming in Java (AWT and Event Handling) 100 AWT - Abstract Windowing Toolkit (c) Rajkumar Single Windowing Interface on Multiple Platforms Supports functions common to all window systems Uses Underlying Native Window system AWT provides GUI widgets Event Handling Containers for widgets Layout managers Graphic operations 101 AWT - Abstract Window Toolkit (c) Rajkumar Portable GUI - preserves native look & feel Standard GUI Components (buttons…) Containers - Panels, Frames, Dialogs Graphics class for custom drawing Layouts responsible for actual positioning of components: BorderLayout, GridLayout, FlowLayout, null layoit 102 Adding Components via Layouts (c) Rajkumar setLayout(new BorderLayout()); // Add text field to top add("North",new TextField()); // Create the panel with buttons at the bottom... Panel p = new Panel(); // FlowLayout 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 ActionListener, MouseListener { TextField text1; PopupMenu popup; MenuItem menuitem1, menuitem2, menuitem3; public popup() { super( "Popup Menu" ); setLayout(new FlowLayout()); setBounds(10, 10, 300, 200 ); setVisible(true); init(); } public void init() { popup = new PopupMenu("Resource Usage" ); 105 Popup Menu and Event Handling... (c) Rajkumar menuitem1 = new MenuItem("CPU"); menuitem1.addActionListener(this); menuitem2 = new MenuItem("Disk"); menuitem2.addActionListener(this); menuitem3 = new MenuItem("Memory"); menuitem3.addActionListener(this); popup.add(menuitem1); popup.add(menuitem2); popup.add(menuitem3); add(popup); text1 = new TextField(20); text1.setBounds(20, 40, 120, 30 ); add(text1); addMouseListener(this); } public void mousePressed(MouseEvent e ) { if( e.getModifiers() != 0 ) popup.show(this, e.getX(), e.getY() ); } 106 Popup Menu and Event Handling public void mouseReleased( MouseEvent e ) { System.out.print("Mouse Released\n" ); } public void mouseEntered( MouseEvent e ) { System.out.print("Mouse Entered\n" ); } public void mouseExited( MouseEvent e ) { System.out.print("Mouse Exited\n" ); } public void actionPerformed( ActionEvent e ) { if( e.getSource() == menuitem1 ) { text1.setText("CPU"); } if( e.getSource() == menuitem2 ) { text1.setText("Disk"); } if( e.getSource() == menuitem3 ) { text1.setText("Memory"); } } public static void main( String args[] ) { popup p = new popup(); } (c) Rajkumar } 107 Custom Drawing (c) Rajkumar // MyApplet.java: draws rectangle with yellow color fill import java.applet.*; import java.awt.*; public class MyApplet 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.setColor(Color.blue); g.drawRect(x,y,width,height); g.setColor(Color.yellow); g.fillRect(x + 1,y + 1,width - 2,height - 2); } } 108 java.applet (c) Rajkumar Applet Class representation of applet init() method called when first loaded start() when applet’s Web page becomes active stop() when user leaves Web Page Actually derived from AWT Panel AppletContext Hooks into Browser environment Can be used to link to another Web page 109 A sample Applet (c) Rajkumar // HelloApplet.java: for processing applet methods import java.awt.*; import java.applet.*; public class HelloApplet 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.drawString( "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 Used to manage: URL streams Client/server sockets Datagrams 112 Server side Socket Operations (c) Rajkumar 1. Open Server Socket: String server; Socket slink; DataOutputStream os; DataInputStream is; server = new ServerSocket( PORT ); 2. Wait for Client Request: Socket client = server.accept(); 3. Create I/O streams for communicating to clients is = new DataInputStream( client.getInputStream() ); os = new DataOutputStream( client.getOutputStream() ); 4. Perform communication with client Receiive from client: String line = is.readLine(); Send to client: os.writeBytes("Hello\n"); 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 DataInputStream( client.getInputStream() ); os = new DataOutputStream( client.getOutputStream() ); 3. Perform communication with client Receiive from client: String line = is.readLine(); Send to client: os.writeBytes("Hello\n"); 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; DataOutputStream os; DataInputStream is; DataInputStream kbd; public client( String args[] ) { server = args[0]; port_id = Integer.valueOf(args[1]).intValue(); try { slink = new Socket( server, port_id ); os = new DataOutputStream( slink.getOutputStream() ); is = new DataInputStream( slink.getInputStream() ); kbd = new DataInputStream( System.in ); } 115 Echo Server Client.. (c) Rajkumar catch( UnknownHostException 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 <end to stop>: "); String line = kbd.readLine(); os.writeBytes( line+"\n" ); 116 Echo Server Client.. if( line.equals("end") ) (c) Rajkumar { os.close(); is.close(); slink.close(); break; } String line2 = is.readLine(); System.out.println("Output: "+line2); } 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 ) { ServerSocket server = null; DataOutputStream os = null; DataInputStream is = null; boolean shutdown = false; if( args.length < 1 ) { System.out.println( "Usage: java server port_num" ); System.exit( 1 ); } int PORT = Integer.valueOf(args[0]).intValue(); try { server = new ServerSocket( 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"); InetAddress cip = client.getInetAddress(); System.out.println( "Client IP Addr: "+cip.toString()); is = new DataInputStream( client.getInputStream() ); os = new DataOutputStream( client.getOutputStream() ); for(;;) { String line = is.readLine(); if( line == null ) break; 119 Echo Server ... (c) Rajkumar if( line.startsWith("end" ) ) { shutdown = true; break; } os.writeBytes(line.toUpperCase()); os.writeBytes("\n"); System.out.println(line); } is.close(); client.close(); } catch( UnknownHostException 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 Local state Global/ shared state PC Hard/Software Context Program Counter Running Thread Object 123 Single and Multithreaded Processes (c) Rajkumar Single-threaded Process Multiplethreaded Process Threads of Execution Single instruction stream Multiple instruction stream Common Address Space 124 OS: Multi-Processing, Multi-Threaded (c) Rajkumar Threaded Libraries, Multi-threaded I/O Application Application Application Application CPU CPU CPU Better Response Times in Multiple Application Environments CPU 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 Independent executables All threads are parts of a process hence communication easier and simpler. 126 Levels of Parallelism: Thread Granularity (c) Rajkumar Task i-l Task Control Data Multiple Issue func1 ( ) { .... .... } a ( 0 ) =.. b ( 0 ) =.. + Task i func2 ( ) { .... .... } a ( 1 )=.. b ( 1 )=.. x Task i+1 func3 ( ) { .... .... } 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 Concurrency Vs Parallelism Concurrency P1 P2 CPU P3 time Number of Simulatneous execution units > no of CPUs 128 Multithreading Multiprocessors (c) Rajkumar Concurrency Vs Parallelism CPU P1 CPU P2 CPU P3 time No of execution process = no of CPUs 129 Threads (c) Rajkumar Java has built in thread support for Multithreading Synchronization Thread Scheduling Inter-Thread Communication: currentThread start setPriority yield run getPriority sleep stop suspend resume Java Garbage Collector is a low-priority thread 130 Threading Mechanisms... (c) Rajkumar Create a class that extends the Thread class Create a class that implements the Runnable interface 131 1st method: Extending Thread class (c) Rajkumar 1st Method: Extending the Thread class class MyThread { public void { // thread } } Creating thread: MyThread thr1 = Start Execution: thr1.start(); extends Thread run() body of execution new MyThread(); 132 2nd method: Threads by implementing Runnable interface (c) Rajkumarclass ClassName implements Runnable { ..... public void run() { // thread body of execution } } Creating Object: ClassName myObject = new ClassName(); Creating Thread Object: Thread thr1 = new Thread( myObject ); Start Execution: thr1.start(); 133 Multi-Threaded (c) Rajkumar Thread and its subclasses run one thread per instance class MyThread extends Thread { public void run () { ...Start running } } Any Runnable object can wrap a thread around itself class Server implements Runnable { Thread t; Server () { t = new Thread(this); .} public void run () { ...Start running } } Thread control: Thread.start(), Thread.stop() 134 Manipulation of Current Thread // CurrentThreadDemo.java (c) Rajkumar class CurrentThreadDemo { public static void main(String arg[]) { Thread ct = Thread.currentThread(); ct.setName( "My Thread" ); System.out.println("Current Thread : "+ct); try { for(int i=5; i>0; i--) { System.out.println(" " + i); Thread.sleep(1000); } } catch(InterruptedException e) { System.out.println("Interrupted."); } } } Run: Current Thread : Thread[My Thread,5,main] 5 4 3 2 1 135 Creating new Thread... (c) Rajkumar // ThreadDemo.java class ThreadDemo implements Runnable { ThreadDemo() { Thread ct = Thread.currentThread(); System.out.println("Current Thread : "+ct); Thread t = new Thread(this,"Demo Thread"); t.start(); try { Thread.sleep(3000); } catch(InterruptedException 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(InterruptedException e) { System.out.println("Child interrupted."); System.out.println("Exiting child thread."); } public static void main(String args[]) { new ThreadDemo(); } } Run: Current Thread : Thread[main,5,main] 5 4 3 Exiting main thread. 2 1 Exiting child thread. } 137 Thread Priority... (c) Rajkumar // HiLoPri.java class Clicker implements Runnable { int click = 0; private Thread t; private boolean running = true; public Clicker(int p) { t = new Thread(this); t.setPriority(p); } public void run() { while(running) click++; } public void start() { t.start(); } public void stop() { running = false; } } 138 ...Thread Priority (c) Rajkumar class HiLoPri { public static void main(String args[]) { Thread.currentThread().setPriority(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); } } Run1: (on Solaris) 0 vs. 956228 Run2: (Window 95) 304300 vs. 4066666 139 Threads Need Synchronization (c) Rajkumar Server instances lock themselves at method-level class Buffer { // synchronize on buffer instance public synchronized void put (int i) ... public synchronized int get () . void safe () .} Client instance locks a server object before using it synchronized (array_to_sort) { ..... }wait(); // within synchronized methodnotify(); 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] Run3:Synchronized object in run(): synchronized(Target){ Target.call(msg); } The output is the same as Run2 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 Got: 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 ValueSet = false; synchronized int get() { try { if(!ValueSet) wait(); } catch(InterruptedException e) { } System.out.println("Got : "+n); ValueSet = false; notify(); return n; } 147 Queue (interthread communication)... (c) Rajkumar synchronized void put(int n) { try { if(ValueSet) wait(); } catch(InterruptedException e) { } this.n = n; System.out.println("Put : "+n); ValueSet = 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... // DeadLock.java (c) Rajkumar class A { synchronized void foo(B b) { String name = Thread.currentThread().getName(); 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.currentThread().getName(); 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 DeadLock implements Runnable { (c) Rajkumar A a = new A(); B b = new B(); DeadLock() { Thread.currentThread().setName("Main Thread"); new Thread(this).start(); a.foo(b); System.out.println("Back in the main thread."); } public void run() { Thread.currentThread().setName("Racing Thread"); b.bar(a); System.out.println("Back in the other thread"); } public static void main(String args[]) { new DeadLock(); } } 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 JavaOS OS Hardware Hardware Hardware Java on a Desktop OS Java on a Smaller OS Java on JavaOS Network Java on a Browser 156 Java Applications! (c) Rajkumar Java applications are now available Cost of manfg zero, cost of distribution zero, cost of marketing zero! Hot Java is lean - loads everything else from the net. Java itself is small - 40k to 225k New class of small machines will emerge Java on cellular phones, credit cards, washing machines, and everywhere ? 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 Sun (SPARC) ftp://java.sun.com Sun(x86) ftp://xm.com:/pub/ IBM(Aix, OS/2)ftp://ncc.hursley.ibm.com/javainfo DEC(Alpha OSF/1) http://www.gr.osf.org:8001/projects/web/java/ SGI http://liawww.epfl.ch/~simon/java/irixjdk.html HP http://www.gr.osf.org:8001/projects/web/java Linux http://www.blackdown.org AT & T http://www.gr.osf.org:8001/projects/web/java Windows 3.1 http://www.alphaworks.ibm.com 159 (c) Rajkumar Java Development Tools (Present and Planned) 160 Sun’s Java WorkShop (c) Rajkumar JDK: Compiler and runtime environment Class Libraries Documentation javadoc - Automated Documentation Takes comments and converts to HTML IDE: Visual Java, and integrated tools, JavaBeans Other Products and API: JavaHelp, Java Card, Java Blend, JavaOS, Java Mail, Java Management, Java Electronic Commerce Framework Java Enterprise API: Java Naming and Directory Interface, Java IDL, JDBC, RMI and Object Serialization 161 Symantec Cafe 1.0 (Released) (c) Rajkumar Full IDE for Windows 95/NT Graphic Development Tools Two Compilers Debugger Class Browser 162 Microsoft Jakarta (Planned) (c) Rajkumar Visual C++ type interface Will Support ActiveX/COM Internet Explorer 3.0 will have Just-In-Time Java compiler 163 Borland JBuilder (c) Rajkumar Visual RAD workbench for maximum productivity. Rapid Application Development (RAD) and Open Component Architecture patterned after Delphi. 100+ JavaBean components, with source code, for drag-and-drop applications. Beans Express--easiest way to create industrystandard Java-Bean components. DataExpress -- the fastest way to build business and database appplications. Borland DataGateway for Java connectivity to all major database servers. Multi-tier applications with integrated RMI and CORBA. Versions: Standard, Professional, & Client/Server 164 Challenges & Possible Directions (c) Rajkumar Performance AWT - need better GUI! Maintaining Interoperability Security - current restrictions limit what can be done Native Compilers Is Portability that Important? 165 Comments (c) Rajkumar Java is a fun and easy programming language Portability = Mediocrity? Java will become a programming language of choice, but may take on a final form that will surprise many! 166 JDBC (c) Rajkumar Java API for Relational Databases Being standardized by all major players 167 Javascript and Java (Preview) (c) Rajkumar Javascript can control Java applets Static data accessible as properties of applet var i = Bank.Account.count Public methods invocable on Java instances Provided those instances are accessible through the Applet Applet is accessible through document document.applet_Name_Attribute.do_Stuff() 168 Java for HPC! (c) Rajkumar Many efforts are in in progress for making java as a language for parallel programming. Java computing frameworks (HPC, numeric, data parallel) Java in distributed simulations and applications (e.g., real-world HPC, grand chalenge) Source to source translators (C, Fortran, C++ to Java) Web based computation environment in Java Java for HPC conference: http://www.cs.ucsb.edu/conferences/java98 Java for Science and Engineering computing: subscribe java-for-cse to majordomo@npac.syr.edu 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 handleEvent() and action()) Button, List, MenuItem, TextField: Interface: ActionListener Method: actionPerformed(ActionEvent event) Checkbox, CheckboxMenuItem, Choice: Interface: ItemListener Method: itemStateChanged(..) Dialog, Frame: Interface: WindowListener Method: windowClosing(), windowOpened(),... 170 How to Convert Programs to AWT 1.1... (c) Rajkumar 3. Change class declaration so that class implements public class MyClass extends SomeComponent implements ActionListener 4. Register action Listener newComponentObject.addActionListener(this); 5. Change event handling method: Old: public boolean action(Event e, Object arg) New: public void actionPerformed(ActionEvent 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.getSource() (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 Java as a Comprehensive Programming Solution Object Oriented Portable High Performance Geared for Distributed Environments Secure Highly suitable for Internet programming 173 Summary (c) Rajkumar Java is really very well poised Incredible leverage from the Web Will impact the C++ and Smalltalk markets Rate of progress is astonishingly high Development environments – CORBA linkages – Components – Fasten you seat-belts! 174 The End (c) Rajkumar Questions ? 175 Thank You ... (c) Rajkumar ? 176