Showing posts with label advance java tutorial. Show all posts
Showing posts with label advance java tutorial. Show all posts

Wednesday, 4 January 2012

Creating a RESTful Web Service Reference

To utilize a RESTful Web service from your application, you must create a RESTful Web service reference.
To create a RESTful Web service reference:
  1. Navigate to the Web Service References page. See "Accessing the Web Service References Page".
  2. Click Create.
  3. Select REST and click Next.
  4. For REST Details, specify the following:
    1. Name - Enter a name to identify the reference.
    2. URL - Enter the URL endpoint of the Web service.
    3. Proxy - Enter a proxy to override the application proxy for this service (optional).
    4. HTTP Method - Choose the http method used for the request to the Web service. Select GET, HEAD, POST, PUT or DELETE.
    5. Basic Authentication - Select Yes to require HTTP Basic Authentication. Otherwise, select No.
    6. HTTP Headers - Enter the names of the HTTP headers to send with the request.
    7. Click Next.
  5. For REST Input parameters, specify the following:
    1. Name - Enter the name of the input parameter expected by the method.
    2. Type - Select the input type.
    3. Click Add Parameter.
    4. Repeat steps a though c for each expected input.
    5. Click Next.
  6. For REST Output parameters, specify the following:
    1. Output Format - Select XML or Text for the response format expected from the Web service.
    2. XPath to Output Parameters (XML only) - Enter an XPath expression to the relevant part of the response.
    3. Response Namespace (XML only) - Enter the namespace corresponding to the Response XPath.
    4. Parameter Delimiter (Text only)- Enter the character or sequence that separates parameters returned from the Web service. Use \n to indicate a new line and \t to indicate a tab character.
    5. New Record Delimiter (Text only) - Enter the character or sequence that determines a new record in a text response from the Web service. Use \nto indicate a new line and \t to indicate a tab character.
    6. Name - Enter the name of the output parameter returned by the method.
    7. Type - Select the output type.
    8. Click Add Parameter.
    9. Repeat steps f though h for each returned output parameter.
    Note:
    Click Test to send a request to a RESTful Web service and see the response. This test process will help you in specifying the appropriate Output parameters.
  7. Click Create.
The Create Web Service Reference Success page appears. The Web service reference is added to the Web Service References Repository.

Understanding Web Service References

To utilize Web services in Oracle Application Express, you create a Web service reference using a wizard. Web service references can be based on a Web Services Description Language (WSDL) document, RESTful style, or created manually by supplying information about the service.
When you create a Web service reference based on a WSDL, the wizard analyzes the WSDL and collects all the necessary information to create a valid SOAP message, including:
  • The URL used to post the SOAP request over HTTP(S)
  • A Universal Resource Identifier (URI) identifying the SOAP HTTP request
  • Operations of the Web Service
  • Input parameters for each operation
  • Output parameters for each operation
When you create a Web service reference manually, you supply the necessary information to create a valid SOAP request, including:
  • The URL used to post the SOAP request over HTTP(S)
  • A Universal Resource Identifier (URI) identifying the SOAP HTTP request
  • The SOAP envelope for the request, including any item substitutions
  • Optionally the name of a collection to store the response from the Web service
When you create a RESTful Web service reference, you supply the necessary information about the structure of the request and response including:
  • A Universal Resource Identifier (URI) identifying the RESTful request
  • The HTTP method identifying the method of the Web service
  • HTTP Headers, if required, that are part of the request
  • The type of input expected by the Web service
  • The format of the response and how to identify the response parameters

    Accessing the Web Service References Page

    You manage Web service references on the Web Service References page.
    To access the Web Service References page:
    1. On the Workspace home page, click the Application Builder icon.
    2. Select an application.
    3. Click Shared Components.
      The Shared Components page appears.
    4. Under Logic, click Web Service References.
      The Web Service References page appears.

    Specifying an Application Proxy Server Address

    If your environment requires a proxy server to access the Internet, you must specify a proxy server address on the Application Attributes page before you can create a Web service reference.
    To specify a proxy address for an application:
    1. On the Workspace home page, click the Application Builder icon.
    2. Select an application.
      Application home page appears.
    3. Click the Edit Application Properties button.
    4. Under Name, enter the proxy server in the Proxy Server field.
    5. Click Apply Changes.

Writing Java Class Based Web Services

