Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 (c) Rajkumar Rajkumar School of Computing Queensland University of Technology Brisbane, Australia URL:

Similar presentations

Presentation on theme: "1 (c) Rajkumar Rajkumar School of Computing Queensland University of Technology Brisbane, Australia URL:"— Presentation transcript:

1 1 (c) Rajkumar Rajkumar School of Computing Queensland University of Technology Brisbane, Australia URL: Internet and Java Revolutions Impact on Education

2 2 (c) Rajkumar Motivation 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

3 3 (c) Rajkumar Agenda 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

4 4 (c) Rajkumar What is the Internet ? 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

5 5 (c) Rajkumar Internet Technology Evolution 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

6 6 (c) Rajkumar Installed base and Growth rate for telephone lines, mobile phones, and Internet hots Installed, Growth Rates (%) Income Group/ Phone MobileInternet Phone Mobile Internet RegionLines Phones HostsLines Phones Hosts Lower Income Lower- Middle Upper - Middle High Africa Americas Asia Europe Oceans World Source: ACM, Nov, 97 (phones, international telecommunication union, hosts, network Wizards

7 7 (c) Rajkumar Internet 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

8 8 (c) Rajkumar Internet Evolution File & mail TCP/IP Webpages Netscape On line connects to internet Secure payments Multi media Authoring Java VRML HTML Internet everywhere Internet appliances Price based services Live communities ? 10% of Market 20% of Market Total Market

9 9 (c) Rajkumar Early Internet Early Internet supported only . 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

10 10 (c) Rajkumar World Wide Web 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.

11 11 (c) Rajkumar Viewing WWW pages c View text, graphics, pictures, sounds, video c Web Browser c HyperText Markup Language (HTML) c Computer Independent c Operating System Independent

12 12 (c) Rajkumar Web Browsers c Netscape Navigator c Microsoft Internet Explorer c Omni Web c NCSA Mosaic c Lynx (text only)

13 13 (c) Rajkumar Internet Organization Truly world-wide Multiple communication media types

14 14 (c) Rajkumar Internet Organization Computers:

15 15 (c) Rajkumar WWW Organization Server Client

16 16 (c) Rajkumar Generating Web Pages 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

17 17 (c) Rajkumar HTML 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 for formatting documents. c HTML -The de-facto language for publishing on the Internet. Hypermedia- Hyper-links to Multimedia.

18 18 (c) Rajkumar Internet Tools 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

19 19 (c) Rajkumar How does the Web work ? 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

20 20 (c) Rajkumar HTTP Send the INFORMATION ABOUT C-DAC ACTS The information about C-DAC ACTS The client sends an HTTP message to a computer running a Web Server program and asks for a document The client sends an HTTP message to a computer running a Web Server program and asks for a document The web server sends the hypermedia HTML documents to the client. You end up seeing the document on your screen The web server sends the hypermedia HTML documents to the client. You end up seeing the document on your screen How does the Web Work

21 21 (c) Rajkumar HTML document Centre for Development of Advanced Computing... webmaster

22 22 (c) Rajkumar

23 23 (c) Rajkumar URLs 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 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

24 24 (c) Rajkumar CGI (Common Gateway Interface) 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

25 25 (c) Rajkumar Authoring tools and Filters 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- HoTMetaL, HTML Assistant - Shareware

26 26 (c) Rajkumar Preconfigured v/s Integrated Internet Products c Integrated Internet Products- From multiple vendors c Preconfigured Systems- Web Server and a Client ready to use c Suns Netra Internet Server c SGIs WebFORCE Indy and WebFORCE Challenge S c Apples Internet Server Solution c DECs Internet AlphaServer c Integraphs Web Server 10

27 27 (c) Rajkumar Future Directions 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

28 28 (c) Rajkumar Internet in Education * Institution Web Site: - about the university - faculties and department details - research facilities, area, and groups - faculty members details with their publications * Admission Process: - course announcement, - making available details of course - admission applications, - announcement of selection * University Facilities: - computing facilities, accommodation, recreation, etc.. * Teaching Process: - Use of WWW in the Curriculum - Homework and Quizzes - Virtual Classroom - Virtual Lectures - Student Interaction - Q & A * Creating Your Own Page HTML Tags (Title, Body, images, etc.) Basic HTML code & file structure Links and Anchors; Linking it elsewhere: Moving around the WWW Making it all Look Pretty * Use components such as: - WWW Forms, Frames, Sound, Video, - Animation, WWW Plugins * Make web attractive through: Adding web applications: - customer enquiry - Free applications

29 29 (c) Rajkumar Internet as a delivery Vehicle

30 30 (c) Rajkumar Interesting URLs c ( The WhiteHouse) c (Everything about the WWW) c (Software on Sun) c (India Net Foundation Services) c telnet:// (Free Public Access Unix System) c (Search engines, Add URL) c (World Alumni on the net) c (Free ) c (Free Website,2MB space) c (Offers virtual web servvices for compinies to host their website). c (Kannada news paper on web)

31 31 (c) Rajkumar Class Sites To Visit c c c c c c c

32 32 (c) Rajkumar API Bottleneck Network LAN PC SUN MAC Server

33 33 (c) Rajkumar The OS - Platform lock Application OS Applications tied to OS OS tied to Platform

34 34 (c) Rajkumar Application OS The Web * Seeded by HTML from CERN * Revolutionised by MOSAIC * Standardised, universal interface to data * Graphical * Broadcast capability - publish once, reach millions

35 35 (c) Rajkumar Making life easier! 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

36 36 (c) Rajkumar Java and Java Computing

37 37 (c) Rajkumar Java - An Introduction 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

38 38 (c) Rajkumar Java From 10,000 Ft. c According to the world, Java is... c According to Sun, Java is... c On closer inspection, Java is

39 39 (c) Rajkumar According to the World, Java Is... 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

40 40 (c) Rajkumar According to Sun, Java is... 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!

41 41 (c) Rajkumar On Closer Inspection, Java is... c Simple c Pure c Portable c Surprisingly effective

42 42 (c) Rajkumar As a whole, Java is a Comprehensive Programming Solution c Object Oriented c Portable c High Performance c Geared for Distributed Environments c Secure

43 43 (c) Rajkumar Java as Object Oriented 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

44 44 (c) Rajkumar Java as Portable 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

45 45 (c) Rajkumar Total Platform Independence JAVA COMPILER JAVA BYTE CODE JAVA INTERPRETER Windows 95MacintoshSolarisWindows NT (translator) (same for all platforms) (one for each different system)

46 46 (c) Rajkumar Java Write Once, Run Anywhere

47 47 (c) Rajkumar Architecture Neutral & Portable c Java 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

48 48 (c) Rajkumar Java as High Performance c JVM uses lean and mean bytecodes c Small binary class filtes c Just-in-time Compilers c Multithreading c Native Methods

49 49 (c) Rajkumar Java in the World of Distributed Computing c Class Loader c Lightweight Binary Class Files c Multithreading c Dynamic c Good communication constructs c Secure

50 50 (c) Rajkumar Java as Secure c Language designed as safe c Strict compiler c Dynamic Runtime Loading (Verifier) c Runtime Security Manager

51 51 (c) Rajkumar Object Oriented Languages -a Comparison FeatureC++ Objective C AdaJava Encapsulation Yes Inheritance Yes NoYes Multiple Inherit. Yes No Polymorphism Yes Binding (Early/Late) Both EarlyLate Concurrency Poor DifficultYes Garbage Collection NoYesNoYes Genericity YesNoYesNo Class Libraries Yes LimitedYes

52 52 (c) Rajkumar Java better than C++ ? 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 ?

53 53 (c) Rajkumar Basic Data Types c Types boolean either true of false char16 bit Unicode 1.1 byte8-bit integer (signed) short16-bit integer (signed) int32-bit integer (signed) long64-bit integer (singed) float32-bit floating point (IEEE ) double64-bit floating point (IEEE ) c String (class for manipulating strings) c Java uses Unicode to represent characters internally

54 54 (c) Rajkumar Java Integrates Power of Compiled Languages and Flexibility of Interpreted Languages

55 55 (c) Rajkumar Two Types of JavaApplications c Different ways to write/run a Java codes are: main 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 c Application -Java interpreter c Applets- Java enabled web browser (Linked to HTML via tag. in html file)

56 56 (c) Rajkumar Java Bytecodes move locally or through network Java Source (.java) Java Compiler Java Bytecode (.class ) Java Interpreter Just in Time Compiler Runtime System Class Loader Bytecode Verifier Java Class Libraries Operating System Hardware Java Virtual machine Runtime Environment Compile-time Environment Java Environment/ Life Cycle of Java Code

57 57 (c) Rajkumar Java Development Kit 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

58 58 (c) Rajkumar Hello Internet // Hello Internet program class HelloInternet { public static void main(String args[]) { System.out.println(Hello Internet); }

59 59 (c) Rajkumar Program Processing c Compilation # javac results in HelloInternet.class c Execution # java HelloInternet Hello Internet #

60 60 (c) Rajkumar Simple Java Applet // A sample applet import java.applet.Applet; public class HelloWorld extends Applet { public void paint(Graphics g) { g.drawString(Hello World !,25,25); }

61 61 (c) Rajkumar Calling an Applet Hello Worls Applet

62 62 (c) Rajkumar Execution of Applets Hello Hello Java 4 APPLET Development AT CDAC-India The Internet hello.class AT C-DACS WEB SERVER Create Applet tag in HTML document Accessing from CRAY Corp. (USA) The browser creates a new window and a new thread and then runs the code

63 63 (c) Rajkumar Web Perspective c How did Web interactions work? c How do they work with Java? c Distributed Java objects and the Web

64 64 (c) Rajkumar Classical Web Perspective

65 65 (c) Rajkumar Java Web Perspective

66 66 (c) Rajkumar Significance of downloading Applets 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 one.html

67 67 (c) Rajkumar Power of Java and the Web ] Deliver applications, not just information ] Eliminate porting ] Eliminate end-user installation ] Slash software distribution costs ] Reach millions of customers - instantly

