Sie sind auf Seite 1von 65

Enterprise System Essentials

Core to Java EE

Enterprise System Essentials


Collections
Network Programming (TCP / UDP)

Collection
Generics

Collection
A collection is a container object that holds a
group of objects known as elements.
It contains operations for Adding, Updating, and
Removing elements
A Collections framework is a unified architecture
for representing and manipulating collections. It
has:

Interfaces: abstract data types representing collections


Implementations: concrete implementations of the
collection interfaces
Algorithms: methods that perform useful
computations, such as searching and sorting

These algorithms are said to be polymorphic: the same method


can be used on different implementations

Collection Interface

Collection Interface

Collection Interface

Wildcards in Collection

Classes and interfaces in the collection framework can have


parameter type specifications that do not fully specify the type
plugged in for the type parameter
Because they specify a wide range of argument types, they
are known as wildcards
public void method(String arg1, ArrayList<?> arg2)

In the above example, the first argument is of type String,


while the second argument can be an ArrayList<T> with any
base type
A bound can be placed on a wildcard specifying that the type
used must be an ancestor type or descendent type of some
class or interface
The notation <? extends String> specifies that the argument
plugged in be an object of any descendent class of String
The notation <? super String> specifies that the argument
plugged in be an object of any ancestor class of String

Collection Framework

Interfaces: An interface describes a set of


methods:
No constructors or instance variables
Interfaces must be implemented by classes
Objects can be treated as the same type
Implementations: A collection class
implements an Abstract Data Types (ADT) as a
Java class
implements all methods of the interface
can be instantiated
Java implements interfaces with list, map, and set.
Algorithms: Java has polymorphic algorithms to
provide functionality for different types of
collections, such as, Sorting, Shuffling, Searching,
and etc.

Collection API Hierarchy


SortedSet

TreeSet

Set

AbstractSet

Collection

HashSet

LinkedHashSet

AbstractCollection
Vector
AbstractList

List

ArrayList

AbstractSequentialList

LinkedList

Deque
Queue

Interfaces

AbstractQueue

Abstract Classes

PriorityQueue

Concrete Classes

Stack

Collection API Hierarchy


In Map, each object is associated with a key.
Key is used to get or put the object in a map.

SortedMap
Map

TreeMap
AbstractMap

Interfaces

Abstract Classes

HashMap

Concrete Classes

LinkedHashMap

Collection Implementations: List

A List collection stores elements by position


and includes index-based operations, such
as:

Array List
Link List

The List interface extends the Collection


interface by adding index-based operations.
These allow for insertion, deletion, access,
and updates at an index position in the list.

List Collection: ArrayList


An ArrayList collection is a generalized
array that stores element in a contiguous
block of memory.
Grows dynamically that it automatically
expands to handle insertion and deletion
of new elements.
Direct-access structure
The collection efficiently:

O(1) to inserts and deletes an element


O(n) for operations at complete list

The list shifted right for insertion and left


for deletion

List Collection: LinkList


A LinkedList collection is a sequence whose
elements have a value and links that
identify adjacent elements in the
sequence.
Sequential- access structure.
Inserting or deleting elements in a
LinkedList involves O(1) operations
Extended to the OrderedList class that
creates collections that store elements in
order.

List Collection: Stack


A Stack is a collection with a single reference
point called the top of the stack.
An element is added at the top of the stack
(push operation) and removed from the top
of the stack (pop operation).
Last-In-First-Out (LIFO) ordering, elements
come off a stack in the reverse order of their
insertion

Collection Implementations: Set


A Set is a collection that resembles a Bag
with the provision that duplicate values are
not allowed.
Applications typically use Set collections for
operations set union, set intersection, and
set difference.

Collection Implementations: Map


A Map is a collection of key-value pairs.
Key uniquely identifies the element while the
value field typically has associated data.
Access to an element requires only the key
Map is referred to as an associative array.

Collection Implementation Guides


Hash Table

Set

balanced
tree

ArrayList
Vector
HashMap
Hashtable

linked list

TreeSet
(sortedSet)

HashSet

List

Map

Resizable
array

LinkedList
TreeMap
(sortedMap)

Network Programming

Client-Server Model

Most of the network


applications are designed
so that one end is client
and the other side the
server.
Server

Provides some type of


services to its clients.

Client

Uses the services provided


by the server.

Client

Server

Client-Server Model

Two Server Classes


Iterative Servers
1.
2.
3.
4.

Wait for a client t arrive


Process the client request
Send the response back
to the client
Go back to step 1

Problem?
.

When step 2 takes a


while, no other clients are
serviced

Concurrent Servers
1.
2.

3.

Wait for a client request


