Title: Advanced Java Unit 3
1Advanced JavaUnit 3
2Agenda
- Final Socket Notes
- Look at URLs
- Summarize I/O
- Present some ideas about distributed computing in
Java
3Avoiding Infinite Block
- If not properly constructed the Socket
constructor may block indefinitely - JDK 1.4 offers a solution
Socket (String host, int port) Socket s new
Socket() s.connect(new InetSocketAddress(host,por
t) , timeout)
Blocks waiting for host
Only waits timeout milisecs for host
4Thread Method
public final void join(long millis) throws
InterruptedException Waits at most millis
milliseconds for this thread to die. A timeout
of 0 means to wait forever. Parameters
millis - the time to wait in
milliseconds. Throws
InterruptedException - if another thread has
interrupted the current thread. The
interrupted status of the current
thread is cleared when this exception is thrown
5Older Version Workaround
Socket s null Thread t new Thread()
public void run( ) try s new
Socket(host, port) catch (IOException e)
t.start() try t.join(timeout) catch
(InterruptedException e)
6Half Close
Socket s new Socket(host,port) BufferedReade
r r new BufferedReader( new
InputStreamReader(s.getInputStream())) PrintWrite
r w new PrintWriter(s.getOutputStream(),
true) // send request data w.print(
.) s.shutdownOutput() // now socket is half
closed I.e open for input only String
line while ((line r.readLine()) ! null)
. . s.close()
Tells server that you are done
7URLs
- Now lets look at URLs and which provide a
relatively high-level mechanism for accessing
resources on the Internet - Client uses some service
- Server - provides some service
8Working with URLs
- URL is the acronym for Uniform Resource Locator
- It is a reference (an address) to a resource on
the Internet. - You provide URLs to your favorite Web browser so
that it can locate resources on the Internet
9Properties and Uses
- Java programs use a class called URL in the
java.net package to represent a URL address. - Applications
- You can use a URL to read in application data
- Have an applet load specific web pages by having
users specify a URL
10Constructing a URL
- Think of a URL as the name of a file on the Web
because most URLs refer to a file on some machine
on the network. - However, remember that URLs also can point to
other resources on the network, such as database
queries and other data
11The anatomy of a URL
- A URL has two main components
- Protocol identifier
- Resource name
12The anatomy of a URL
- The protocol identifier and the resource name are
separated by a colon and two forward slashes. - The protocol identifier indicates the name of the
protocol to be used to fetch the resource
13Sample Protocols
- Hypertext Transfer Protocol (HTTP)
- Usually used to serve up hypertext documents
- Other protocols include
- File Transfer Protocol FTP
- Gopher, File, and News
14The anatomy of a Resource name
- The format of the resource name depends entirely
on the protocol used, but for many protocols
including HTTP, the resource name contains these
components - Host Name The name of the machine on which the
resource lives. - Filename The pathname to the file on the machine
15More Components of the Anatomy
- Host Name The name of the machine on which the
resource lives. - Filename The pathname to the file on the machine
(sometimes implied I.e with index.html) - Port Number The port number to which to connect
(typically optional). - Reference A named anchor within a resource that
usually identifies a specific location within a
file (typically optional).
16Reading from and Writing to a URLConnection
- Some URLs, such as many that are connected to
cgi-bin scripts, allow you to (or even require
you to) write information to the URL - Example
- A search script may require detailed query data
to be written to the URL before the search can be
performed. Lets see how to write to a URL and
how to get results back.
17Reading
- You can read and write to a URL
- First we will look at simple examples using the
URL class then we will look at examples involving
the http centric URLConnection class
18Creating a URL
- Within your Java programs, you can create a URL
object that represents a URL address - The URL object always refers to an absolute URL
but can be constructed from an absolute URL, a
relative URL, or from URL components.
19URL Example
- The easiest way to create a URL object is from a
String that represents the human-readable form of
the URL address. - Example
- http//heaven.org/apply.html
20Creating a URL Relative to Another
- A relative URL contains only enough information
to reach the resource relative to (or in the
context of) another URL - Consider a html file named JoesHomePage.html
(http//www.JoesPlace.com/JoesHomePage.html ) - Within this page there arelinks to other pages
- lta href"PicturesOfMe.html"gtPictures of Melt/agt
21Relative URLs
- General Form
- new URL(URL baseURL, String relativeURL)
- URL Joes
- new URL (http//www.JoesPlace.com/
) - URLPix
- new URL (Joes, PicturesOfMe.html)
Base
Relative
22Other Constructs
- public URL(String protocol, String host,
- int port, String file)
- throws MalformedURLException
- public URL(String url)
- throws MalformedURLException
- public URL(String host, String file)
- throws MalformedURLException
23MalformedURLException
- Each URL constructor throws a MalformedURLExceptio
n - Java does not verify to throw this exception it
only checks URL specification form - try
- URL myURL new URL(. . .)
- catch (MalformedURLException e)
- . . .
- // exception handler code here
- . . .
-
Good idea to catch error and deal with the error
immediately
24Specific Example From Book
public Choice setChoiceList() Choice ch new
Choice() URL furl null DataInputStream
din null String buf ch.addItem("Pick
One") try furl new URL(getDocumentBase(
) "resources.html") catch
(MalformedURLException e)
e.printStackTrace() ch.addItem("No Items
Available") return ch
25Opening the URL
String files null try din new
DataInputStream(furl.openStream())
catch( IOException e)
e.printStackTrace() ch.addItem("No Items
Available") return ch
26Adding the Choices
try while((buf din.readLine()) ! null)
ch.addItem(buf) din.close()
catch(IOException e)
e.printStackTrace() ch.addItem("No Items
Available") return ch return
ch
27Another example
import java.net. import java.io.
public class URLReader
public static void main(String args) throws
Exception URL yahoo new
URL("http//www.yahoo.com/")
BufferedReader in new BufferedReader(
new
InputStreamReader(
yahoo.openStream()))
String inputLine while
((inputLine in.readLine()) ! null)
System.out.println(inputLine)
in.close()
28Sample Explanation
- When you run the program, you should see,
scrolling by in your command window, the HTML
commands and textual content from the HTML file
located at http//www.yahoo.com/ - Alternatively, the program might hang or you
might see an exception stack trace.
29Sending your Applet to a URL
... String name getParameter("Goto")
try gotoURL new URL(name) catch
(MalformedURLException e) // remember to
handle errors! ... public boolean
mouseDown(Event e, int x, int y)
getAppletContext().showDocument(gotoURL)
return(true)
30Goto Example
- Enable a browser to goto Web location
- You can dynamically link providing live content
with a very small amount of code - Of course you will have to add an applet tag
ltapplet code GotoDemo width300 height200gt
ltparam nameGoto" valuewww.gl.umbc.edu/432 gt
lt/appletgt
Tag
31Writing to a URLConnection
- Many HTML pages contain forms-- text fields and
other GUI objects that let you enter data to send
to the server - After you type in the required information and
initiate the query by clicking a button, your Web
browser writes the data to the URL over the
network.
32The Other End
- At the other end, a cgi-bin script (usually) on
the server receives the data, processes it, and
then sends you a response, usually in the form of
a new HTML page. - Many cgi-bin scripts use the POST METHOD for
reading the data from the client. Thus writing to
a URL is often called posting to a URL.
Server-side scripts use the POST METHOD to read
from their standard input.
33Interacting With cgi-bin scripts
- A Java program can interact with cgi-bin scripts
also on the server side. It simply must be able
to write to a URL, thus providing data to the
server. - It can do this by following a few relatively
steps.
34The steps
- .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
35Example Explanation
- Say The script at our Web site reads a string
from its standard input, reverses the string, and
writes the result to its standard output. - The script requires input of the form
stringstring_to_reverse, where string_to_reverse
is the string whose characters you want displayed
in reverse order.
36Some Sanity checking
import java.io. import
java.net. 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) .
37Creating the URL
- Next, the program creates the URL object--the URL
for the backwards script
URL url new URL("http//java.sun.com/cgi-bin/bac
kwards") URLConnection c
url.openConnection()
c.setDoOutput(true)
38Creating the a Writer
- The program then creates an output stream on the
connection and opens a PrintWriter on it. - If the URL does not support output,
getOutputStream method throws an
UnknownServiceException. - If the URL does support output, then this method
returns an output stream that is connected to the
standard input stream of the URL on the server
side--the client's output is the server's input
PrintWriter out new PrintWriter(c.getOutputStrea
m())
39Doing the Writing
- Next, the program writes the required information
to the output stream and closes the stream. - This code writes to the output stream using the
println method - just like writing data to a
stream. - The data written to the output stream on the
client side is the input for the backwards script
on the server side.
out.println("string" stringToReverse)
out.close()
40Read back the results
- BufferReader in new BufferedReader(
- new
InputStreamReader(c.getInputStream())) - String inputLine
- while ((inputLine in.readLine()) !
null) - System.out.println(inputLine)
- in.close()
41Output from example
Reverse Me reversed is eM esreveR
42Convenience methods
- getDate
- getExpiration
- getLastModified
- getContentLength
- getContentType
- getContentEncoding
43Selected References
- Advanced Techniques for Java Developers Chapter
4 - http//java.sun.com/docs/books/tutorial/networking
/urls/index.html - Exploring Java, OReilly, Niemeyer Peck
pgs.335-363 - http//userpages.umbc.edu/vick/432/lectures/Fall9
8/UsingJava/Applets/MoreOnApplets.html