Writing Java class based Web Services involves building a Java class that includes one or more methods. When a Web Services client makes a service request, Oracle Application Server Web Services invokes a Web Services Servlet that runs the method that implements the service request. There are very few restrictions on what actions Web Services can perform. At a minimum, Web Services generate some data that is sent to a client or perform an action as specified by a Web Service request.
This section shows how to write a stateful and a stateless Java Web Service that returns a string, "Hello World". The stateful service also returns an integer running count of the number of method calls to the service. This Java Web Service receives a client request and generates a response that is returned to the Web Service client.
The sample code is supplied on the Oracle Technology Network Web site,
http://otn.oracle.com/tech/java/oc4j/demos/1012/index.html
After expanding the Web Services demo.zip file, the Java class based Web Service is in the directory under webservices/demo/basic/java_services on UNIX or in\webservices\demo\basic\java_services on Windows.

Writing Stateless and Stateful Java Web Services

Oracle Application Server Web Services supports stateful and stateless implementations for Java classes running as Web Services, as follows:
  • For a stateful Java implementation, Oracle Application Server Web Services uses a single Java instance to serve the Web Service requests from an individual client.
  • For a stateless Java implementation, Oracle Application Server Web Services creates multiple instances of the Java class in a pool, any one of which may be used to service a request. After servicing the request, the object is returned to the pool for use by a subsequent request.

Defining a Java Class Containing Methods for the Web Service

Create a Java Web Service by writing or supplying a Java class with methods that are deployed as a Web Service. In the sample supplied in the java_services sample directory, the .ear file, ws_example.earcontains the Web Service source, class, and configuration files. In the expanded .ear file, the class StatefulExampleImpl provides the stateful Java service and StatelessExampleImpl provides the stateless Java service.
When writing a Java Web Service, if you want to place the Java service in a package, use the Java package specification to name the package. The first line of StatefulExampleImpl.java specifies the package name, as follows:
package oracle.j2ee.ws_example;

The stateless sample Web Service is implemented with StatelessExampleImpl, a public class. The class defines a public method, helloWorld(). In general, a Java class for a Web Service defines one or more public methods.
Example 3-1 shows StatelessExampleImpl.
The stateful sample Web Service is implemented with StatefulExampleImpl, a public class. The class initializes the count and defines two public methods, count() and helloWorld().
Example 3-2 shows StatefulExampleImpl.
Example 3-1 Defining A Public Class with Java Methods for a Stateless Web Service
package oracle.j2ee.ws_example;

public class StatelessExampleImpl {
    public StatelessExampleImpl() {
  }
  public String helloWorld(String param) {
    return "Hello World, " + param;
  }
}
Example 3-2 Defining a Public Class with Java Methods for a Stateful Web Service
package oracle.j2ee.ws_example;

public class StatefulExampleImpl {
  int count = 0;
  public StatefulExampleImpl() {
  }
  public int count() {
    return count++;
  }
  public String helloWorld(String param) {
    return "Hello World, " + param;
  }
}

A Java class implementation for a Web Service must include a public constructor that takes no arguments. Example 3-1 shows the public constructor StatelessExampleImpl() and Example 3-2 showsStatefulExampleImpl().
When an error occurs while running a Web Service implemented as a Java class, the Java class should throw an exception. When an exception is thrown, the Web Services Servlet returns a Web Services (SOAP) fault. Use the standard J2EE and OC4J administration facilities to view the logs of Servlet errors for a Web Service that uses Java classes for its implementation.
When you create a Java class containing methods that implement a Web Service, the method's parameters and return values must use supported types, or you need to use an interface class to limit the methods exposed to those methods using only supported types

Friday, 23 December 2011

XML-RPC Libraries

A lot of work has already gone into RPC, and more recently XML-RPC. Like using SAX, DOM, and JDOM for XML handling, there is no reason to reinvent the wheel when there are good, even exceptional, Java packages in existence for your desired purpose. The center for information about XML-RPC and links to libraries for Java as well as many other languages can be found at http://www.xmlrpc.com.
On Hannes's site is a description of the classes in his XML-RPC package and instructions. Download the archive file and expand the files into your development area or IDE. You should then be able to compile these classes; there is example servlets  that requires the servlet classes (servlet.jar for Servlet API 2.2). You can obtain these classes with the Tomcat servlet engine by pointing your web browser to http://jakarta.apache.org. If you do not wish to play with the servlet example, the servlet classes are not required for the programs in this chapter.
The core distribution (which does not include the applet or regular expression examples in the downloaded archive) is made up of thirteen classes, all in the helma.xmlrpc package. These are in a ready-to-use format in the lib/xmlrpc.jar file of the distribution. The classes within that distribution are detailed briefly in Table 11-1.

Table 11-1. The XML-RPC classes