to arrive
Start a new server to
handle this clients
requests. When
complete, this new server
terminates
Go back to step 1

Decisions

Before you write socket code, decide

Do you want a TCP-style reliable, full duplex,


connection oriented channel? Or
Do you want a UDP-style, unreliable, message
oriented channel?
Will the code you are writing be the client or the
server?
Client: you assume that there is a process
already running on another machine that you
need to connect to.
Server: you will just start up and wait to be
contacted

Socket Programming using TCP

Client must contact server


server process must first be running
server must have created socket (door) that
welcomes clients contact

Client contacts server by:


creating client TCP socket
specifying IP address, port number of server process
When client creates socket: client TCP establishes
connection to server TCP
When contacted by client, server TCP creates new
socket for server process to communicate with client
Frees up welcoming port
allows server to talk with multiple clients

Socket Programming using TCP

Client

Server

Welcoming
Socket
handshake

Client
socket

bytes
bytes

Connection
Socket

Example: Java TCP Client

Sample client-server app:


1.

2.
3.
4.

client reads line from standard input


(inFromUser stream) , sends to server
via socket (outToServer stream)
server reads line from socket
server converts line to uppercase,
sends back to client
client reads, prints modified line from
socket (inFromServer stream)

Example: Java TCP Client

Client Process
Out to monitor
Out to server

In from server
In from user

Client
TCP
Socket

To Network
From Network

Example: Java TCP Client


import java.io.*;
import java.net.*;
class TCPClient {
public static void main(String[] args)
throws Exception {
String hostName = args[0];
int port = Integer.parseInt(args[1]);
String sentence;
String modifiedSentence;
Create
Console
reader
stream

BufferedReader inFromUser =
new BufferedReader(
new InputStreamReader(System.in));

Example: Java TCP Client


Create
client socket,
connect to server

Socket clientSocket =
new Socket(hostName, port);

Create
output stream
attached to socket

PrintWriter outToServer = null;


outToServer = new PrintWriter(
clientSocket.getOutputStream(),true);

Create
input stream
attached to
socket

BufferedReader inFromServer = null;


inFromServer = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));

Example: Java TCP Client


sentence = inFromUser.readLine();
outToServer.print(sentence + \r\n);

Send line
to server

Read line
from server

modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " +
modifiedSentence);
clientSocket.close();

Close the
connection

}
}

Example: Java TCP Server

Pseudo code TCP server


1.
2.
3.

4.
5.

Bind socket to a specific port where clients can


contact.
Server listens on welcomeSocket for client to
contact it
Loop
Accept new connection (connectSocket)
Read and write data into connectSocket to
communicate with client.
Close connectSocket.
End Loop
Close welcomeSocket

Example: Java TCP Server


import java.io.*;
import java.net.*;

Server Port

public class TCPServer {


public static final int SERVER_PORT = 6789;
public static void main(String argv[])
throws Exception {
String clientSentence;
String capitalizedSentence;

Create
welcome socket
at port 6789

ServerSocket welcomeSocket =
new ServerSocket(SERVER_PORT);

Example: Java TCP Server

Wait, on welcome
socket for contact
by client

Create
Input stream,
attached
to socket

Create output
stream,
attached
to socket

while(true) { // Listen forever


Socket connectSocket =
welcomeSocket.accept();
InputStream sin =
connectSocket.getInputStream();
BufferedReader inFromClient =
new BufferedReader(
new InputStreamReader(sin));
PrintWriter outToClient =
new PrintWriter(
connectSocket.getOutputStream(),
true);

Example: Java TCP Server


Read in line
from socket

clientSentence = inFromClient.readLine();
capitalizedSentence =
clientSentence.toUpperCase()+\r\n;

Write out line


to socket

outToClient.print(capitalizedSentence);
}
}
}

End of while loop,


loop back and wait for
another client
connection

Client-server Socket Interaction: TCP


Server (running on hostid)

Client

create socket on port 6789


for incoming request:
welcomeSocket =
ServerSocket()
wait for incoming
TCP
connection request
connection setup
connectionSocket =
welcomeSocket.accept()

read request from


connectSocket
write reply to
connectionSocket
Close connectSocket

create socket,
connect to hostid, port=6789
clientSocket =
new Socket (hostid,
6789)
send request
using
clientSocket

read reply from


clientSocket
closeclientSocket

Socket Programming using UDP

UDP: very different mindset than TCP

no connection just independent messages sent


no handshaking
sender explicitly attaches IP address and port of
destination
server must extract IP address, port of sender from
received datagram to know who to respond to

UDP: transmitted data may be received out


of order, or lost
UDP provides unreliable transfer of groups
of bytes (datagrams) between client and
server

Socket Programming using UDP


