Misra’s blog

Archive for the ‘J2EE’ Category

Notes on Internationalization

Posted by mtwinkle on July 11, 2007

  • Set the charset of the page to an encoding that is supported by your target languages. I tend to use UTF-8 because it covers the most languages. The following meta declaration in a HTML/JSP page will set the content type:
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  • In the page JavaScript make sure to encode any parameters sent to the server. JavaScript provides the escape() function which returns Unicode escape strings in which localized text will appear in hexadecimal format. For more details on JavaScript encoding see Comparing escape(), encodeURI(), and encodeURIComponent().
  • On the server-side component set the character encoding using the HttpServletRequest.setCharacterEncoding() method. Before you access the localized parameter using the HttpServletRequest.getParameter() call. In the case of UTF this would be request.setCharactherEncoding("UTF-8");.

A server-side component returning AJAX responses needs to set the encoding of the response to the same encoding used in the page.

    response.setContentType("text/xml;charset=;UTF-8");
    response.getWriter().write("<response>invalid</response>");

Posted in J2EE | Leave a Comment »

What is 2-phase commit?

Posted by mtwinkle on July 11, 2007

A commit operation is an all-or-nothing affair. If a transaction cannot be completed, the rollback must restore the system to the pre-transaction state.

In order to ensure that a transaction can be rolled back, a software system typically logs each operation, including the commit operation itself. A recovery manager uses the log records to undo (and possibly redo) a partially completed transaction.

When a transaction involves multiple distributed resources, for example, a database server on two different network hosts, the commit process is somewhat complex because the transaction includes operations that span two distinct software systems, each with its own resource manager, log records, and so on.

With a two-phase commit protocol, the distributed transaction manager employs a coordinator to manage the individual resource managers.

The commit process proceeds as follows:

  • Phase 1
    • Each participating resource manager coordinates local operations and forces all log records out:
    • If successful, respond “OK”
    • If unsuccessful, either allow a time-out or respond “OOPS”
  • Phase 2
    • If all participants respond “OK”:
      • Coordinator instructs participating resource managers to “COMMIT”
      • Participants complete operation writing the log record for the commit
    • Otherwise:
      • Coordinator instructs participating resource managers to “ROLLBACK”
      • Participants complete their respective local undos

In order for the scheme to work reliably, both the coordinator and the participating resource managers independently must be able to guarantee proper completion, including any necessary restart/redo operations. The algorithms for guaranteeing success by handling failures at any stage are provided in advanced database texts.

Posted in J2EE | Leave a Comment »

JSF vs Struts

Posted by mtwinkle on July 10, 2007

http://jroller.com/page/dgeary?entry=top_ten_reasons_to_prefer

#10: There’s only one Struts

Struts is an open-source product, whereas JSF is a specification.

#9: JSF is the standard

JEE 5.0 containers must provide an implementation of JSF, which means that JSF will soon be ubiquitous.#8: POJO Action Methods

Struts actions are tied to the Struts API, but JSF action methods can be implemented in Plain Old Java Objects.
#7: Managed Beans

Like Spring, JSF uses dependency injection (or inversion of control, if you will), for instantiating and initializing beans. It’s true that Struts creates action beans and form beans for you, but JSF generalizes that concept and adds the ability to initialize managed beans—of any type—created by the framework.#6: Extensibility

This is huge. JSF has 6 objects that implement much of the framework’s capabilities and you can easily replace those objects by decorating the default implementations. That makes it ridiculously easy, for example, to add your own custom variables to the JSF expression language. It also makes it easy, for example, to plug in your own view handlers, perhaps a view handler that implements Tapestry-like views so you can truly separate components and HTML. In fact, Shale, does both of those things. As if that weren’t enough, JSF gives you numerous hooks into the JSF lifecycle to inject your own voodoo. Shale gives you even more.#5: Event Model

JSF has an event model that lets you react to value changes, actions, and phase changes in the JSF lifecycle.
#4: Value Bindings

