1 lecture 6 george koutsogiannakis /summer 2011 cs441 current topics in programming languages

59
1 Lecture 6 George Koutsogiannakis /Summer 2011 CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES

Upload: nathan-rose

Post on 03-Jan-2016

215 views

Category:

Documents


0 download

TRANSCRIPT

1

Lecture 6

George Koutsogiannakis /Summer 2011

CS441

CURRENT TOPICS IN PROGRAMMING LANGUAGES

Topics

• Starting a child process.

• More on Special Graphical Components.– JEditorPane / JTable Editable and Selectable cells.

• I/O Streams

• Client Server / Using sockets.– Client / Server steps for Connection Oriented

– Multithreaded server

– Connectionless Client / Server

– Multicasting2

Start Child Processpublic class StartChildProcess {

public static void main(String[] args) {

Runtime rt=Runtime.getRuntime();

Process proc;

String cmd[]=new String[3];

cmd[0]="V1T4.exe";

cmd[1]="newtst22.txt";

cmd[2]="6";

try

{ proc=rt.exec(cmd);DataInputStream in=new DataInputStream(proc.getInputStream());

byte[] buf=new byte[256];

int cbRead=0;

while(cbRead>=0)

cbRead=in.read(buf);

in.close();

String str=new String(buf); //write the data into a file

FileOutputStream file=new FileOutputStream("testout.txt");

OutputStreamWriter out=new OutputStreamWriter(new BufferedOutputStream(file));

out.write(str);

out.flush();

file.close();}

catch(IOException e)

{System.out.println(e);}}

} 3

java CC exe Data stream

Start Child Process

• The child process is a C program that has a main that takes as arguments two parameters.

main(argc, argv)– Where argc is an integer that represents the number of arguments

– And argv is an array of Strings that represents the arguments to be passed to this process. The first entry into the array is always the name of the child process’ executable.

• For more details see example posted on the course ‘ s web site: start a child process with a Java program.

4

JEditorPane Component

• Special component that can display different formats of files.

• It supports:– HTML.

– RTF (Rich Text Format).

– Special purpose applications via a ‘Editor Kits”.

– Display could be editable by the user and saved.

5

JEditorPane Component

• Usage:– Within try/catch block that captures IOException:

Create an object of the class:

JEditorPane editorpane= new JEditorPane (url );

Where url is a String that points to either a web resource

