UMBC
Advanced Java Applications
Shon Vick CMSC 331
UMBC
Agenda
We will look at some advanced techniques and applications of Java The first will take a quick look at some data structures built into the language Next will show be how Java and Object Orientation can be applied to networking Finally we will be to show Reflection in Java
2
UMBC
Hashtable Example
Hashtable numbers = new Hashtable(); key value [Link]("one", new Integer(1)); [Link]("two", new Integer(2)); [Link]("three", new Integer(3));
UMBC
Hashtable Example
Specific Object
Object
Integer n = (Integer)[Link]("two"); if (n != null) { [Link]("two = " + n); }
4
UMBC
Many Other Collections
Vector Stack LinkedList Dictionary ArrayList [Link] ocs/api/[Link] for a complete list
5
UMBC
Networking
Using the networking capabilities provided in the Java environment is quite easy We will see how to use Sockets
UMBC
Sockets
Lower-level network communication
Client uses some service Server - provides some service
TCP provides a reliable, point-to-point communication channel for client-server apps
UMBC
What Is a Socket?
A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent.
UMBC
How do Sockets work?
A server runs on a specific computer and has a socket that is bound to a specific port number.
Client knows the hostname and port of server and tries to make a connection request
9
UMBC
Connection established
If the server accepts the connection it gets a new socket bound to a different port. It needs a new socket (and consequently a different port number) so that it can continue to listen to the original socket
10
UMBC
How does Java support Sockets
The [Link] package provides a class, Socket, that implements one side of a twoway connection between your Java program and another program on the network It also includes the ServerSocket class, which implements a socket that servers can use to listen for and accept connections to client
11
UMBC
Echo Echo Echo
import [Link].*; import [Link].*; public class EchoClient { public static void main(String[] args) throws IOException { Socket echoSocket = null; PrintWriter out = null; BufferedReader in = null; //
12
UMBC
Establish the Socket connection
try { echoSocket = new Socket(avatar ", 7777); out = new PrintWriter([Link](), true); in = new BufferedReader(new InputStreamReader([Link]())); } catch
Input
13
Host
Port
Output
UMBC
Need to Catch Exceptions
} catch (UnknownHostException e) { [Link]("Don't know about host: avatar."); [Link](1); } catch (IOException e) { [Link]("Couldn't get I/O for " + "the connection to: avatar."); [Link](1); } 14
UMBC
Simple Socket Example
Set up a mechanism to read from standard input
BufferedReader stdIn = new BufferedReader( new InputStreamReader([Link])); String userInput; Read from standard input while ((userInput = [Link]()) != null) { Write to Server
[Link](userInput);
[Link]("echo: " + [Link]()); }
Output whats read back from Server
15
UMBC
Close up Shop on Client side
[Link]( ); [Link]( ); [Link]( ); [Link]( );
16
UMBC
Basic Steps
Open a socket. Open an input stream and output stream to the socket. Read from and write to the stream according to the server's protocol. Close the streams. Close the socket.
17
UMBC
Same Basic Steps
This client program is straightforward and simple because the Echo server implements a simple protocol Even with more complicated protocols such as HTTP server, your client program while more complicated will follow the same basics as this simple example
18
UMBC
Server
A server must open a SeverSocket
ServerSocket server = new ServerSocket( 7777 );
Call accept on that socket creating a new socket
Socket socket = [Link]();
Socket acts as socket from client
19
UMBC
If a socket is a pipe
We could conceptualize this like so:
Ports
Server
Client
The Socket Plumbing
The things flowing through the Plumbing
20
UMBC
The Answer Is ..
A Number of things can conceptually flow through the pipe We will focus on two:
Objects Characters from a String
We looked at several examples last time
The first was a simple echo program a very simple protocol give me back what I gave you (Strings) We also looked at simpleprotocol example (Protocol Objects)
21
UMBC
Objects flow through the Pipe
Let first address the case where we want to have objects flowing over the pipe Must have at least the following mechanisms for
Objects to be written by the server Objects to be read by the client
22
UMBC
The newprotocol Client
public class Client { Socket socket = new Socket( "[Link]", 9999 ); // ObjectInputStream input = new ObjectInputStream([Link]() );
// read using serialization NewProtocol protocol = (NewProtocol)([Link]() ); [Link](Protocol: + protocol); [Link]();
23
UMBC
The newprotocol Server
class ThreadedSocket extends Thread { // here is where all the real work is done. private Socket socket; ThreadedSocket( Socket socket ) { [Link] = socket; // ObjectOutputStream output = new ObjectOutputStream([Link]() );
[Link]( protocol );
24
UMBC
Reading and Writing Objects
An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream. The objects can be read (reconstituted) using an ObjectInputStream. General Mechanism
This works for the sockets as was just shown but is actually more general Persistent storage of objects can be accomplished by using a file for the stream.
25
UMBC
File example
For example to write an object that can be read by the example in ObjectInputStream
FileOutputStream ostream = new FileOutputStream([Link]"); ObjectOutputStream p = new ObjectOutputStream(ostream); [Link](12345); [Link]("Today"); [Link](new Date()); [Link](); [Link]();
26
UMBC
The read counterpart
FileInputStream istream = new FileInputStream(" [Link] "); ObjectInputStream p = new ObjectInputStream(istream); int i = [Link](); String today = (String)[Link](); Date date = (Date)[Link](); [Link]();
27
UMBC
The Needed Java Framework
Only objects that support the [Link] interface can be written to streams. The class of each serializable object is encoded including the class name and signature of the class, the values of the object's fields and arrays, and the closure of any other objects referenced from the initial objects This relates to introspection/reflection which we will discuss shortly
28
UMBC
More about the Framework
The default deserialization mechanism for objects restores the contents of each field to the value and type it had when it was written.
Marshalling of Objects (Serialize) Un marshaling of Object (Serialize)
29
UMBC
Deserialization & Object Reflection
Fields declared as transient or static are ignored by the deserialization process. References to other objects cause those objects to be read from the stream as necessary.
Graphs of objects are restored correctly using a Reflection reference sharing mechanism. New objects are always allocated when deserializing, which prevents existing objects from being overwritten
30
UMBC
Reflection Allows
Determination of the class of an object. Creation of an instance of a class whose name is not known until runtime. Obtaining information about a class's modifiers, fields, methods, constructors, and superclasses. Determination of constants and method declarations that belong to an interface
31
UMBC
Reflection Also Allows
Allows one to get and set the value of an object's field, even if the field name is unknown to your program until runtime. Allows one to invoke a method on an object, even if the method is not known until runtime. Create a new array, whose size and component type are not known until runtime, and then modify the array's components.
32
UMBC
Examining Classes
A way to get information about classes at runtime For each class, the Java Runtime Environment (JRE) maintains an immutable Class object that contains information about the class. A Class object represents, or reflects, the class To get this information you need to get the Class object that reflects the class
33
UMBC
Retrieving Class Objects
You can retrieve a Class object in several ways:
Class c = [Link]() // for some object named foo Foo
Bar b = new Bar(); Class c = [Link](); Class s = [Link]();
Bar
34
UMBC
Other Ways of Retrieving Class Objects
If you know the name of the class at compile time, you can retrieve its Class object by appending .class to its name:
Class c = [Link];
You can also use the [Link] static method:
Class c = [Link](commandNameToken)
35
UMBC
Getting the Class Name
Every class in the Java programming language has a name. When you declare a class, the name immediately follows the class keyword At runtime, you can determine the name of a Class object by invoking the getName method. The String returned by getName is the fully-qualified name of the class. A good home study question: Given an instance prints the names of the classes its inheritance hierarchy from least specific to most specific excluding Object
36
UMBC
An Example
import [Link].*;
import [Link].*;
class SampleName { public static void main(String[] args) {
Button b = new Button();
printName(b); } static void printName(Object o) { Class c = [Link](); String s = [Link](); [Link](s);
Need Reflection Package To Do this
37
}}
UMBC
Selected References
Advanced Techniques for Java Developers,Berg &Fritzinger, Wiley, 1999 Chapter 4 [Link] g/[Link] The Java Programming Language , [Link] and J. Gosling , Addison-Wesley , 1996 Java in a Nutshell , D. Flanagan, O'Reilly and Associates [Link]
38
UMBC
More References
The Java Programming Language , [Link] and J. Gosling , Addison-Wesley , 1996 Java in a Nutshell , D. Flanagan, O'Reilly and Associates [Link]
39