68 68 (c) Rajkumar Lifecycle of Java Code

69 69 (c) Rajkumar Bytecode Verifier 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

70 70 (c) Rajkumar Class Loader c Unique Namespace for each origin c Local namespace classes are called built-ins c Prevents class spoofing

71 71 (c) Rajkumar Security Manager c Prevents unauthorized disk read/writes c Restricts network access c Other access restrictions (native methods) c Implementation is browser dependent

72 72 (c) Rajkumar General Language Features 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

73 73 (c) Rajkumar Removed From C++ 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....

74 74 (c) Rajkumar Added or Improved over C++ c Interfaces: type Vs. class c Garbage collection c Exceptions (More powerful than C++) c Strings c Instanceof c Package c Multi-threads

75 75 (c) Rajkumar Declaring Classes 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… }

76 76 (c) Rajkumar Inheritance in Java 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… }

77 77 (c) Rajkumar Creating and Using Objects 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...

78 78 (c) Rajkumar Class Methods and Variables n int pi = Math.PI; n int theMax = Math.max(x,6); Definitions: n public final static double PI = ; n public static int max(int a, int b);

79 79 (c) Rajkumar Access Rules n public n private n protected n package (Default - no keyword)

80 80 (c) Rajkumar Using Threads n Define a Thread class public MyThread extends Thread { public void run() { // Override default method while (true) { // do custom code… …. n Using the thread MyThread t = new MyThread(); t.start(); // Start the thread... Detailed discussion on Threads, later

81 81 (c) Rajkumar Strings c The language defines strings as objects c doSomething("abc" + "cde"); c doSomething(String s) {..} c String abc = new String(Hello); c System.out.println(abc);

82 82 (c) Rajkumar Exceptions 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 TypeC; c Exceptions must be caught or declared c Errors do not have to be caught c Surprisingly effective at producing robust code

83 83 (c) Rajkumar Exception Handling 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; }

84 84 (c) Rajkumar More about Exceptions 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

85 85 (c) Rajkumar Interfaces 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{ }

86 86 (c) Rajkumar Interface: Type and Sub-Type 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 updateItem (int position); }

