Project Scenario for OpX. High-level Overview In the Test GUI Controller, opXController, for the opX command there is conceptually a call to an appropriate.

Slides:



Advertisements
Similar presentations
Chapter 6 Server-side Programming: Java Servlets
Advertisements

Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
Java Card Technology Ch07: Applet Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Computer Science & Engineering.
COMP 121 Week 5: Exceptions and Exception Handling.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause.
Exception Handling.  What are errors?  What does exception handling allow us to do?  Where are exceptions handled?  What does exception handling facilitate?
1 Lecture 4 Exception Handling. 2 Exception-Handling Fundamentals An exception is an abnormal condition that arises in a code sequence at run time A Java.
11-Jun-15 Exceptions. 2 Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
Advanced Java Class Network Programming. Network Protocols Overview Levels of Abstraction –HTTP protocol: spoken by Web Servers and Web Clients –TCP/IP:
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
Chapter 8 Overview – Learn to use try catch blocks – Learn to use streams – Learn to use text files.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L24 (Chapter 25) Networking.
1 Exception Handling (in a nutshell). 2 Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle the.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 25 Networking.
Chapter 10 Classes Continued
Advanced Java Course Exception Handling. Throwables Class Throwable has two subclasses: –Error So bad that you never even think about trying to catch.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Web Proxy Server. Proxy Server Introduction Returns status and error messages. Handles http CGI requests. –For more information about CGI please refer.
An program As a simple example of socket programming we can implement a program that sends to a remote site As a simple example of socket.
Java Software Solutions Foundations of Program Design Sixth Edition
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
CPSC 252 Exception Handling Page 1 Exceptions and exception handling Client programmers can make errors using a class attempting to dequeue an item from.
CIS 270—Application Development II Chapter 13—Exception Handling.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
Chapter 5 - Writing a Problem Domain Class Definition1 Chapter 5 Writing a Problem Domain Class Definition.
Application Protocols: HTTP CSNB534 Semester 2, 2007/2008 Asma Shakil.
16-Oct-15 JSP Implicit Objects. 2 JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer.
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Exceptions Handling Exceptionally Sticky Problems.
1 Streams Files are a computer’s long term memory Need ability for programs to –get information from files –copy information from program variables to.
Serialization. Serialization is the process of converting an object into an intermediate format that can be stored (e.g. in a file or transmitted across.
Sample Application Multi Layered Architecture (n-tier): –Graphical User Interface (GUI): Forms, components, controls The Visual Designer in Visual Studio.
Introduction to Exception Handling and Defensive Programming.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
Exception Handling Part 2: Creating and Throwing Exceptions CSIS 3701: Advanced Object Oriented Programming.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Li Tak Sing COMPS311F. Case study: consumers and producers A fixed size buffer which can hold at most certain integers. A number of producers which generate.
Creating PHPs to Insert, Update, and Delete Data CS 320.
1 Chapter 28 Networking. 2 Objectives F To comprehend socket-based communication in Java (§28.2). F To understand client/server computing (§28.2). F To.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
Java server pages. A JSP file basically contains HTML, but with embedded JSP tags with snippets of Java code inside them. A JSP file basically contains.
Server-side Programming The combination of –HTML –JavaScript –DOM is sometimes referred to as Dynamic HTML (DHTML) Web pages that include scripting are.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
JS (Java Servlets). Internet evolution [1] The internet Internet started of as a static content dispersal and delivery mechanism, where files residing.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
Exceptions and Assertions Chapter 15 – CSCI 1302.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
Architecture Multi Layered Architecture (n-tier): Application: Model Controllers Database Access Graphical User Interface (GUI): Forms, components, controls.
Creating a GUI Class An example of class design using inheritance and interfaces.
Chapter 6 - More About Problem Domain Classes1 Chapter 6 More About Problem Domain Classes.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Introduction to Exceptions in Java CS201, SW Development Methods.
111 State Management Beginning ASP.NET in C# and VB Chapter 4 Pages
Handling Exceptionally Sticky Problems
I/O Basics.
Chapter 14: Exception Handling
URL in Java C343 Lab (Week 13).
Handling Exceptionally Sticky Problems
Web APIs API = Application Programmer Interface
Presentation transcript:

Project Scenario for OpX

High-level Overview In the Test GUI Controller, opXController, for the opX command there is conceptually a call to an appropriate Class, C, of the form OpXResponseInfo opXResponse = C.opX(OpXRequest); Where OpXRequst is an instance of OpXRequestInfo. Then we show the response in the response window with IView.setResponse(opXResponse.toString());

Things to Understand First, things to do in the OpXController of the GUI is to get ready to make the call The class, C, is not on the same machine as the GUI. So, how do we call the operation across the internet? – We use a client and a server We call the opX command on the client communicator, CC. OpXResponseInfo opXResponse = CC.opX(opXRequest); The client communicator encodes the operation and its parameters (opXRequest) and sends them to the server. The server gets the operation and parameters (bundled in the object opXRequest) and decodes them. The server then calls C.opX(opXRequest) and gets a response, opXResponse, of type OpXResponseInfo

Getting Ready to make the call Get the parameters from the GUI – Use IView.getParameters() Use them to create an instance of OpXRequestInfo, opXRequest – I have a constructor whose single parameter is the output of IView.getParameters() OpXRequestInfo opXRequest = new OpXRequestInfo(Iview.getParameters) Get a string representation of the opXRequest – String stringRepresentation = opXRequest.toString(); Use IView.setRequst(stringRepresentation) to display the string in the GUI

Calling the opX operation across the Internet We use a client and a server – In the opXController we call the opX command in the client communicator, CC. OpXResponseInfo opXResponse = CC.OpX(OpXRequest); – The client communicator encodes the operation and its parameters (opXRequest) and sends them to the server. – The server gets the operation and parameters (bundled in the object opXRequest) and decodes them. – The server then makes the call we wanted to make in the first place OpXResponseInfo opXResponse = C.opX(opXRequest) – The server then encodes the response and sends it back to the client – The client communicator then decodes the response (opXResponse) as the return value for the method call made in the opXController.

The Client Communicator Design There exists one method for every operation opX. – OpXRequestInfo opX(OpXRequestInfo opXRequest) Each of the methods for the 7 commands are all most identical. We will take all of the common code and put it in its own method which we will call “doPost” If done well, the OpXResponseInfo opX(OpXRequestInfo) method becomes a one liner: return (OpXResponseInfo) doPost(opXName, opXRequest)

The “doPost” method First, set up the connection Encode the opXRequest and send it Handle any problems (the connection failed, the response is not OK, or the response is empty). Decode the response as an object and send it to the opX method that called “doPost”

Setting up the Connection Create a string representation of the address of the server – + opXName opXName is an input parameter to doPost Create a URL URL url = new URL(the string you just created) Create HttpURLConnection HttpURLConnection connection = (HttpURLConnection)url.open(); The HttpURLConnection class is in the Java library

Setting up the Connection (Continued) Set the request method type connection.setRequestMethod(“POST”); Indicate there will be information in the body of the request connection.setDoOutput(true); Now connect connection.connect();

Encoding and Sending using XStream Encode and store in the body of the request xStream.toXML(opXRequst, connection.getOutputStream()) – The opXRequest is a parameter to doPost – The xStream is an instance of XStream Send the request to the server connection.getOutputStream.close();

Handling the Response Get the response code connection.getResponseCode() Get the response length connection.getResponseLength() If everything is correct – Decode the response and store it in an object Object object = xStream.fromXML(connection.getInputStream) Return the object to the opX method that called doPost (the calling method then casts the object to the appropriate type)

Handling Errors Use a try/catch block Throw errors for – Response code not equal to HttpURLConnection.HTTP_OK – contentLength not equal to 0 – IOException Thrown when trying to connection or communicate

The Server Perspective Create a Server class containing a HttpServer we will call httpServer. When you set up the server – Initialize anything that you need For example, initialize the datebase – You may need to use the DataImporter to fill the Database – Create the HttpServer HttpServer httpServer = HttpServer.create(new InetSocketAddress(8080), 10) – Set the Executor httpServer.setExecutor(null) – Create the contexts for each command. For the opX command it might be httpServer.createContext(“/opX”, opXHandler); – There are 7 such commands – The name of the operation is the one appended to the end of the url string in the client » There is one context (“/”, fileTransfer) for the 8 th command. – The opXHandler is described on the next page – Start the server server.start()

Server Handlers Each of the handlers is an instance of a subClass of the library class HttpHandler abstract public HttpHandler { public HttpHandler(){} abstract void handle(HttpExchange exchange); } Create an HttpHandler for every operation opX. This is done in the Server class – Do this by subclassing HttpHandler, overloading the handle method, and creating an instance. This is best done using an anonymous inner class. – Assign it to a variable name of your choice which is the name used when creating a context (see previous slide) – Example private HttpHandler opXHandler = new HttpHandler() { public void handle(HttpExchange exchange) throws IOException { //see next slide }

The Body of every Handler Retrieve and decode the request OpXRequestInfo opXRequestInfo = (OpXRequestInfo)xStream.fromXML(exchange.getRequestBody()) The xStream is a variable in the Server class The exchange is the input parameter in the handle method getRequestBody() actually gets an InputStream Execute the operation on the appropriate class OpXResponseInfo opXResponse = C.opX(opXRequestInfo) Encode the response and send it back to the client communicator – First, set the headers Exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0); – Endcode and write the response to the response body xStream.toXML(opXResponse, exchange.getResponseBody()) getResponseBody actually returns an OutputStream – Send the response exchange.getResponseBody.close();

Handling Errors on the Server Side Wrap everything in try/catch block – Catch IOExceptions when creating the server – Catch any exceptions thrown when the operation in the model class is called If there is an error send and error response back exchange.sendResponseHeaders( HttpURLConnection.HTTP_INTERNAL_ERROR, -1) – You don’t have to write anything to the response body (using xStream.toXML) nor do you perform exchange.getResponseBody().close()

The opX operations in the Server This is up to you I use a single Class called Controller that has a method for each of the 8 commands Most of the logic should go here – Including error detection and reporting The database access classes should primarily by “getters” and “setters” – The may be of a higher level and thus not match one for one with sql commands on a table.

The 8 th Command FileDownload Command Differences – We don’t really use the “/opX” method of identifying the corresponding handler for file downloading You might consider httpServer.createContext(“/”, fileDownloader); – The fileDownloader doesn’t encode the response. It opens up the output file (an OutputStream) of the exchange It also opens the source file as an InputStream. It then copies the contents of the source file into the output stream of the exchange When finished, it closes the OutputStream.