The JAVA API.

Slides:



Advertisements
Similar presentations
Multiplexing/Demux. CPSC Transport Layer 3-2 Multiplexing/demultiplexing application transport network link physical P1 application transport network.
Advertisements

1 Frameworks. 2 Framework Set of cooperating classes/interfaces –Structure essential mechanisms of a problem domain –Programmer can extend framework classes,
Prepared By E. Musa Alyaman1 URLs, InetAddresses, and URLConnections Chapter 9.
1 Java Networking – Part I CS , Spring 2008/9.
Internetworking (Contd) Chapter 4. Figure 3.26 ATM protocol layers.
1 Overview r Socket programming with TCP r Socket programming with UDP r Building a Web server.
1 Recitation 11. Applet Applets. An applet is a Java program that is started by a browser (e.g. netscape or internet explorer) when an html file has a.
CIS – Spring Instructors: Geoffrey Fox, Bryan Carpenter Computational Science and.
2: Application Layer1 Socket Programming. 2: Application Layer2 Socket-programming using TCP Socket: a door between application process and end- end-transport.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 25 Networking.
Web Proxy Server. Proxy Server Introduction Returns status and error messages. Handles http CGI requests. –For more information about CGI please refer.
UMBC CMSC 331 Java The JAVA API. UMBC CMSC 331 Java 2 A Tour of the Java API An API User’s Guide, in HTML, is bundled with Java Much of the “learning.
Io package as Java’s basic I/O system continue’d.
Introduction to JAVA CMSC 331 Spring Introduction Present the syntax of Java Introduce the Java API Demonstrate how to build –stand-alone Java programs.
2: Application Layer 1 Socket Programming TCP and UDP.
Applets  The Applet Class  The HTML Tag F Passing Parameters to Applets.
Building an ftp client and server using sockets we now know enough to build a sophisticated client/server application!  ftp  telnet  smtp  http.
CS4273: Distributed System Technologies and Programming I Lecture 5: Java Socket Programming.
2: Application Layer1 Socket programming Socket API r introduced in BSD4.1 UNIX, 1981 r explicitly created, used, released by apps r client/server paradigm.
Internet Software Development Applets Paul J Krause.
Java Programming, Second Edition Chapter Seventeen Multithreading and Animation.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
CS 3131 Introduction to Programming in Java Rich Maclin Computer Science Department.
Object Oriented Programming in Java Lecture 16. Networking in Java Concepts Technicalities in java.
CSC 205 – Java Programming II Applet. Types of Java Programs Applets Applications Console applications Graphics applications Applications are stand-alone.
Lecture 9 Network programming. Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet.
Li Tak Sing COMPS311F. Case study: consumers and producers A fixed size buffer which can hold at most certain integers. A number of producers which generate.
1 Chapter 28 Networking. 2 Objectives F To comprehend socket-based communication in Java (§28.2). F To understand client/server computing (§28.2). F To.
From Coulouris, Dollimore, Kindberg and Blair Distributed Systems: Concepts and Design Edition 5, © Addison-Wesley 2012 Slides for Chapter 4: Interprocess.
Slides for Chapter 4: Interprocess Communication From Coulouris, Dollimore and Kindberg Distributed Systems: Concepts and Design Edition 4, © Addison-Wesley.
CS 4244: Internet Programming User Interface Programming in Java 1.0.
Intro to Applets. Applet Applets run within the Web browser environment Applets bring dynamic interaction and live animation to an otherwise static HTML.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Concurrent Computing CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
UMBC CMSC 331 Java The JAVA API. UMBC CMSC 331 Java 2 A Tour of the Java API An API User’s Guide, in HTML, is bundled with Java Much of the “learning.
Java Programming II Java Network (I) Java Programming II.
1 Lecture 9: Network programming. 2 Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on.
1 CSCD 330 Network Programming Fall 2013 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright Lecture 8a Application.
Java Applets Adding Animation. Import Files You still need to include the same files: –import java.applet.*; –import java.awt.*;
Introduction to JAVA CMSC 331 Fall Introduction Present the syntax of Java Introduce the Java API Demonstrate how to build –stand-alone Java programs.
Network Programming. These days almost all devices.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Objects and Classes. F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive data type and object type.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 33 Networking.
Network Programming Communication between processes Many approaches:
Socket Programming Ameera Almasoud
Multithreaded applets
Echo Networking COMP
Threads in Java Two ways to start a thread
Chapter 13: Multithreading
Multi Threading.
Network Programming Introduction
Distributed Computing, M. L. Liu
Distributed Computing, M. L. Liu
Clients and Servers 19-Nov-18.
Programming in Java Text Books :
Socket programming - Java
Clients and Servers 1-Dec-18.
CSCD 330 Network Programming
Java Threads (Outline)
Java Threads (Outline)
The JAVA API.
NETWORK PROGRAMMING CNET 441
Chapter 15 Multithreading
Threads in Java James Brucker.
Socket Programming 2: Application Layer.
Multiplexing/Demux.
Clients and Servers 19-Jul-19.
Clients and Servers 13-Sep-19.
Review Communication via paired sockets, one local and one remote
Presentation transcript:

The JAVA API

A Tour of the Java API An API User’s Guide, in HTML, is bundled with Java Much of the “learning curve” is in the API Let’s look at some packages

See http://docs.oracle.com/javase/8/docs/api/ for the current APIs The Java API java.applet Applet class java.awt Windows, buttons, mouse, etc. java.awt.image image processing java.awt.peer GUI toolkit java.io System.out.print java.lang length method for arrays; exceptions java.net sockets java.util System.getProperty See http://docs.oracle.com/javase/8/docs/api/ for the current APIs

The package java.lang The class Object The class Class The root class in Java Example methods: clone(), equals(), toString() Subclasses may override these methods The class Class Example methods: getName(), getSuperClass()

Observing an object’s class void printClassName (Object obj) { System.out.println("The class of " + obj + " is " + obj.getClass().getName()); }

Strings in Java Strings are nt a primitive data type, but represented as objects. Many methods defined in class java.lang: Several constructors Lots of methods: concat(), equals(), indexOf(), length() strings are concatenated with + Strings are constants (immutable) You can concatenate two strings to produce a new, longer string, using the + operator, but you cannot add, delete, insert into, or delete from any particular string.

StringBuffers in Java Several methods defined in class java.lang: Constructors can specify length or initial value append(), insertf(), length(), toString()

Java.lang.system Printstreams Inputstreams System.out.err(“Error message”); Inputstreams System.in.read(inputCharacter) System.in.read(inputBuffer, 0, maxChars)

The Cloneable Interface A class implements the cloneable interface by overriding the Object method clone() For example, we could add a clone() method to the FIFO class, if we wanted to be able to make copies of queues.

The class java.util Interface to host OS Some basic functions and data structures BitSet, Dictionary (the superclass of Hashtable), Stack, Vector Random number generation

System Properties System properties are like UNIX environment variables, but platform independent The API class java.util has methods for accessing the system properties

// determine environment variables import java.util.*; class envSnoop { public static void main ( String args[] ) { Properties p; String s; p = System.getProperties(); p.list(System.out); s = System.getProperty("user.name"); System.out.println("user.name="+s); s = System.getProperty("user.home"); System.out.println("user.home="+s); }

Java GUI The awt class allows you to create frames buttons menus and menubars checkboxes text areas scrolling lists

Java.net Defines several useful objects: URLs Internet Addresses Sockets Datagrams packets sockets

Manipulating URLs A Web server can provide lots of information about a file being sent back in response to an HTTP request. A URL can be read into a string, using the getContent() or opened as a DataInputStream, and read using readLine()