87 87 (c) Rajkumar Class Implements Interface c Complete type/class separation possible class Order implements Observer { public void update (Object o) { // do stuff toupdate } // data and other implementation } c Any object can support multiple interfaces c Client can see its types separately or conjoined c A powerful approach to design, roles, distribution, design patterns c Takes a little bit of getting used to

88 88 (c) Rajkumar Implementation Inheritance c Single inheritance of implementation class X extends W implements E, F { // Stuff in class X }

89 89 (c) Rajkumar Interfaces and Classes!

90 90 (c) Rajkumar Uses of Interfaces 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

91 91 (c) Rajkumar Garbage Collected 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

92 92 (c) Rajkumar instanceof and casts 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

93 93 (c) Rajkumar Packages 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

94 94 (c) Rajkumar Packages and Utilities 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)

95 95 (c) Rajkumar Rich Object Environment 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

96 96 (c) Rajkumar Main Packages n java.lang n java.util n n java.awt n java.awt.image n java.applet n

97 97 (c) Rajkumar java.lang Core Classes Base Class: Object c String String s = This is number + 6; c Math Math.sqrt(4.0); c System System.out.println(An error occurred); System.exit(1);

98 98 (c) Rajkumar java.lang Type Wrappers Literals: int, double, boolean, char … Literals wrapped in Classes: Integer, Double, Boolean, Character c Literals used for high performance c Examples: int x = Integer.parseInt(6); Integer I = new Integer(999); double dbl = I.doubleValue();//Returns

99 99 (c) Rajkumar - Filtering input streams 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()); }