ClassPurpose
XmlRpcCore class allowing method calls on handlers by an XML-RPC server.
XmlRpcClientClass for client to use for RPC communication over HTTP, including proxy and cookie support.
XmlRpcClientLiteClass for client to use when a less-featured HTTP client is needed (no cookies, proxy support).
XmlRpcServerClass for servers to use to receive RPC calls.
XmlRpcServletProvides the functionality of XmlRpcServer in a servlet format.
XmlRpcProxyServletActs as an XML-RPC servlet proxy.
XmlRpcHandlerBase interface for controlling XML-RPC interactions by handlers.
AuthenticatedXmlRpcHandlerSame as XmlRpcHandler, but allows for authentication.
Base64Encodes and decodes between bytes and base 64 encoding characters.
BenchmarkTimes roundtrip XML-RPC interactions for a specific SAX driver.
WebServerA lightweight HTTP server for use by XML-RPC servers.
The SAX classes (from earlier examples) and a SAX driver are not included in the distribution, but they are required for operation. In other words, you need a complete XML parser implementation that supports SAX. I continue to use Apache Xerces in these examples, although the libraries support any SAX 1.0-compatible driver.
Once you have all the source files compiled, ensure that the XML-RPC classes, SAX classes, and your XML parser classes are all in your environment's classpath. This should have you ready to write your own custom code and start the process of "saying hello." Keep the XML-RPC source files handy, as looking at what is going on under the hood can aid in your understanding of the examples.

What Is RPC?

 RPC is remote procedure calls. Where RMI lets you interoperate directly with a Java object, RPC is built in more of a dispatch fashion. Instead of dealing with objects, RPC lets you use standalone methods across a network. Although this limits interactivity, it does make for a slightly simpler interface to the client. You can think of RPC as a way to use "services" on remote machines, while RMI allows you to use "servers" on remote machines. The subtle difference is that RMI typically is driven entirely by the client, with events occurring when methods are invoked remotely. RPC is often built more as a class or set of classes that works to perform tasks with or without client intervention; however, at times these classes service requests from clients, and execute "mini" tasks for the clients. I will show you some examples shortly to clarify these definitions.
RPC, while not as interactive an environment as RMI, does offer some significant advantages. RPC allows disparate systems to work together. While RMI allows the use of IIOP for connecting Java to CORBA servers and clients, RPC allows literally any type of application intercommunication, because the transport protocol can be HTTP. Since virtually every language in use today has some means of communicating via HTTP, RPC is very attractive for programs that must connect to legacy systems. RPC is also typically more lightweight than RMI (particularly when using XML as the encoding, which I'll cover next); while RMI often has to load entire Java classes over the network (such as code for applets and custom helper classes for EJB), RPC only has to pass across the request parameters and the resulting response, generally encoded as textual data. RPC also fits very nicely into the API model, allowing systems that are not part of your specific application to still access information from your application. This means that changes to your server do not have to result in changes to other clients' application code; with pure textual data transfer and requests, additional methods can be added without client recompilation, and minor changes are sufficient to use these new methods.
The problem with RPC has traditionally been the encoding of data in transfer; imagine trying to represent a Java Hashtable or Vector in a very lightweight way through textual formats. When you consider that these structures can, in turn, hold other Java object types, the data representation quickly becomes tricky to write; it also has to remain a format that is usable by all the disparate programming languages, or the advantages of RPC are lessened. Until recently, an inverse relationship had been developing between the quality and usability of the encoding and its simplicity; in other words, the easier it became to represent complex objects, the more difficult it became to use the encoding in multiple programming languages without proprietary extensions and code. Elaborate textual representations of data were not standardized and required completely new implementations in every language to be usable. You can see where this discussion is leading.
See XML-RPC
Learn about What is RMI?

What Is RMI?

In short, RMI is remote method invocation. RMI allows a program to invoke methods on an object when the object is not located on the same machine as the program. This is at the heart of distributed computing in the Java world, and is the backbone of EJB as well as many enterprise application implementations. Without getting into too much detail, RMI uses client stubs to describe the methods a remote object has available for invocation. The client acts upon these stubs (which are Java interfaces), and RMI handles the "magic" of translating requests to a stub into a network call. This call invokes the method on the machine with the actual object, and then streams the result back across the network. Finally, the stub returns this result to the client that made the original method call, and the client moves on. The main idea is that the client doesn't typically worry about the RMI and network details; it uses the stub as if it were the actual object with implemented methods. RMI (using JRMPFigure 11.1.1, Java's remote protocol) makes all this network communication happen behind the scenes, allowing the client to deal with a generic exception (java.rmi.RemoteException) and spend more time handling business rules and application logic. RMI can also use different protocols such as Internet Inter-ORB Protocol (IIOP), allowing communication between Java and CORBA objects, often in different languages such as C or C++.
RMI carries a cost, though. First, using RMI is resource-intensive. JRMP provides very poor performance, and writing a remote protocol to replace it is not a simple task. As clients issue RMI calls, sockets must be opened and maintained, and the number of sockets can affect system performance, particularly when the system is accessible via a network (which then requires more sockets to be opened for HTTP access). RMI also requires a server or provider to bind objects to. Until an object is bound to a name on one of these providers, the object is not accessible to other programs. This requires using an RMI registry, a Lightweight Directory Access Protocol (LDAP) directory server, or a variety of other Java Naming and Directory Interface (JNDI) services. Finally, RMI can involve a lot of coding, even with all the helpful RMI server classes you get with the JDK; a remote interface describing the methods available to be invoked must be coded (as well as quite a few other interfaces if you are using EJB). This also means that adding an additional method to the server class results in a change to the interface and recompilation of the client stubs, something that is often not desirable and sometimes not possible.
Learn What is RPC?
See XML-RPC