With Struts, you are responsible for ferrying data from your forms to your model objects. You implement an action with an execute method that takes a form bean as an argument. Then you manually pull data out of that form bean and push it to your model. For every form in your application. Ugh. With JSF, you do this: #{model.property}. That’s all. JSF takes care of the rest.#3: Renderers

Have you ever looked at the source code for Struts tags? They generate HTML directly. JSF component tags, OTOH, don’t generate anything; instead, they refer to a component-renderer pair on the server. The component maintains state whereas the renderer is in charge of rendering a view. The point here is that renderers are pluggable: you can replace the default renderers with your own implementations; for example, in my Felix talk at NFJS, I illustrate how to implement a custom label renderer that adds asteriks to labels that represent required fields. You plug in that renderer, and JSF will automatically use it throughout your application. Sweet.#2: Render Kits

I had a Struts consulting job a few years ago where we had to support both a browser-based interface and radio frequency devices, and it was painful. That task would’ve been greatly simplified with JSF because you can create your own render kit—a collection of renderers for a particular display technology—and plug it into JSF.#1: Components

Components are the number one differentiator between Struts and JSF. Like Swing, JSF provides a rich infrastructure for developing components in addition to a standard set of components. That infrastructure makes it relatively easy to create your own components and share them with others. Already, we’re seeing custom components popping up all over the place, for example with Oracle’s ADF and MyFaces, both of which provide a rich set of components such as JavaScript-powered calendars, trees, etc. Of course, components are only half the story; typically, components delegate rendering to a separate renderer, which provides substantial benefits (see item #3 above). But, as with most things in JSF, you are not forced to adhere to the party line. If you want, you can implement components that render themselves, although if you do so, you will loose the ability to plug a different renderer into your component.

Posted in J2EE | 2 Comments »

SEAM

Posted by mtwinkle on July 10, 2007

The two core concepts in Seam are the notion of a context and the notion of a component. Components are stateful objects, usually EJBs, and an instance of a component is associated with a context, and given a name in that context.

A conversation is a unit of work from the point of view of the user. It might span several interactions with the user, several requests, and several database transactions. But to the user, a conversation solves a single problem. For example, “book hotel”, “approve contract”, “create order” are all conversations.

A conversation holds state associated with “what the user is doing now, in this window”. A single user may have multiple conversations in progress at any point in time, usually in multiple windows. The conversation context allows us to ensure that state from the different conversations does not collide and cause bugs.

The business process context holds state associated with the long running business process. This state is managed and made persistent by the BPM engine

Application context is mainly useful for holding static information such as configuration data, reference data or metamodels. For example, Seam stores its own configuration and metamodel in the application context.

we obtain components from a context via injection, and put component instances into a context via outjection.

Almost all seam components need a name. We assign a name to a component using the @Name annotation:

Posted in J2EE | Leave a Comment »

JSF notes

Posted by mtwinkle on July 8, 2007

jsfintro-lifecycle.gif

What is JSF and how is it useful?

JSR-127

FacesServlet is the Controller for the entire web application.

Every JSF page that contains JSF specific markup will begin with the <f:view> tag.

The faces-config.xml file is the heart of a JSF web application. In this file we define our Java Beans and our navigation rules.

JSF is a server side user interface component framework for Java based web apps.

One of the greatest advantages of JavaServer Faces technology is that it offers a clean separation between behavior and presentation.

JavaServer Faces technology provides a rich architecture for managing component state, processing component data, validating user input, and handling events.

For example, page authors with no programming expertise can use JavaServer Faces technology UI component tags to link to server-side objects from within a web page without writing any scripts.

Life Cycle of a JSF page

The life cycle of a JavaServer Faces page is similar to that of a JSP page: The client makes an HTTP request for the page, and the server responds with the page translated to HTML.

Click a hyperlink on an HTML page which opens a JSF page.

Request- non-Faces. Response – Faces

When a request for a JavaServer Faces page is made, such as when a link or a button is clicked, the JavaServer Faces implementation begins the restore view phase. During this phase, the JavaServer Faces implementation builds the view of the page, wires event handlers and validators to components in the view, and saves the view in the FacesContext instance. All the application’s component tags, event handlers, converters, and validators have access to the FacesContext instance.

After the component tree is restored, each component in the tree extracts its new value from the request parameters by using its decode method. The value is then stored locally on the component. If the conversion of the value fails, an error message associated with the component is generated and queued on FacesContext. This message will be displayed during the render response phase, along with any validation errors resulting from the process validations phase.

http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSFIntro10.html

 

Main advantage is that it’s going to be part of J2EE 5.0.

1. Makes it easy to construct a UI from a set of reusable UI components

2. Helps manage UI state across server requests

3. Allows custom UI components to be easily built and re-used

4. Simplifies migration of application data to and from the UI

Difference between Struts and JSF or Why would someone choose JSF over classic JSP and Struts?

Struts is a Controller Framework. There are pieces of it that operate as a View- like, HTML tags and Tiles library.

JSF is a View Framework. It provides a UI component model that enables a much richer component set and user interaction model.

What is JSF UI component?

A user interface control that outputs data to a client or allows a user to input data to a JSF application.

What is JSF conversion model?

A mechanism for converting between string-based markup generated by JSF UI components and server-side Java objects.

2. How to pass a parameter to the JSF application using the URL string?

http://your_server/your_app/product.jsf?id=777

FacesContext fc = FacesContext.getCurrentInstance();
String id = (String) fc.getExternalContext().getRequestParameterMap().get("id");

<h:outputText value="#{param['id']}" />

3. How to add context path to URL for outputLink?

<h:outputLink value="#{facesContext.externalContext.requestContextPath}/myPage.faces">

4. How to get current page URL from backing bean?

FacesContext fc = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest) fc.getExternalContext().getRequest()

 context.getViewRoot().getViewId();