import java.net.*; import java.io.*; import java.util.*; public class GetURLInfo { // Create a URL from the specified address, open a connection // to it, and then display information about the URL. public static void main(String[] args) throws MalformedURLException, IOException { URL url = new URL(args[0]); URLConnection connection = url.openConnection(); printinfo(connection); }

public static void printinfo(URLConnection u) throws IOException { // Display the URL address, and information about it. System.out.println(u.getURL().toExternalForm() + ":"); System.out.println(" Content Type: " + u.getContentType()); System.out.println(" Content Length: " + u.getContentLength()); System.out.println(" Last Modified: " + new Date(u.getLastModified())); System.out.println(" Expiration: " + u.getExpiration()); System.out.println(" Content Encoding: " + u.getContentEncoding()); // Read and print out the first five lines of the URL. System.out.println("First five lines:"); DataInputStream in = new DataInputStream(u.getInputStream()); for(int i = 0; i < 5; i++) { String line = in.readLine(); if (line == null) break; System.out.println(" " + line); }

UDP Examples UDP - Unreliable datagram packet Examples from Flanagan Send a UDP packet Receive a UDP packet

// This example is from the book _Java in a Nutshell_ by // David Flanagan. // Written by David Flanagan. // Copyright (c) 1996 O'Reilly & Associates. // You may study, use, modify, and distribute this example for // any purpose. This example is provided WITHOUT WARRANTY // either expressed or implied. import java.io.*; import java.net.*; // This class sends the specified text as a datagram to // port 6010 of the specified host. public class UDPSend { static final int port = 6010; public static void main(String args[]) throws Exception { if (args.length != 2) { System.out.println( "Usage: java UDPSend <hostname> <message>"); System.exit(0); }

// Get the internet address of the specified host InetAddress address = InetAddress.getByName(args[0]); // Convert the message to an array of bytes int msglen = args[1].length(); byte[] message = new byte[msglen]; args[1].getBytes(0, msglen, message, 0); // Initilize the packet with data and address DatagramPacket packet = new DatagramPacket(message, msglen, address, port); // Create a socket, and send the packet through it. DatagramSocket socket = new DatagramSocket(); socket.send(packet); }

import java.io.*; import java.net.*; // This program waits to receive datagrams sent to port 6010. // When it receives one, it displays the sending host and port, // and prints the contents of the datagram as a string. public class UDPReceive { static final int port = 6010; public static void main(String args[]) throws Exception { byte[] buffer = new byte[1024]; String s; // Create a packet with an empty buffer to receive data DatagramPacket packet = new DatagramPacket(buffer, buffer.length); // Create a socket to listen on the port. DatagramSocket socket = new DatagramSocket(port);

for(;;) { // Wait to receive a datagram socket.receive(packet); // Convert the contents to a string s = new String(buffer, 0, 0, packet.getLength()); // And display them System.out.println("UDPReceive: received from " + packet.getAddress().getHostName() + ":" + packet.getPort() + ": " + s); } // close for } // close main } // close class UDPReceive

Using Threads Thread objects are the basis for multi-threaded programming. Multi-threaded programming allows a single program to conduct concurrently running threads that perform different tasks. Defined in java.lang.Thread

The Runnable Interface A class that implements this interface can provide the “body” of a thread The run() method needs to be specified

Using a Single Thread The simpleThread class implements the Runnable interface Implements run() method for Runnable interface Implements init(), start() and stop(), extending Applet class Can’t just extend Thread class, since Thread.stop() is final and can’t be overriden (why?)

// Simple Thread Example, based on "Neon Sign" public class OneThread extends java.applet.Applet implements Runnable { Thread kicker; public void init() { kicker = null; } public void start() { if(kicker == null) { // If no thread is started yet kicker=new Thread(this); // then create one kicker.start(); // and start it } public void stop() { kicker.stop(); kicker = null; }

public void run() { long sleepTime; System.out.println("Hello!"); sleepTime = 5000; while(true) { // Loop forever // The sleep method below might be interrupted // and cause an exception, so catch it. try { // Wait for some period of time Thread.sleep( sleepTime ); sleepTime = (sleepTime == 3000 ? 4000 : 3000 ); } catch (Exception e){ return; } System.out.println("Hello again after "+sleepTime+ " milliseconds"); }

Neon Sign Example Start a thread Load two GIF images Repeat forever Display first image Sleep a random period of time Display the other image

// Blinking Neon Light by Mattias Flodin import java.awt.*; public class BlinkItem extends java.applet.Applet implements Runnable { Image imPic[]; // Array that holds the two images int iPicIndex=0; // Keeps track of which image is displayed Thread kicker; public void init() { // *Always* resize, in case the HTML author forgot to // include WIDTH and HEIGHT tags resize(512,243); } public void Paint(Graphics g) { update(g); } // Using the update method will get rid of some flickering public void update(Graphics g) { // Display an error message if something // unexpected has happened to the images if(imPic[iPicIndex]==null) g.drawString("Error when loading picture", 0, 172); // Draw the current image g.drawImage(imPic[iPicIndex],0,0, this);

public void start() { if(kicker == null) { // If no thread is started yet kicker=new Thread(this); // then create one kicker.start(); // and start it } public void stop() { kicker=null; } public void run() { imPic=new Image[2]; // Dimension the image array // Load the two images in our 'animation' imPic[0]=getImage(getCodeBase(), "images/Homepage1.gif"); imPic[1]=getImage(getCodeBase(), "images/Homepage2.gif"); for(;;) { // Loop forever repaint(); // Redraw the window iPicIndex=iPicIndex==0 ? 1 : 0; // Switch image // The sleep method below might be interrupted // and cause an InterruptedException, so we'll // have to catch it. try { // Wait for a random amount of time Thread.sleep( (int) (Math.random()*500)); } catch (InterruptedException e){}

Multiple Threads An applet that creates a pool of simple threads Each thread has an ID number, and may handle different tasks Note separation of applet and thread classes

Multiple Threaded Example public class ThreadExample extends java.applet.Applet { public void init() { simpleThread[] threadPool = new simpleThread[2]; threadPool[0] = new simpleThread(1); threadPool[1] = new simpleThread(2); }

public class simpleThread implements Runnable { Thread thisThread; int thisThreadID; public simpleThread (int i) { thisThreadID = i; this.start(); } public void start() { if(thisThread == null) { // If thread isn’t started thisThread = new Thread(this); // create one thisThread.start(); // and start it } public void stop() { thisThread.stop(); thisThread = null; }

public void run() { long sleepTime; System.out.println("Hello from simpleThread "+ thisThreadID); while(true) { // The sleep method below might be interrupted // and cause an exception, so catch it. try { // Wait for a random amount of time sleepTime = (long) ( Math.random()*4 ); Thread.sleep( sleepTime*1000 ); } catch (Exception e) { return; } System.out.println("Hello again from simpleThread "+ thisThreadID+" after "+sleepTime+" seconds");

Other Ideas Patterns as an addition to the StringBuffer class (ala Perl) One could easily write a better browser intelligent pre-fetching of URLs other ideas?

Where to get more information There are now many decent Java books Many other web resources