Sunday, 18 December 2011

Using Scope Objects

Collaborating Web components share information via objects that are maintained as attributes of four scope objects. You access these attributes using the [get|set]Attribute methods of the class representing the scope. Table 11-4 lists the scope objects.
Table 11-4 Scope Objects 
Scope Object
Class
Accessible From
Web context
Web components within a Web context.
Session
Web components handling a request that belongs to the session.
Request
Web components handling the request.
Page
The JSP page that creates the object.

The Life Cycle of a JSP Page

A JSP page services requests as a servlet. Thus, the life cycle and many of the capabilities of JSP pages (in particular the dynamic aspects) are determined by Java Servlet technology.
When a request is mapped to a JSP page, it is handled by a special servlet that first checks whether the JSP page's servlet is older than the JSP page. If it is, it translates the JSP page into a servlet class and compiles the class. During development, one of the advantages of JSP pages over servlets is that the build process is performed automatically.

Translation and Compilation

During the translation phase, each type of data in a JSP page is treated differently. Template data is transformed into code that will emit the data into the stream that returns data to the client. JSP elements are treated as follows:
  • Directives are used to control how the Web container translates and executes the JSP page.
  • Scripting elements are inserted into the JSP page's servlet class.
  • Elements of the form <jsp:XXX ... /> are converted into method calls to JavaBeans components or invocations of the Java Servlet API.
For a JSP page named pageName, the source for a JSP page's servlet is kept in the file
J2EE_HOME/repository/host/web/
   context_root/_0002fpageName_jsp.java
 
For example, the source for the index page (named index.jsp) for the date localization example discussed at the beginning of the chapter would be named
J2EE_HOME/repository/host/web/date/_0002findex_jsp.java
 
Both the translation and compilation phases can yield errors that are only observed when the page is requested for the first time. If an error occurs while the page is being translated (for example, if the translator encounters a malformed JSP element), the server will return a ParseException, and the servlet class source file will be empty or incomplete. The last incomplete line will give a pointer to the incorrect JSP element.
If an error occurs while the JSP page is being compiled (for example, there is a syntax error in a scriptlet), the server will return a JasperException and a message that includes the name of the JSP page's servlet and the line where the error occurred.
Once the page has been translated and compiled, the JSP page's servlet for the most part follows the servlet life cycle described in the section Servlet Life Cycle:
  1. If an instance of the JSP page's servlet does not exist, the container:
    1. Loads the JSP page's servlet class
    2. Instantiates an instance of the servlet class
    3. Initializes the servlet instance by calling the jspInit method
  2. Invokes the _jspService method, passing a request and response object.
If the container needs to remove the JSP page's servlet, it calls the jspDestroy method.

Execution

You can control various JSP page execution parameters using by page directives. The directives that pertain to buffering output and handling errors are discussed here. Other directives are covered in the context of specific page authoring tasks throughout the chapter.

Buffering

When a JSP page is executed, output written to the response object is automatically buffered. You can set the size of the buffer with the following page directive:
<%@ page buffer="none|xxxkb" %>
 
A larger buffer allows more content to be written before anything is actually sent back to the client, thus providing the JSP page with more time to set appropriate status codes and headers or to forward to another Web resource. A smaller buffer decreases server memory load and allows the client to start receiving data more quickly.

Handling Errors

Any number of exceptions can arise when a JSP page is executed. To specify that the Web container should forward control to an error page if an exception occurs, include the following pagedirective at the beginning of your JSP page:
<%@ page errorPage="file_name" %>
 
The Duke's Bookstore application page initdestroy.jsp contains the directive
<%@ page errorPage="errorpage.jsp"%>
 