will return you the name of the current JSP

5. How to access web.xml init parameters from java code?

You can get it using externalContext getInitParameter method.

<context-param>
 <param-name>connectionString</param-name>
 <param-value>jdbc:oracle:thin:scott/tiger@cartman:1521:O901DB</param-value>
</context-param>

FacesContext fc = FacesContext.getCurrentInstance();

String connection = fc.getExternalContext().getInitParameter("connectionString");



6. How to access web.xml init parameters from jsp page?

Product Id: <h:outputText value="#{initParam['productId']}"/>

7. How to terminate the session?

public String logout() {

  FacesContext fc = FacesContext.getCurrentInstance();
  HttpSession session = (HttpSessionfc.getExternalContext().getSession(false);
  session.invalidate();
  return "login_page";
}

<% session.invalidate(); %> <c:redirect url=”loginPage.jsf” />

8. How to implement “Please, Wait…” page?

9. How to reload the page after ValueChangeListener is invoked?

At the end of the ValueChangeListener, call FacesContext.getCurrentInstance().renderResponse()

10. How to download PDF file with JSF?

public void viewPdf(ActionEvent event) {
 String filename = "filename.pdf";

 // use your own method that reads file to the byte array
 byte[] pdf = getTheContentOfTheFile(filename)

 FacesContext faces = FacesContext.getCurrentInstance();
 HttpServletResponse response = (HttpServletResponsefaces.getExternalContext().getResponse();
 response.setContentType("application/pdf");
 response.setContentLength(pdf.length);
 response.setHeader"Content-disposition""inline; filename=\""+fileName+"\"");
 try {
  ServletOutputStream out;
  out = response.getOutputStream();
  out.write(pdf);
 catch (IOException e) {
  e.printStackTrace();
 }
 faces.responseComplete();
}

This is a jsp file snippet:

<h:commandButton immediate="true" actionListener="#{backingBean.viewPdf}" value="Read PDF" />

11. How to show Confirmation Dialog when user Click the Command Link?

12. What is the different between getRequestParameterMap() and getRequestParameterValuesMap()

13. Is it possible to have more than one Faces Configuration file?

Yes

14. How to mask actual URL to the JSF page?

15. How to print out html markup with h:outputText?

In case of <h:outputText escape=”false” value=”<b>This is a text</b>”/>

16. h:inputSecret field becomes empty when page is reloaded. How to fix this?

Set redisplay=true, it is false by default.

Posted in J2EE | 2 Comments »

Apache ANT

Posted by mtwinkle on April 13, 2007

ANT is a build tool.
Ant is extended using Java classes.
The configuration files are XML-based. Specifies a target tree where various tasks get executed. Each task is run by an object that implements a particular Task interface.

Download ANT from:
http://ant.apache.org/bindownload.cgi
Save & Extract it inside a folder on your local machine.

******************************
cls
echo off
echo Set up for ANT start……..
set ANT_HOME=D:\sun\ANT
set JAVA_HOME=C:\Program Files\Java\jdk1.5.0_06
set PATH=%PATH%;%ANT_HOME%\bin
echo Set up for ANT completed successsfully!!
******************************

Posted in J2EE | Leave a Comment »

Creating Web services using the J2EE 1.4

Posted by mtwinkle on April 13, 2007

http://java.sun.com/developer/technicalArticles/J2EE/j2ee_ws/
http://developers.sun.com/sw/building/codesamples/jax-rpc/
http://java.sun.com/webservices/interop/reference/tutorial/doc/Examples_glassfish6.html

1. Design and Code the Service Endpoint Interface
What is Endpoint interface?
Ans. In which you declare the methods that a web service remote client may invoke on the service.

Endpoint interface must:
* It extends the java.rmi.Remote interface
* It does not have constant declarations such as public static final
* Its methods throw the java.rmi.RemoteException (or one of its subclasses)
* Its method parameters and return data types are supported JAX-RPC types

2. Implement the Service Endpoint Interface

Steps:
1. Create folders D:\sun\AppServer\apps\build
2. apps directory contains the .java files, and the build directory contains the .class
Compile:
prompt> javac -d build Math*.java
The -d option instructs the compiler to write the output .class files into the build directory:
3. Write a Configuration File config.xml
This file tells “wscompile” to create a WSDL file with the following information:

* The service name is MyFirstService.
* The WSDL namespace is urn:Foo.
* The classes for the service are in the math package under the build directory.
* The service endpoint interface is math.MathFace.

Download jws-dp (Java web services developer pack)
http://java.sun.com/webservices/downloads/previous/webservicespack.jsp
/jaxrpc/bin/wscompile

Add the jaxrpc/bin directory to your PATH environment variable.
**************
cls
echo off
echo Set up for JAX-RPC start……..
set JAXRPC_HOME=C:\Program Files\tomcat50-jwsdp\jaxrpc\
set PATH=%PATH%;%JAXRPC_HOME%\bin
echo Set up for JAX-RPC completed successsfully!!
**************
D:\sun\AppServer\apps>
wscompile -define -mapping build/mapping.xml -d build -nd build -classpath build config.xml

Start Tomcat:
C:\Program Files\tomcat50-jwsdp\bin

Check if the sever started successfully:
http://localhost:8080/

Download SDK from
http://java.sun.com/javaee/downloads/index.jsp

WAR File Creation using deploytool
Start the DeployTool by running the deploytool.bat file from the /bin/

Posted in J2EE | Leave a Comment »

AJAX

Posted by mtwinkle on April 12, 2007

AJAX: Asynchronous Javascript and XML
Difference between Javascript and AJAX:
1a. Javascript had no way of sending information between the web browser and the web server.
Typical scenario –> Create a HTML form with some input fields and submit button. User enters the info and clicks submit. The information is sent to the server using ‘GET’ or ‘POST’, server responds, and then the results are displayed in the new page.

1b. In AJAX- Javascript communicate directly with the server, using a special Javascript object XMLHttpRequest.
No need of submit button to send the data to the server. Also, the whole page need not be refreshed and the result can be displayed on the same page itself.

The XMLHttpRequest object has a special property called onreadystatechange. onreadystatechange stores the function that will process the response from the server.
Every time the “ready state” changes this function will be executed.

What is this “ready state”?
The XMLHttpRequest object has another property called readyState. This is where the status of our server’s response is stored. The response can be processing, downloading or completed. Each time the readyState changes then our onreadystatechange function executes.
readyState is 4 that means the response is complete.

The property that stores the server’s response, responseText.

Quick Tip:
If you want to update a non form element, be sure to use the innerHTML attribute that is associated with all HTML elements. In our case we are updating a div every time a query is sent off. Also, remember that you can easily access an HTML element by giving it an id and using Javascript’s document.getElementById function.

Technologies used by AJAX:
1. Javascript-
2. DOM – for accessing and manipulating the structure of the HTML of the page
3. XML – represents the data passed between the server and client.
4. XMLHttpRequest – object for asynchronously exchanging the XML data between the client and the server.

Should I use an HTTP GET or POST for my AJAX calls?

AJAX requests should use an HTTP GET request when retrieving data where the data will not change for a given request URL. An HTTP POST should be used when state is updated on the server.

Posted in J2EE | Leave a Comment »

JMS

Posted by mtwinkle on July 7, 2006

Q. What is JMS?
Ans. Java Messaging service. It is asynchronous.

Q. Difference between JMS and RPC?
Ans. In RPC, the method invoker waits for the method to finish execution and return the control back to the invoker. i.e it is synchronous in nature.

In JMS, the message sender just sends the message to the destination and continues its own processing. It does not wait for the receiver to respond. i.e asynchronous.

Q. What are the advantages of JMS?
Ans. It is asynchronous in nature. Thus, not all the pieces need to be up all the time for the application to function as a whole. Even if the receiver is down, the MOM will store the messages and will send them once the receiver comes back up.

Q. Example of JMS products available.
Ans. IBM’s MQ series

Q. What are the different types of messages available in the JMS API?
Ans. Message, TextMessage, BytesMessage, StreamMessage, ObjectMessage, mapMessage

Q. Difference between Topic and Queue?
Ans.
Topic: Used for one to many messaging – Supports Publish-subscribe messaging- unreliable but fast
Queue: Used for one to one messaging – Supports Point to Point messaging – highly reliable

Q. Role of JMS in enterprise solution development?
Ans.
1. Enterprise application integration: Where a legacy application is integrated with a new application via messaging
2. B2B: Business can interact with each other via messaging because JMS allows organisations to co-operate without tightly coupling their business systems.
3. Geographically dispersed units: JMS can ensure safe exchange of data amongst the geographically dispersed units of any organisation.
4. One to many applications: The applications that have to push data in packet to huge number of clients in a one to many fashion are good candidate for the JMS use. eg. auction sites, stock quote services etc.

Posted in J2EE | 1 Comment »

UML

Posted by mtwinkle on July 7, 2006

Q. What is UML?
Ans. UML is a modelling language for visualizing, specifying and documenting the artifacts of a s/w intensive system.

Artifacts cover:
Requirements
- Use case diagrams – diagrammatic representation of System requirements. Represents ‘What’ the system will offer.
Architecture
- Component diagrams
- Deployment diagrams
Design
- Activity diagram
- Class diagram
- Collaboration diagram
- Sequence diagram
- State transition diagram
Prototypes
- Dialog designs

Q. Who are ‘Actors’?
Ans
1. Not part of the system but interact with it
2. Give inputs to the system
3. Receive output from the system
4. Could be human or non-human

Q. Difference b/w Aggregation and composition
Ans.

Q. What is a collaboration diagram?
Ans.

Posted in J2EE | Leave a Comment »