1 / 39

Advanced Java Unit 3

Advanced Java Unit 3. CMSC 291 Shon Vick. Agenda. Look at URLs Summarize I/O Present some ideas about distributed computing in Java. URLs. Now lets look at URLs and which provide a relatively high-level mechanism for accessing resources on the Internet Client – uses some service

oriana
Download Presentation

Advanced Java Unit 3

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Advanced JavaUnit 3 CMSC 291 Shon Vick

  2. Agenda • Look at URLs • Summarize I/O • Present some ideas about distributed computing in Java

  3. URLs • 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

  4. Working 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

  5. Properties 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

  6. Constructing 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 • Consider the example in the text on pages 82-85

  7. The anatomy of a URL • A URL has two main components • Protocol identifier • Resource name

  8. The 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

  9. Sample Protocols • Hypertext Transfer Protocol (HTTP) • Usually used to serve up hypertext documents • Other protocols include • File Transfer Protocol FTP • Gopher, File, and News

  10. The 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

  11. More 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).

  12. Reading 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. Let’s see how to write to a URL and how to get results back.

  13. Reading • 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

  14. Creating 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.

  15. URL 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

  16. Creating 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: <a href="PicturesOfMe.html">Pictures of Me</a>

  17. Relative 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

  18. Other 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

  19. MalformedURLException • Each URL constructor throws a MalformedURLException • 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

  20. Specific 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; }

  21. Opening the URL String[] files = null; try { din = new DataInputStream(furl.openStream()); } catch( IOException e) { e.printStackTrace(); ch.addItem("No Items Available"); return ch; }

  22. Adding 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; }

  23. Another 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(); }

  24. Sample 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.

  25. Sending 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); }

  26. Goto 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: <applet code= GotoDemo width=300 height=200> <param name=“Goto" value=“www.gl.umbc.edu/432 > </applet> Tag

  27. Writing 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.

  28. The 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.

  29. Interacting 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.

  30. The 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

  31. Example 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 string=string_to_reverse, where string_to_reverse is the string whose characters you want displayed in reverse order.

  32. Some 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); }

  33. Creating 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/backwards"); URLConnection c = url.openConnection(); c.setDoOutput(true);

  34. Creating 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.getOutputStream());

  35. Doing 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();

  36. Read back the results BufferReader in = new BufferedReader( new InputStreamReader(c.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close();

  37. Output from example Reverse Me reversed is: eM esreveR

  38. For Next Time • Read Chapters 6 and 7 about distributed processing • Finish homework

  39. Selected References • Advanced Techniques for Java Developers Chapter 4 • http://java.sun.com/docs/books/tutorial/networking/urls/index.html • Exploring Java, O’Reilly, Niemeyer & Peck pgs.335-363 • http://userpages.umbc.edu/~vick/432/lectures/Fall98/UsingJava/Applets/MoreOnApplets.html

More Related