(i.e. http://localhost:8080/MyWeb/index.html)

Or to a file in the local system

(i.e. file://C:/MyPrograms/index.html )

– editorpane.set(false); prevents editing on the text area.

6

JEditorPane Component

– Register the component with a listener so that when user clicks on a url the file gets retrieved and displayed:

html.addHyperlinkListener(this);– Add the editor pane component to a container like a

JPanel (possibly add it to a JScrollPane before adding it to a JPanel).

– Override the hyperlinkUpdate method of the HyperlinkListener Interface.

7

JEditorPane Component

• public void hyperlinkUpdate ( HyperlinkEvent e)

{

if (e.getEventType() = = HyperlinkEvent.EventType.ACTIVATED)

try

{

editorpane.setPage(e.getURL());

…………………………………………………………

……………………………………………………………………….

• It is assumed that a text field has been created with the proper listener for the text field where the user can type the url that leads to the file to be displayed.

• For more details see example poste don the course ‘s web site:browser.java

8

JTable

• When we create a JTable we can have the user:– Edit the cells.– Select rows and columns whose data the user

wants to save maybe in a file or in a data structure.

9

Editing JTable

• Example of EditableTable.java program on course ‘s web site.

– Program lets user create a model object:

• Override various methods of TableModel.

• Calling the method fireTableCellUpdated(row, column) in turn calls the listener (event handler) of the Controller part.

• Overriding method isCellEditable can identify the specific cells that the user can edit when the Table and its data is displayed.

– Create the View:

• Wrap the model object with a JTable object and then with a JScrollPane object.

• Set the viewing size using the JTable object:

Mytable.setPreferredScrollableViewportSize(new Dimension( 500, 300);

10

Editing JTable

– Create the Controller by implementing the Listener interface TableCellEditor and overriding its methods:

public Component getTableCellEditorComponent (JTable table, Object value, boolean isSelected, int row, int column)

and

public Object getCellEditorValue()• Notice that editing can be done directly ion the displayed cell or on a special

JTextArea or JTextField component that can be presented to the user.

11

JTable –Selecting Rows and Columns.

• See example SimpleTableSelectionDemo.java on the course’ s web site.

• Create the model and view as in previous example of Editable Table.

• Use the JTable object to set the mode of selection by the user”– Allow single row selection only or

– Allow multiple rows to be selected or

– Allow intervals of multiple rows to be selected.

i.e table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

• Create a reference of ListSelectionModel and register it with an event handler.

– The event handler overrides method valueChanged of ListSelectionListener interface.

– In this method w e can sense the beginning index of the row selected and the ending index.

– Once we know the rows we can capture the row data and do whatever we want to do with it.

12

I/O Streams

• Java uses many different types. Which stream you use depends on the type of communication i.e. – Are we opening a particular type of file for

reading or writing?– What data types are involved?– Are we setting up a communication path

between a client and a server?• Are we transmitting entire objects?

13

File Types

• Java basically supports two types of files:– text files: data is stored as characters – binary files: data is stored as raw bytes

The type of a file is determined by the classes used to write to the file.

• Types of Files can be:– Files written using Bytes Streams (1s and 0s).– Files written using Character Streams (char types).– Files written in terms of Strings (text).– Files written using primitive data types (int, double etc)– Files written using entire object streams (recording all

information about an object in a coded format).

14

File Types

• To read an existing file, you must know the file's type in order to select and import the appropriate library classes for reading the file.

15

Writing to Text Files

• Several situations can exist:– the file does not exist

– the file exists and we want to replace the current contents

– the file exists and we want to append to the current contents

• We specify whether we want to replace the contents or append to the current contents.

16

Streams• Therefore:

• To read a file input stream is needed.

• To write to a file output stream is needed.

• The java.io package provides the classes for establishing input and output streams.

17

Selected Input Classes in the java.io Package

Class DescriptionInputStream Abstract superclass representing a

stream of raw bytesFileInputStream Input stream to read raw bytes of data

from filesObjectInputStream Class to read/recover objects from a

file written using ObjectOutputStream

18

Hierarchy for Input Classes

19

Selected java.io Output Classes

Class DescriptionWriter Abstract superclass for output classes

OutputStreamWriter Class to write output data streams

OutputStream Abstract superclass representing an output stream of raw bytes

FileWriter Class for writing to character files

BufferedWriter More efficient writing to character files

PrintWriter Prints basic data types, Strings, and objects

PrintStream Supports printing various data types conveniently

FileOutputStream Output stream for writing raw bytes of data to files

ObjectOutputStream Class to write objects to a file

20

Hierarchy for Output Classes

21

Reading Text Files with Scanner

• In CS115 we used the File object and the Scanner object to read a text file• i.e.import java.io.File;import java.io.IOException;import java.util.Scanner;Public class ReadFile {Public static void main(String[] args) {

try{

File myfile=new File(“mytextfiel.txt”);Scanner scan=new Scanner(myfile);

while(scan.hasMoreTokens()) { String str=scan.next();

System.out.println(str); }

catch)(IOException ioe) { System.out.println(ioe.toString()); } }}

22

Opening and Closing an Input Stream• When we construct an input stream or output stream object, the

JVM associates the file name, standard input stream, or standard output stream with our object. This is opening the file.

• When we are finished with a file, we optionally call the close method to release the resources associated with the file.

Return value Method name and argument list

void close( )

releases resources associated with an open input stream. Throws an IOException.

Closing an output stream

• When closing a Buffered output stream in addition to the close() method for the stream the methdod flush() should also be invoked:

datastreamobject.flush();– Flushing the output stream forces any

buffered output bytes to be written out.

24

Opening and Closing Standard Streams

• Some streams are standard and the are available to any java program.

• The standard input stream (System.in), the standard output stream (System.out), and the standard error stream (System.err) are open when the program begins. They are intended to stay open and should not be closed.

25

Exceptions While Reading from a File We can catch this exception:

FileNotFoundException thrown by the Scanner constructor if the filename is not found when opening the file

We do not expect these exceptions to occur, so we will catch them as subclasses of IOException, and print the stack trace.

InputMismatchException if the input does not match the expected data type. (The next method does not throw this exception, so we don’t need to catch this exception).

NoSuchElementException if we attempt to read beyond the end of the file. IllegalStateException if we attempt to read after calling the close method.

26

Buffering

Writing data to the disk is much slower than writing data into main memory.

When a class uses buffering, instead of writing one character at a time to the file, it accumulates the data in a temporary location in memory, called a buffer.

When the buffer is full or is flushed, the accumulated

data is written to the file in one efficient operation.

27

Writing Primitive Types to Text Files

FileOutputStream, a subclass of the OutputStream class, is designed to write a stream of bytes to a file.

The PrintWriter class is designed for converting primitive data types to characters and writing them to an output stream. – print method, writes data without a newline

– println method, writes data then adds a newline28

Example: Writing to a Text File

Suppose we want to write a String aString to a File

try {

FileOutputStream file = new FileOutputStream(filename, true);

OutputStreamWriter filestream = new OutputStreamWriter(new BufferedOutputStream(file));

filestream.write(aString);

filestream.flush();

file.close();

}

Catch(IOException ioe)

{

System.out.ptintln(ioe.toString());

}

• If more than one String is to be written then a loop can be used.

• Notice that the flush method needs to be called at the end to flush out the stream into the file. If this is not done the String is not written in the file!

29

Serialization

• Writing objects into a file involves a protocol of Java called: Serialization– Objects are converted (serialized) into a byte

stream and stored in the file.

• Reading objects from a file involves a protocol called deserialization.– Objects are converted back to the particular

data type that they belong to.

30

Serialization

• A State of an object is the particular value sof its attributes (fields) at a particular time.

• Saving a particular state via serialization is called “persistence”.

31

Writing Objects to a File

To write an object to a file, its class must implement the Serializable interface, which indicates that:– the object can be converted to a byte stream to be written to a file– that byte stream can be converted back into a copy of the object

when read from the file

The Serializable interface has no methods to implement. All we need to do is: – import the java.io.Serializable interface– add implements Serializable to the class header– i.e public class MyClass implements Serializable

32

The ObjectOutputStream ClassThe ObjectOutputStream class, coupled with

the FileOutputStream class, provides the functionality to write objects to a file.

The ObjectOutputStream class provides a convenient way to write objects to a file. – Its writeObject method takes one argument: the object

to be written.

33

Constructors for Writing Objects Class Constructor

FileOutputStream FileOutputStream( String filename, boolean mode )

creates a FileOutputStream object from a String representing the name of a file. If the file does not exist, it is created. If mode is false, the current contents of the file, if any, will be replaced. If mode is true, writing will append data to the end of the file. Throws a FileNotFoundException.

ObjectOutputStream ObjectOutputStream( OutputStream out )

creates an ObjectOutputStream that writes to the OutputStream out. Throws an IOException. 34

The writeObject MethodReturn value Method name and argument listvoid writeObject( Object o )

writes the object argument to a file. That object must be an instance of a class that implements the Serializable interface. Otherwise, a run-time exception will be generated. Throws an IOException.

35

Omitting Data from the File

The writeObject method does not write any object fields declared to be static or transient.

You can declare a field as transient if you can easily reproduce its value or if its value is 0. Syntax to declare a field as transient:

accessModifier transient dataType fieldName

Example:

private transient double totalRevenue;

36

Reading Objects from a FileThe ObjectInputStream class, coupled with

FileInputStream, provides the functionality to read objects from a file.

The readObject method of the ObjectInputStream class is designed to read objects from a file.

Because the readObject method returns a generic Object, we must type cast the returned object to the appropriate class.

When the end of the file is reached, the readObject method throws an EOFException, so we detect the end of the file when we catch that exception.

37

Constructors for Reading Objects

Class ConstructorFileInputStream FileInputStream( String filename )

constructs a FileInputStream object from a String representing the name of a file. Throws a FileNotFoundException.

ObjectInputStream ObjectInputStream( InputStream in )

creates an ObjectInputStream from the InputStream in. Throws an IOException.

38

The readObject Method

Note:

– we detect reaching the end of the file in the EOFException catch block

–we use a finally block to close the file

Return value Method name and argument list

Object readObject( ) reads the next object and returns it. The object must be an instance of a class that implements the Serializable interface. When the end of the file is reached, an EOFException is thrown. Also throws an IOException and ClassNotFoundException

39

Example Of Writing Objects

• Suppose that we have a class called Vehicle.

• We could serialize the Vehicle class by making a minor change to the class:

public class Vehicle implements Serializable

• We can exclude certain fields of the class from being serialized (and thus have their values written) by using the keyword transient in front of the declaration of the field.

i.e.

private transient double init_v;

private transient double init_d;

40

Example Of Writing Objects

Vehicle va=new Vehicle(“My Vehicle”, 2, 3, 2.1, 3.5);

try{

FileOutputStream fos=new FileOutputStream(“MyFile.ser”);

ObjectOutputStream oos=new ObjectOutputStream(fos);

oos.writeObject(va);

oos.close();

}

catch(IOException ioe)

{

System.out.println(“Error writing into file”);

ioe.printStackTrace();

}41

Example of Reading the Object From the File

try{FileInputStream fis = new FileInputStream(“MyFile.ser”);ObjectInputStream ois = new ObjectInputStream(fis);Vehicle vh = (Vehicle)ois.readObject();ois.close();}Catch(IOException ioe){

System.out.println(“Error writing into file”); ioe.printStackTrace();}• We can output the object’s attributes and observe that the values are the

same as the ones we wrote in the file.

42

Client / Server

• Socket: holds IP address and software port number number

43

client server

Listening Socket

Data Port

Client’s Socket

1

2

1. Client contacts server’s listening port requesting permission to connect.2.If permission is granted communications take place via a data port dedicated

to this client.Other clients can request permission to connect and also be given their own data port on the server.

Client / Server

• A multithreaded server handles each client communication with it in a separate thread for each client.

• Networking can be established in Java by using the java.net classes.

• In setting up the communications we can have two kinds of sockets :– Connection oriented:

• Uses TCP/IP protocols.

• Requires a handshake to establish the communication and a handshake to end it.

• Reliable . Ensures that packets reach destination.

• Continuous Stream sockets.

• Think of it a s a phone call type of communication.

– Connectionless oriented:• Uses datagram packets

• Does not require a handshake to start the communication or to end it.

• Unreliable. No guarantee that packets will arrive to their destination.

• Better performance than TCP but requires more coding.

• Think of it as writing a 10 page letter and putting it in 10 different envelops (one page in each envelop) and then mailing them.

44

Client /Server

• Three steps to create a Server process for TCP/IP:1. Create a server socket object:

ServerSocket ss= new ServerSocket ( 5000, 100);Where 5000 is the listening port for the server and 100 is the maximum

number of clients that can connect.

ss object represents the listening socket

2. The following code lets the listening port to accept a request from a client:

Socket connection=ss.accept();

45

Client /Server

– Notice that:– Program execution blocks at this line waiting for a client send connection request packets. – Socket type object connection encapsulates the information about the client when it

arrives i.e. client’s IP address, client ‘s port number.– That when the server accepts it sends packets with information about itself including the

port that is assigned to this client for data exchange. This port is assigned on the fly by the O.S.

– Program execution now resumes.

3. Create input and Output Stream objects:

ObjectInputStream input= new ObjectInputStream( connection.getInputStream()); //server gets input from client’s output stream

ObjectOutputStream output=new ObjectOutputStream (connection.getOutputStream()); //server sends output out to the client’s input stream

46

Client /Server

– Notice that connection is the object that encapsulates the information about the particular client.

– Use the object streams to either read incoming data from the Input Stream (on the port assigned to this particular client) or write into the Output Stream to send data to the client.

i.e. Output.writeObject(String message);

Or (String) input.readObject();

Notice that objects can be serialized and exchanged between the client and the server in a serializable format (streams of ones and zeros).

47

Client /Server

• Steps 2 and 3 should be in a while loop that lets the server run continually and block while it is waiting fro a client’s request.

• The server should be started on its own DOS pane and then minimized letting it run in the background.

48

Client / Server

• Three steps to create a client process:1. Create a Socket to ask connection with a server.

Socket cs= new Socket(serverIP , port)

Where serverIP is the IP address of the server (could be localhost if both client and server are on the same machine) and

Port is the listening port number of the server (i.e. 5000 in our example).

2. Create Input and Output Stream objects as in step 3 of the server.

i.e. ObjectOutputStream os= new ObjectOutputStream (cs.getOutputSream());

ObjectInputStream is= new ObjectInputStream (cs.getInputStream());

3. Process incoming and outgoing data.49

Client / Server

• See example on the course’s web site for client server processes.

• Multithreaded Server:– Needs a main thread that allocates threads to clients requesting

connection. This main thread passes to the allocated thread a reference of the Socket objec that represents the particular client from step 2 of the server example.

– The allocated thread handles the subsequent communications between the client and the server by overriding the Thread class’ run method.

50

Client / Server Datagrams

• Server:1. Create Datagram Socket

DatagramSocket socket= new DatagramSocket ( 5000)

where 5000 is the assigned port

2. Wait for incoming packets from client and capture them (notice that no listening port is involve d).

DatagramPacket receivedpacket= new DatagramPacket ( data, data.length);

Where data is a byte array to store the data read fro m the incoming datagram packets.

program execution blocks at the following line of code:

socket.receive(receivepacket);

51

Client / Server Datagrams

3. Process packet i.e.

String mydata= new String (receivepacket.getData(), 0, receivepacket.length());

String clientaddress= receivepacket.getAddress();

String clientport= receivepacket.getPort();

4. Create datagram to send to data back to client.

DatagramPacket sendpacket= new DatagramPacket (data) where

data is some String.

socket.send (sendpacket);• Notice that 1) steps 2 and 3 should be within a while loop that keeps the

server running while it blocks 2) that the cod efor 2 and 3 should be within try/catch for IOException 3) that th eserver should be in its own DOD pane.

52

Client / Server - Multicasting

• See example Settingup Multicasting on the course’ s web site.

• In Multicasting we use connectionless communications (datagrams).

• A multicast group needs to be created and the group needs to be joined by members.

53

Client / Server - Multicasting

• Let us look at example where we set up a messaging service that is controlled by a messaging server:

54

Server

Client 1

Client 2

Client 3

1

2

3

Client / Server - Multicasting

1. Client port created on the fly asks for permission to connect. The server accepts and creates a data port for the client on the fly. The information is sent to the client

2. Client sends a message to a multithreaded port on the server if the request is accepted. The server creates a thread for this client to handle the client’ s message.

3. The server has a multicast port to send data out to subscribers. The server sends out the message to all clients who have subscribe to the multicast port.

4. The clients receive the message on a special port.

55

Client / Server - Multicasting

• A Multicast group is identified by a class D IP address and by standard UDP port (datagram port).

• The allowable IP addresses are in the range:

224.0.0.0 to 239.255.255.255 inclusive.

• Address 224.0.0.0 is reserved and not be used.

• One joins the group as follows:

MulticastSocket ms = new MulticastSocket (6000);

where 6000 is the agreed multicast port.

InetAddress group =InetAddress.getByName(“228.5.6.7”);

where 228.5.6.7 is the agreed multicast IP

56

Client / Server - Multicasting

ms.jointGroup ( group );

Now the member has joined other members that have done the same.• To send a message to the members:

create an array of type byte.

place the message into the byte array.

create the Datagram packet:

DatagramPacket packet = new DatagramPacket ( buffer, buffer.length, address, port).

where buffer is the byte array, address is the multicast IP and port is the port agreed for multicasting.

socket.send ( packet );

57

Client / Server - Multicasting

• To receive a packet:

create a byte type array to store data from incoming datagram packet call it buffer.

DatagramPacket receivedpacket= new DatagramPacket buffer, buffer.length);

socket.receive ( receivedpacket);

String message = new String ( receivepacket.getData () );

• A member can leave the group by invoking:

socket.leaveGroup ( address) ;

where address is the multicast IP

58

Study Guide

• Look up examples on Client/Server posted on the course’s web site under the examples page.

59