100 100 (c) Rajkumar GUI Programming in Java (AWT and Event Handling)

101 101 (c) Rajkumar AWT - Abstract Windowing Toolkit 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

102 102 (c) Rajkumar AWT - Abstract Window Toolkit 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 BorderLayout, GridLayout, FlowLayout, null layoit

103 103 (c) Rajkumar Adding Components via Layouts 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);

104 104 (c) Rajkumar Adding Components via Layouts

105 105 (c) Rajkumar Popup Menu and Event Handling... // 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" );

106 106 (c) Rajkumar Popup Menu and Event Handling... 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 ), e.getX(), e.getY() ); }

107 107 (c) Rajkumar 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(); }

108 108 (c) Rajkumar Custom Drawing // 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(; g.drawRect(x,y,width,height); g.setColor(Color.yellow); g.fillRect(x + 1,y + 1,width - 2,height - 2); }

109 109 (c) Rajkumar java.applet c Applet c Class representation of applet c init() method called when first loaded c start() when applets Web page becomes active c stop() when user leaves Web Page c Actually derived from AWT Panel c AppletContext c Hooks into Browser environment c Can be used to link to another Web page

110 110 (c) Rajkumar A sample Applet // 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"); }

111 111 (c) Rajkumar Network/Socket Programming in Java

112 112 (c) Rajkumar c Used to manage: c URL streams c Client/server sockets c Datagrams

113 113 (c) Rajkumar Server side Socket Operations 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. }

114 114 (c) Rajkumar Client side Socket Operations 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();

115 115 (c) Rajkumar Echo Server Client.. // client interface to server import*; import*; 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( ); }

116 116 (c) Rajkumar Echo Server Client.. 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 : "); String line = kbd.readLine(); os.writeBytes( line+"\n" );

117 117 (c) Rajkumar Echo Server Client.. if( line.equals("end") ) { 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(); }

118 118 (c) Rajkumar Echo Server... // echo server import*; import*; 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 ); }

119 119 (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; Echo Server...

120 120 (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]); } Echo Server...

121 121 (c) Rajkumar System.out.println( "Server Down" ); try { server.close(); } catch(IOException e) {} } Echo Server

122 122 (c) Rajkumar Multithreading in Java (A built-in feature in Java)

123 123 (c) Rajkumar What are Threads? Ø Thread is a piece of code that can execute in concurrence with other threads. Ø It is a schedule entity on a processor 0 Local state 0 Global/ shared state 0 PC 0 Hard/Software Context Registers Hardware Context Status Word Program Counter Running Thread Object

124 124 (c) Rajkumar Single and Multithreaded Processes Single-threaded Process Single instruction stream Multiple instruction stream Multiplethreaded Process Threads of Execution Common Address Space

125 125 (c) Rajkumar OS: Multi-Processing, Multi-Threaded Application CPU Better Response Times in Multiple Application Environments Higher Throughput for Parallelizeable Applications CPU Threaded Libraries, Multi-threaded I/O

126 126 (c) Rajkumar Threaded Process Model THREAD STACK THREAD DATA THREAD TEXT SHARED MEMORY Threads within a process l Independent executables l All threads are parts of a process hence communication easier and simpler.