The beginning of errorpage.jsp indicates that it is serving as an error page with the following page directive:
<%@ page isErrorPage="true|false" %>
 
This directive makes the exception object (of type javax.servlet.jsp.JspException) available to the error page, so that you can retrieve, interpret, and possibly display information about the cause of the exception in the error page.

Note: You can also define error pages for the WAR that contains a JSP page. If error pages are defined for both the WAR and a JSP page, the JSP page's error page takes precedence.

Saturday, 17 December 2011

JSP Examples Tutorial - Using Abstract Classes in JSP


<HTML>
    <HEAD>
        <TITLE>Using Abstract Classes</TITLE>
    </HEAD>
    <BODY>
        <H1>Using Abstract Classes</H1>
        <%!
            javax.servlet.jsp.JspWriter localOut;
            abstract class a
            {
                abstract String getText() throws java.io.IOException;
                public void printem() throws java.io.IOException 
                {
                    localOut.println(getText());
                }
            }
            class b extends a
            {
                String getText() throws java.io.IOException 
                {
                    return "Hello from JSP!";
                }
            }
        %>     
        <%
            localOut = out;     
            b bObject = new b();
            bObject.printem();
        %>
    </BODY>
</HTML>

What Is a JSP Pages?


JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format, such as HTML, SVG, WML, and XML; and JSP elements, which construct dynamic content. A syntax card and reference for the JSP elements are available at:
http://java.sun.com/products/jsp/technical.html#syntax
The source code for this example is in the j2eetutorial/examples/src/web/date directory created when you unzip the tutorial bundle. The JSP page index.jsp used to create the form appears below; it is a typical mixture of static HTML markup and JSP elements. If you have developed Web pages, you are probably familiar with the HTML document structure statements (<head><body>, and so on) and the HTML statements that create a form (<form>) and a menu (<select>). The lines in bold in the example code contain the following types of JSP constructs:
  • Directives (<%@ page ... %>) import classes in the java.util package and the MyLocales class, and set the content type returned by the page.
  • The jsp:useBean element creates an object containing a collection of locales and initializes a variable that points to that object.
  • Scriptlets (<% ... %> ) retrieve the value of the locale request parameter, iterate over a collection of locale names, and conditionally insert HTML text into the output.
  • Expressions (<%= ... %>) insert the value of the locale name into the response.
  • The jsp:include element sends a request to another page (date.jsp) and includes the response in the response from the calling page.
    <%@ page import="java.util.*,MyLocales" %>
    <%@ page contentType="text/html; charset=ISO-8859-5" %>
    <html>
    <head><title>Localized Dates</title></head>
    <body bgcolor="white">
    <jsp:useBean id="locales" scope="application" 
       class="MyLocales"/>
    <form name="localeForm" action="index.jsp" method="post">
    <b>Locale:</b>
    <select name=locale>
    <% 
       String selectedLocale = request.getParameter("locale");
       Iterator i = locales.getLocaleNames().iterator();
       while (i.hasNext()) {
          String locale = (String)i.next();
          if (selectedLocale != null &&
             selectedLocale.equals(locale)) {
    %>
             <option selected><%=locale%></option>
    <%   
          } else { 
    %>
             <option><%=locale%></option>
    <%
          } 
       }
    %>
    </select>
    <input type="submit" name="Submit" value="Get Date">
    </form>
    <jsp:include page="date.jsp"/>
    </body>
    </html>
     
    
To build, deploy, and execute this JSP page:
  1. Go to j2eetutorial/examples and build the example by executing ant date.
  2. Create a J2EE application called DateApp.
    1. Select FileNewApplication.
    2. In the file chooser, navigate to j2eetutorial/examples/src/web/date.
    3. In the File Name field, enter DateApp.
    4. Click New Application.
    5. Click OK.
  3. Create the WAR and add the Web components to the DateApp application.
    1. Select FileNewWeb Component.
    2. Select DateApp from the Create New WAR File In Application combo box.
    3. Enter DateWAR in the WAR Display Name field.
    4. Click Edit.
    5. Navigate to j2eetutorial/examples/build/web/date. Select index.jspdate.jspMyDate.class, and MyLocales.class and click Add. Then click Finish.
    6. Click Next.
    7. Click JSP In The Web Component radio button, and then click Next.
    8. Select index.jsp from the JSP Filename combo box. Click Finish.
  4. Enter the context root.
    1. Select DateApp.
    2. Select the Web Context tab.
    3. Enter date.
  5. Deploy the application.
    1. Select ToolsDeploy.
    2. Click Finish.
  6. Invoke the URL http://<host>:8000/date in a browser.