Pseudo
1.
2.
3.
4.
5.

code for UDP Client

Create socket
Loop
Send Message To Well-known port
of the Server
Receive Message From Server
Close Socket

Example: Java UDP Client


import java.io.*;
import java.net.*;
class UDPClient {
public static void main(String[] args)
throws Exception {
String hostName = args[0];
int port = Integer.parseInt(args[1]);
String sentence;
String modifiedSentence;
Create
stdin
stream

BufferedReader inFromUser =
new BufferedReader(
new InputStreamReader(System.in));

Example: Java UDP Client


Create client
socket
Translate
hostname to IP
address using DNS

Create datagram
with data-tosend,
length, IP addr,
port
Send datagram
to server

DatagramSocket clientSocket =
new DatagramSocket();
InetAddress ipAddress =
InetAddress.getByName(hostName);
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
sentence = inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(
sendData, sendData.length, ipAddress, port);
clientSocket.send(sendPacket);

Example: Java UDP Client


DatagramPacket receivePacket =
new DatagramPacket(receiveData,
receiveData.length);
clientSocket.receive(receivePacket);

Read
datagram
from server

modifiedSentence =
new String(receivePacket.getData());
System.out.println("FROM SERVER:" +
modifiedSentence);

Close the
connection

clientSocket.close();
}
}

Socket Programming using UDP

Pseudo code for UDP Server


1.
2.
3.
4.
5.
6.

Create socket
Bind socket to a specific port where
clients can contact you
Loop
Receive UDP Message from client x
Send UDP Reply to client x
Close Socket

Example: Java UDP Server


import java.io.*;
import java.net.*;

Create
datagram
socket
at port 6789

Create space
for
received
datagram
Receive
datagram