127 127 (c) Rajkumar 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 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 Levels of Parallelism: Thread Granularity Levels of Parallelism: Thread Granularity Task i-l Task i Task i+1 func1 ( ) {.... } func1 ( ) {.... } func2 ( ) {.... } func2 ( ) {.... } func3 ( ) {.... } func3 ( ) {.... } a ( 0 ) =.. b ( 0 ) =.. a ( 0 ) =.. b ( 0 ) =.. a ( 1 )=.. b ( 1 )=.. a ( 1 )=.. b ( 1 )=.. a ( 2 )=.. b ( 2 )=.. a ( 2 )=.. b ( 2 )= x x Load m Task m Control m Data m Multiple Issue m Task m Control m Data m Multiple Issue

128 128 (c) Rajkumar Multithreading - Uniprocessors c Concurrency Vs Parallelism K Concurrency Number of Simulatneous execution units > no of CPUs P1 P2 P3 time CPU

129 129 (c) Rajkumar Multithreading - Multiprocessors Concurrency Vs Parallelism P1 P2 P3 time No of execution process = no of CPUs CPU

130 130 (c) Rajkumar Threads c Java has built in thread support for Multithreading c Synchronization c Thread Scheduling c Inter-Thread Communication: currentThreadstartsetPriority yieldrungetPriority sleepstopsuspend resume c Java Garbage Collector is a low-priority thread

131 131 (c) Rajkumar Threading Mechanisms... c Create a class that extends the Thread class c Create a class that implements the Runnable interface

132 132 (c) Rajkumar 1st method: Extending Thread class c 1st Method: Extending the Thread class class MyThread extends Thread { public void run() { // thread body of execution } Creating thread: MyThread thr1 = new MyThread(); Start Execution: thr1.start();

133 133 (c) Rajkumar 2nd method: Threads by implementing Runnable interface class ClassName implements Runnable {..... public void run() { // thread body of execution } c Creating Object: ClassName myObject = new ClassName(); c Creating Thread Object: Thread thr1 = new Thread( myObject ); c Start Execution: thr1.start();

134 134 (c) Rajkumar Multi-Threaded c Thread and its subclasses run one thread per instance c class MyThread 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()

135 135 (c) Rajkumar Manipulation of Current Thread // 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]

136 136 (c) Rajkumar Creating new Thread... // 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."); }

137 137 (c) Rajkumar...Creating new Thread. 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] Exiting main thread. 2 1 Exiting child thread.

138 138 (c) Rajkumar Thread Priority... // 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; } }

139 139 (c) Rajkumar...Thread Priority 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( + " vs. " +; } Run1: (on Solaris) 0 vs Run2: (Window 95) vs

140 140 (c) Rajkumar Threads Need Synchronization 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

141 141 (c) Rajkumar Monitor model (for Syncronisation) Method 1 Method 2 Block 1 Key Threads Monitor (synchronised) solves race-condition problem

142 142 (c) Rajkumar Threads Synchronisation... // 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(); }

143 143 (c) Rajkumar...Threads Synchronisation. public void run() {; } 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){; } The output is the same as Run2

144 144 (c) Rajkumar Queue (no inter-threaded communication)... // produce and consumer 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(); }

145 145 (c) Rajkumar Queue (no inter-threaded communication)... 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(); }

146 146 (c) Rajkumar...Queue (no inter-threaded communication). class 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

147 147 (c) Rajkumar Queue (interthread communication)... // 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; }

148 148 (c) Rajkumar Queue (interthread communication)... 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(); }

149 149 (c) Rajkumar Queue (interthread communication)... 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(); }

150 150 (c) Rajkumar...Queue (no interthread communication). 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

151 151 (c) Rajkumar Deadlock... // class A { synchronized void foo(B b) { String name = Thread.currentThread().getName(); System.out.println(name + " entered"); 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"); }

152 152 (c) Rajkumar Deadlock... class B { synchronized void bar(A a) { String name = Thread.currentThread().getName(); System.out.println(name + " entered"); 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"); }

153 153 (c) Rajkumar...Deadlock. class DeadLock implements Runnable { A a = new A(); B b = new B(); DeadLock() { Thread.currentThread().setName("Main Thread"); new Thread(this).start();; System.out.println("Back in the main thread."); } public void run() { Thread.currentThread().setName("Racing Thread");; System.out.println("Back in the other thread"); } public static void main(String args[]) { new DeadLock(); } Run: Main Thread entered Racing Thread entered Main Thread trying to call B.last() Racing Thread trying to call A.last() ^C

154 154 (c) Rajkumar Threads in Action... Cooperative threads - File Copy reader() { lock(buff[i]); read(src,buff[i]); unlock(buff[i]); } reader() { lock(buff[i]); read(src,buff[i]); unlock(buff[i]); } writer() { lock(buff[i]); write(src,buff[i]); unlock(buff[i]); } writer() { lock(buff[i]); write(src,buff[i]); unlock(buff[i]); } buff[0] buff[1] Cooperative Parallel Synchronized Threads

155 155 (c) Rajkumar Server Threads Message Passing Facility Server Process Client Process User Mode Kernel Mode Threads in Action... Multithreaded Server

156 156 (c) Rajkumar A Look Inside the Java Platform Java Virtual Machine Porting Interface Applets and Applications Java Base API Java Base Classes Java Standard Extension API Java Standard Extension Classes Adapter OS Hardware Adapter OS Hardware JavaOS Hardware The Java Base Platform (in black) Adapter Browser OS Hardware Network Java on a Browser Java on a Desktop OS Java on a Smaller OS Java on JavaOS

157 157 (c) Rajkumar Java Applications! c 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 - 40k to 225k c New class of small machines will emerge c Java on cellular phones, credit cards, washing machines, and everywhere ?

158 158 (c) Rajkumar Internet Universal Interface Web Servers with JAVA applications Clients running any OS on any platform

159 159 (c) Rajkumar Java on my platform ? c Sun (SPARC) c Sun(x86) c IBM(Aix, OS/2) c DEC(Alpha OSF/1) c SGI jdk.html c HP c Linux c AT & T c Windows 3.1

160 160 (c) Rajkumar Java Development Tools (Present and Planned)

161 161 (c) Rajkumar Suns Java WorkShop 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, JavaBeans c Other Products and API: JavaHelp, Java Card, Java Blend, JavaOS, Java Mail, Java Management, Java Electronic Commerce Framework c Java Enterprise API: Java Naming and Directory Interface, Java IDL, JDBC, RMI and Object Serialization

162 162 (c) Rajkumar Symantec Cafe 1.0 (Released) c Full IDE for Windows 95/NT c Graphic Development Tools c Two Compilers c Debugger c Class Browser

163 163 (c) Rajkumar Microsoft Jakarta (Planned) c Visual C++ type interface c Will Support ActiveX/COM c Internet Explorer 3.0 will have Just-In-Time Java compiler

164 164 (c) Rajkumar Borland JBuilder c Visual RAD workbench for maximum productivity. c Rapid Application Development (RAD) and Open Component Architecture patterned after Delphi. c 100+ JavaBean components, with source code, for drag-and-drop applications. c Beans Express--easiest way to create industry- standard Java-Bean components. c DataExpress -- the fastest way to build business and database appplications. c Borland DataGateway for Java connectivity to all major database servers. c Multi-tier applications with integrated RMI and CORBA. c Versions: Standard, Professional, & Client/Server

165 165 (c) Rajkumar Challenges & Possible Directions 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?

166 166 (c) Rajkumar Comments 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!

167 167 (c) Rajkumar JDBC c Java API for Relational Databases c Being standardized by all major players

168 168 (c) Rajkumar Javascript and Java (Preview) c Javascript can control Java applets c Static data accessible as properties of applet c var i = Bank.Account.count 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()

169 169 (c) Rajkumar Java for HPC! 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: c Java for Science and Engineering computing: subscribe java-for-cse to c

170 170 (c) Rajkumar How to Convert Programs to AWT 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(),...

171 171 (c) Rajkumar How to Convert Programs to AWT 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)

172 172 (c) Rajkumar How to Convert Programs to AWT Delete the event handling code in this way (a) Delete all return statements (b) Change 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

173 173 (c) Rajkumar Just to Summarize 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

174 174 (c) Rajkumar Summary 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!

175 175 (c) Rajkumar The End Questions ?

176 176 (c) Rajkumar Thank You... ?

Download ppt "1 (c) Rajkumar Rajkumar School of Computing Queensland University of Technology Brisbane, Australia URL:"

Similar presentations

Ads by Google