public class UDPServer {


public static void main(String args[])
throws Exception {
DatagramSocket serverSocket =
new DatagramSocket(6789);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true){
DatagramPacket receivePacket =
new DatagramPacket(receiveData,
receiveData.length);
serverSocket.receive(receivePacket);

Example: Java UDP Server


String sentence =
new String(receivePacket.getData());
Get IP addr
& port of
sender

InetAddress IPAddress =
receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence =
sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();

Create
datagram
to send to
client
Write out
datagram
to socket

DatagramPacket sendPacket =
new DatagramPacket(sendData,
sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}

End of while loop,


loop back and wait for
another datagram

Socket Programming using UDP

Server has a well-known port number


Client initiates contact with the server
Less difference between server and client
code than in TCP

Both client and server bind to a UDP socket


Not accept for server and connect for client

Client send to the well-known server port


Server extracts the clients address from the
received datagram

TCP vs. UDP

TCP

pipe between the two processes


the pipe is logically connected to the destination
reliable byte stream channel

UDP

no welcoming socket, no pipe


destination address attached to bytes
unreliable transport service
receiving process must unravel each received
packet for packets information bytes

Common well known ports

Ports 20/21 File Transfer Protocol


Port 23
Telnet
Port 25
Simple Mail Transport Proto.
Port 79
Finger
Port 80
HTTP
Port 110
POP3 (Post Office Protocol)
All well known ports in the range 1..1023

Next Generation Internet

The solution is IPv6 which uses 128 bit


addresses
Improves services such as multicasting and
secure communication
Several addresses per m2 of the Earths
surface (3.4 x 1038 to be precise)
Not yet widely deployed by ISPs
Perhaps widely deployed in 2-4 years
Well written Java software should move to IPv6
without modification/recompilation

One benefit of abstracted APIs

IP Addresses and Java

Java has a class java.net.InetAddress which


abstracts network addresses
Serves three main purposes:

Encapsulates an address
Performs name lookup (converting a host name
into an IP address)
Performs reverse lookup (converting the address
into a host name)

java.net.InetAddress (1)

Abstraction of a network address


Currently uses IPv4 (a 32 bit address)
Will support other address formats in future
Allows an address to be obtained from a host
name and vice versa
Is immutable (is a read-only object)

Create an InetAddress object with the address you


need and throw it away when you have finished

java.net.InetAddress (2)

Static construction using a factory method

InetAddress getByName(String hostName)


hostName can be host.domain.com.au, or
hostName can be 130.95.72.134
InetAddress getLocalHost()

Some useful methods:

String getHostName()
Gives you the host name (for example www.sun.com)
String getHostAddress()
Gives you the address (for example 192.18.97.241)
InetAddress getLocalHost()
InetAddress[] getAllByName(String hostName)

Using InetAddress objects


import java.net.InetAddress;
import java.net.UnknownHostExcepion;
public static void main(String[] args)
{
try {
InetAddress inet1 =
InetAddress.getByName("asp.ee.uwa.edu.au");
System.out.println(
"HostAddress=" + inet1.getHostAddress());
InetAddress inet2 =
InetAddress.getByName("130.95.72.134");
System.out.println("HostName=" + inet2.getHostName());
if (inet1.equals(inet2))
System.out.println("Addresses are equal");
}
catch (UnknownHostException uhe) {
uhe.printStackTrace();
}}

What Is a URL?

Uniform Resource Locator (URL) is a reference


(an address) to a resource on the Internet.
Example:

http
Protocol
Identifier

//www.java.sun.com
Resource
Identifier

What Is a URL? Contd.

The protocol identifier indicates the name of


the protocol to be used to fetch the resource

Examples:

http, ftp, file, news, email, etc

The resource name is the complete address to


the resource

contains one or more of the following components:

Host Name
Port Number
File name
Reference

Creating URL
java.net.URL

The easiest way to create a URL object is from


a String
String str = "http://www.gamelan.com/index.html";
URL gamelan = new URL (str);

Absolute URL

contains all of the information necessary to reach


the resource

Relative URL

contains enough information relative to some


other URL to reach the resource

Creating Relative URL

WEB
Server

/pages/index.html
game.html
net.html

http://www.gamelan.com/pages/game.
html
http://www.gamelan.com/pages/net.h
tml

URL objects for these pages:


URL gamelan = new URL("http://www.gamelan.com/pages/");
URL gamelanGames = new URL(gamelan, "game.html");
URL gamelanNetwork = new URL(gamelan,"net.html");

Other URL Constructors

More complicated constructor:


public URL(String protocol,
String host, int port, String file)
throws MalformedURLException

try {
URL gamelan = new URL("http",
"www.gamelan.com", 80,
"pages/Gamelan.network.html");
} catch (MalFormedURLException ex){
// exception handler code here

Parsing a URL

You can get the protocol, host name, port number,


and filename from a URL using these accessor
methods:

getProtocol

getHost

Returns the port number component of the URL. The getPort


method returns an integer that is the port number. If the port
is not set, getPort returns -1.

getFile

Returns the host name component of the URL.

getPort

Returns the protocol identifier component of the URL.

Returns the filename component of the URL.

getRef

Returns the reference component of the URL.

Example: Parsing a URL


import java.net.*;
import java.io.*;
public class ParseURL {
public static void main(String[] args) throws Exception {
URL aURL = new URL("http://java.sun.com:80/docs/books/" +
"tutorial/index.html#DOWNLOADING");
System.out.println("protocol = " + aURL.getProtocol());
System.out.println("host = " + aURL.getHost());
System.out.println("filename = " + aURL.getFile());
System.out.println("port = " + aURL.getPort());
System.out.println("ref = " + aURL.getRef());
}
}

Example: Parsing a URL

Output

protocol = http
host = java.sun.com
filename = docs/books/tutorial/index.html
port = 80
ref = DOWNLOADING

Reading Directly from a URL


import java.net.*;
import java.io.*;

Create
URL

public class URLReader {


public static void main(String[] args)
throws Exception {
URL yahoo = new URL("http://www.yahoo.com/");

Open
the URL
Input
stream

BufferedReader in = new BufferedReader(


new InputStreamReader(
yahoo.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null){
System.out.println(inputLine);
}
in.close();
}

Read every
thing from
URL and
print
on std out

Setting the Proxy Host

UNIX/DOS Shell Windows 98/XP/2000/Vista


java -Dhttp.proxyHost=proxyhost
[-Dhttp.proxyPort=portNumber] URLReader

Creating a URL connection


import java.net.*;
import java.io.*;
public class URLConnectionReader {
public static void main(String[] args)
throws Exception {
URL yahoo = new URL("http://www.yahoo.com/");
URLConnection yc = yahoo.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}

Writing to a URLConnection

Use the following steps to write:

Create a URL
Open a connection to the URL
Set output capability on the URLConnection
Get an output stream from the connection. This
output stream is connected to the standard input
stream of the cgi-bin script on the server
Write to the output stream
Close the output stream
Use http://java.sun.com/cgi-bin/backwards for
testing

Writing to a URLConnection
public class Reverse {
public static void main(String[] args)
throws Exception {
if (args.length != 1) {
System.err.println("Usage: java Reverse " +
"string_to_reverse");
System.exit(1);
}
String stringToReverse=URLEncoder.encode(args[0]);
URL url = new URL(
"http://java.sun.com/cgi-bin/backwards");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);

Example contd.
PrintWriter out = new PrintWriter(
conn.getOutputStream());
out.println("string=" + stringToReverse);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}

Questions?

Das könnte Ihnen auch gefallen