Spring is an open-source framework, created by Rod Johnson and described in his book Expert One-on-One: J2EE Design and Development.1 It was created to address the complexity of enterprise application development. Spring makes it possible to use plain-vanilla JavaBeans to achieve things that were previously only possible with EJBs. However, Spring’s usefulness isn’t limited to server-side development. Any Java application can benefit from Spring in terms of simplicity, testability, and loose coupling.
■ Lightweight—Spring is lightweight in terms of both size and overhead.
■ Inversion of control—Spring promotes loose coupling through a technique known as inversion of control (IoC). When IoC is applied, objects are passively given their dependencies instead of creating or looking for dependent objects for themselves. You can think of IoC as JNDI in reverse— instead of an object looking up dependencies from a container, the container
gives the dependencies to the object at instantiation without waiting to be asked.
■ Aspect-oriented—Spring comes with rich support for aspect-oriented programming that enables cohesive development by separating application business logic from system services (such as auditing and transaction management). Application objects do what they’re supposed to do—perform business logic—and nothing more.
■ Container—Spring is a container in the sense that it contains and manages the life cycle and configuration of application objects. You can configure how your each of your beans should be created—either create one single instance of your bean or produce a new instance every time one is needed based on a configurable prototype—and how they should be associated with each other.
■ Framework—Spring makes it possible to configure and compose complex applications from simpler components. In Spring, application objects are composed declaratively, typically in an XML file. Spring also provides much infrastructure functionality (transaction management, persistence framework integration, etc.), leaving the development of application logic to you.
May 18, 2007
Definition of Service-Oriented Architecture

A Service-Oriented Architecture (SOA) is a software architecture that is based on the key concepts of an application frontend, service, service repository, and service bus. A service consists of a contract, one or more interfaces, and an implementation.
APPLICATION FRONTENDS
Application frontends are the active players of an SOA. They initiate and control all activity of the enterprise systems.
It is always an application frontend that initiates a business process and receives the results.
SERVICES
A service is a software component of distinctive functional meaning that typically encapsulates a high-level business concept. It consists of several parts:
Contract. The service contract provides an informal specification of the purpose, functionality, constraints, and usage of the service. The form of this specification can vary, depending on the type of service. One non-mandatory element of the service contract is a formal interface definition based on languages such as IDL or WSDL.
Interface. The functionality of the service is exposed by the service interface to clients that are connected to the service using a network. Although the description of the interface is part of the service contract, the physical implementation of the interface consists of service stubs, which are incorporated into the clients[3] of a service and dispatcher.
Implementation. The service implementation physically provides the required business logic and appropriate data. It is the technical realization that fulfills the service contract. The service implementation consists of one or more artifacts such as programs, configuration data, and databases.
Business logic. The business logic that is encapsulated by a service is part of its implementation. It is made available through service interfaces. However, programming against interfaces is desirable, whether or not one applies a service-oriented approach.
Data. A service can also include data.

SERVICE REPOSITORY
A service repository provides facilities to discover services and acquire all information to use the services, particularly if these services must be discovered outside the functional and temporal scope of the project that created them. Although much of the required information is already part of the service contract, the service repository can provide additional information, such as physical location, information about the provider, contact persons, usage fees, technical constraints, security issues, and available service levels.

SERVICE BUS
A service bus connects all participants of an SOAservices and application frontendswith each other. If two participants need to communicatefor example, if an application frontend needs to invoke some functionality of a basic servicethe service bus makes it happen. In this respect, the service bus is similar to the concept of a software bus as it is defined in the context of CORBA. However, significant differences exist between these concepts. Most importantly, the service bus is not necessarily composed of a single technology, but rather comprises a variety of products and concepts.
Software Architecture
A software architecture is a set of statements that describe software components and assigns the functionality of the system to these components. It describes the technical structure, constraints, and characteristics of the components and the interfaces between them. The architecture is the blueprint for the system and therefore the implicit high-level plan for its construction.
(Enterprise SOA: Service-Oriented Architecture Best Practices)
(Enterprise SOA: Service-Oriented Architecture Best Practices)
May 16, 2007
Solving the error EJB with JBoss 4.04
Solved it with the following 3 steps:
1] Edit conf/jboss-service.xml and make CallByValue as 'true' in NamingService as below
name="jboss:service=Naming"
xmbean-dd="resource:xmdesc/NamingService-xmbean.xml">
true
2] Edit deploy/ear-deployer.xml, and set Isloated and CallByValue as true
3]Edit deploy\jbossweb-tomcat55.sar\META-INF\jboss-service.xml , and set Java2ClassLoadingCompilance and UseJbossWebLoader attributes as false
1] Edit conf/jboss-service.xml and make CallByValue as 'true' in NamingService as below
xmbean-dd="resource:xmdesc/NamingService-xmbean.xml">
true
2] Edit deploy/ear-deployer.xml, and set Isloated and CallByValue as true
3]Edit deploy\jbossweb-tomcat55.sar\META-INF\jboss-service.xml , and set Java2ClassLoadingCompilance and UseJbossWebLoader attributes as false
May 15, 2007
What is difference between Application server with Web server
A web server is a server designed to communicate with a web browser. Content includes text-based two-way communication with most of the com going from server to client. Data consists of text, formatting, graphics, sounds, and dynamic content.
An application server can be of several designs, but is basically a synchronous two-way sever that provides access to a single application shared among users through web-based or proprietiary methods. The content consists of data types, app commands, system commands, and data of complex types.
Typically, an app server provides a web-based platform for access to a database-driven application.
An application server can be of several designs, but is basically a synchronous two-way sever that provides access to a single application shared among users through web-based or proprietiary methods. The content consists of data types, app commands, system commands, and data of complex types.
Typically, an app server provides a web-based platform for access to a database-driven application.
Apr 25, 2007
Auto-encodes session IDs in URL
Blarg #22: A Filter that auto-encodes session IDs on relative page links.
Posted by jfalkner on March 27, 2006 at 10:43 PM | Comments (3)
This is an example Filter that auto-encodes all relative links on a website using the HttpServletResponse.encodeURL() method. It was originally encoded as an example during a Develop Mentor course I taught. It is a nice example of a servlet filter that buffers a response, locates links using a simple regular expression, and replaces links with encoded links.
The code. Remember each filter has three parts: the Filter, ServletResponseWrapper, and ServletOutputStream sub-class.
* EncodeSessionInURLFilter.java
* EncodeSessionInURLResponseWrapper.java
* EncodeSessionInURLResponseStream.java
EncodeSessionInURLFilter.java
This filter does nothing more than wraps the HttpServletResponse in order to buffer text sent out to a client.
package example;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class EncodeSessionInURLFilter implements Filter {
ServletContext sc = null;
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
// check that it is a HTTP request
if (req instanceof HttpServletRequest) {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
// nonce encode the normal output
EncodeSessionInURLResponseWrapper wrappedResponse = new EncodeSessionInURLResponseWrapper(
response, sc);
// make sure a session exists
HttpSession session = request.getSession(true);
chain.doFilter(req, wrappedResponse);
// finish the respone
wrappedResponse.finishResponse();
}
}
public void init(FilterConfig filterConfig) {
// reference the context
sc = filterConfig.getServletContext();
}
public void destroy() {
// noop
}
}
EncodeSessionInURLResponseWrapper.java
This wrapper sends back a custom ServletOutputStream object in order to buffer all text that is being sent to the client.
package example;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class EncodeSessionInURLResponseWrapper extends HttpServletResponseWrapper {
protected HttpServletResponse origResponse = null;
protected ServletOutputStream stream = null;
protected PrintWriter writer = null;
ServletContext sc;
public EncodeSessionInURLResponseWrapper(HttpServletResponse response, ServletContext sc) {
super(response);
this.sc = sc;
origResponse = response;
}
public ServletOutputStream createOutputStream() throws IOException {
return (new EncodeSessionInURLResponseStream(origResponse, sc));
}
public void finishResponse() {
try {
if (writer != null) {
writer.close();
} else {
if (stream != null) {
stream.close();
}
}
} catch (IOException e) {}
}
public void flushBuffer() throws IOException {
stream.flush();
}
public ServletOutputStream getOutputStream() throws IOException {
if (writer != null) {
throw new IllegalStateException("getWriter() has already been called!");
}
if (stream == null)
stream = createOutputStream();
return (stream);
}
public PrintWriter getWriter() throws IOException {
if (writer != null) {
return (writer);
}
if (stream != null) {
throw new IllegalStateException("getOutputStream() has already been called!");
}
stream = createOutputStream();
// BUG FIX 2003-12-01 Reuse content's encoding, don't assume UTF-8
writer = new PrintWriter(new OutputStreamWriter(stream, origResponse.getCharacterEncoding()));
return (writer);
}
public void setContentLength(int length) {}
}
EncodeSessionInURLResponseStream.java
This response stream buffers all text that is send to the client and uses a regular expression to locate and replace links with encoded links.
package example;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.*;
import javax.servlet.http.*;
/**
*
* @author Jayson Falkner - jayson@jspinsider.com
*/
public class EncodeSessionInURLResponseStream extends ServletOutputStream {
// abstraction of the output stream used for compression
protected OutputStream bufferedOutput = null;
// state keeping variable for if close() has been called
protected boolean closed = false;
// reference to original response
protected HttpServletResponse response = null;
// reference to the output stream to the client's browser
protected ServletOutputStream output = null;
// default size of the in-memory buffer
private int bufferSize = 50000;
ServletContext sc;
public EncodeSessionInURLResponseStream(HttpServletResponse response, ServletContext sc) throws IOException {
super();
closed = false;
this.sc = sc;
this.response = response;
this.output = response.getOutputStream();
bufferedOutput = new ByteArrayOutputStream();
}
public void close() throws IOException {
// make up a nonce
String nonce = Integer.toString((int)(Math.random()*Integer.MAX_VALUE));
// set the nonce in app scope
sc.setAttribute("nonce", nonce);
// get the content
ByteArrayOutputStream baos = (ByteArrayOutputStream) bufferedOutput;
// make a string out of the response
String pageText = new String(baos.toByteArray());
// use regex to find the links
Pattern p = Pattern.compile(" href=\"[^\"]*|action=\"[^\"]*");
Matcher m = p.matcher(pageText);
String newText = "";
int offset = 0;
while (m.find(offset)) {
// update the text
newText += pageText.substring(offset, m.start());
// update the offset
offset = m.end();
// get the matching string
String match = pageText.substring(m.start(), m.end());
// get the URL
String[] split = match.split("\"");
String url = split[1];
// encode the match
String encoded = response.encodeURL(url);
// add the match to the new text
newText += split[0]+"\""+encoded;
}
// add the final text
newText += pageText.substring(offset, pageText.length());
// set appropriate HTTP headers
// response.setContentLength(compressedBytes.length);
output.write(newText.getBytes());
output.flush();
output.close();
closed = true;
}
public void flush() throws IOException {
if (closed) {
throw new IOException("Cannot flush a closed output stream");
}
bufferedOutput.flush();
}
public void write(int b) throws IOException {
if (closed) {
throw new IOException("Cannot write to a closed output stream");
}
// write the byte to the temporary output
bufferedOutput.write((byte) b);
}
public void write(byte b[]) throws IOException {
write(b, 0, b.length);
}
public void write(byte b[], int off, int len) throws IOException {
System.out.println("writing...");
if (closed) {
throw new IOException("Cannot write to a closed output stream");
}
// write the content to the buffer
bufferedOutput.write(b, off, len);
}
public boolean closed() {
return (this.closed);
}
public void reset() {
//noop
}
}
in web.xml
<filter>
<filter-name>CookieSessionFilter</filter-name>
<filter-class> net.kokolink.zimbra.controller.EncodeSessionInURLFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CookieSessionFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
Posted by jfalkner on March 27, 2006 at 10:43 PM | Comments (3)
This is an example Filter that auto-encodes all relative links on a website using the HttpServletResponse.encodeURL() method. It was originally encoded as an example during a Develop Mentor course I taught. It is a nice example of a servlet filter that buffers a response, locates links using a simple regular expression, and replaces links with encoded links.
The code. Remember each filter has three parts: the Filter, ServletResponseWrapper, and ServletOutputStream sub-class.
* EncodeSessionInURLFilter.java
* EncodeSessionInURLResponseWrapper.java
* EncodeSessionInURLResponseStream.java
EncodeSessionInURLFilter.java
This filter does nothing more than wraps the HttpServletResponse in order to buffer text sent out to a client.
package example;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class EncodeSessionInURLFilter implements Filter {
ServletContext sc = null;
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
// check that it is a HTTP request
if (req instanceof HttpServletRequest) {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
// nonce encode the normal output
EncodeSessionInURLResponseWrapper wrappedResponse = new EncodeSessionInURLResponseWrapper(
response, sc);
// make sure a session exists
HttpSession session = request.getSession(true);
chain.doFilter(req, wrappedResponse);
// finish the respone
wrappedResponse.finishResponse();
}
}
public void init(FilterConfig filterConfig) {
// reference the context
sc = filterConfig.getServletContext();
}
public void destroy() {
// noop
}
}
EncodeSessionInURLResponseWrapper.java
This wrapper sends back a custom ServletOutputStream object in order to buffer all text that is being sent to the client.
package example;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class EncodeSessionInURLResponseWrapper extends HttpServletResponseWrapper {
protected HttpServletResponse origResponse = null;
protected ServletOutputStream stream = null;
protected PrintWriter writer = null;
ServletContext sc;
public EncodeSessionInURLResponseWrapper(HttpServletResponse response, ServletContext sc) {
super(response);
this.sc = sc;
origResponse = response;
}
public ServletOutputStream createOutputStream() throws IOException {
return (new EncodeSessionInURLResponseStream(origResponse, sc));
}
public void finishResponse() {
try {
if (writer != null) {
writer.close();
} else {
if (stream != null) {
stream.close();
}
}
} catch (IOException e) {}
}
public void flushBuffer() throws IOException {
stream.flush();
}
public ServletOutputStream getOutputStream() throws IOException {
if (writer != null) {
throw new IllegalStateException("getWriter() has already been called!");
}
if (stream == null)
stream = createOutputStream();
return (stream);
}
public PrintWriter getWriter() throws IOException {
if (writer != null) {
return (writer);
}
if (stream != null) {
throw new IllegalStateException("getOutputStream() has already been called!");
}
stream = createOutputStream();
// BUG FIX 2003-12-01 Reuse content's encoding, don't assume UTF-8
writer = new PrintWriter(new OutputStreamWriter(stream, origResponse.getCharacterEncoding()));
return (writer);
}
public void setContentLength(int length) {}
}
EncodeSessionInURLResponseStream.java
This response stream buffers all text that is send to the client and uses a regular expression to locate and replace links with encoded links.
package example;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.*;
import javax.servlet.http.*;
/**
*
* @author Jayson Falkner - jayson@jspinsider.com
*/
public class EncodeSessionInURLResponseStream extends ServletOutputStream {
// abstraction of the output stream used for compression
protected OutputStream bufferedOutput = null;
// state keeping variable for if close() has been called
protected boolean closed = false;
// reference to original response
protected HttpServletResponse response = null;
// reference to the output stream to the client's browser
protected ServletOutputStream output = null;
// default size of the in-memory buffer
private int bufferSize = 50000;
ServletContext sc;
public EncodeSessionInURLResponseStream(HttpServletResponse response, ServletContext sc) throws IOException {
super();
closed = false;
this.sc = sc;
this.response = response;
this.output = response.getOutputStream();
bufferedOutput = new ByteArrayOutputStream();
}
public void close() throws IOException {
// make up a nonce
String nonce = Integer.toString((int)(Math.random()*Integer.MAX_VALUE));
// set the nonce in app scope
sc.setAttribute("nonce", nonce);
// get the content
ByteArrayOutputStream baos = (ByteArrayOutputStream) bufferedOutput;
// make a string out of the response
String pageText = new String(baos.toByteArray());
// use regex to find the links
Pattern p = Pattern.compile(" href=\"[^\"]*|action=\"[^\"]*");
Matcher m = p.matcher(pageText);
String newText = "";
int offset = 0;
while (m.find(offset)) {
// update the text
newText += pageText.substring(offset, m.start());
// update the offset
offset = m.end();
// get the matching string
String match = pageText.substring(m.start(), m.end());
// get the URL
String[] split = match.split("\"");
String url = split[1];
// encode the match
String encoded = response.encodeURL(url);
// add the match to the new text
newText += split[0]+"\""+encoded;
}
// add the final text
newText += pageText.substring(offset, pageText.length());
// set appropriate HTTP headers
// response.setContentLength(compressedBytes.length);
output.write(newText.getBytes());
output.flush();
output.close();
closed = true;
}
public void flush() throws IOException {
if (closed) {
throw new IOException("Cannot flush a closed output stream");
}
bufferedOutput.flush();
}
public void write(int b) throws IOException {
if (closed) {
throw new IOException("Cannot write to a closed output stream");
}
// write the byte to the temporary output
bufferedOutput.write((byte) b);
}
public void write(byte b[]) throws IOException {
write(b, 0, b.length);
}
public void write(byte b[], int off, int len) throws IOException {
System.out.println("writing...");
if (closed) {
throw new IOException("Cannot write to a closed output stream");
}
// write the content to the buffer
bufferedOutput.write(b, off, len);
}
public boolean closed() {
return (this.closed);
}
public void reset() {
//noop
}
}
in web.xml
<filter>
<filter-name>CookieSessionFilter</filter-name>
<filter-class> net.kokolink.zimbra.controller.EncodeSessionInURLFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CookieSessionFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
Apr 24, 2007
Handle duplicate form submission
Handle duplicate form submission
The problem of duplicate form submission arises when a user clicks the Submit button more than once before the response is sent back or when a client accesses a view by returning to a previously bookmarked page. This may result in inconsistent transactions and must be avoided. In our sample application, a similar problem will arise if the customer clicks the submit button more than once while submitting the purchase order.
In Struts this problem can be handled by using the saveToken() and isTokenValid() methods of Action class. saveToken() method creates a token (a unique string) and saves that in the user's current session, while isTokenValid() checks if the token stored in the user's current session is the same as that was passed as the request parameter.
To do this the JSP has to be loaded through an Action. Before loading the JSP call saveToken() to save the token in the user session. When the form is submitted, check the token against that in the session by calling isTokenValid(), as shown in the following code snippet:
Listing 3: Using saveToken() and isTokenValid()
public class PurchaseOrderAction extends DispatchAction
{
public ActionForward load(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception
{
try
{ //save the token
saveToken(request)
// rest of the code for loading the form
}
catch(Exception ex){//exception}
}
public ActionForward submitOrder(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception
{
try
{
// check the token. Proceed only if token is valid
if(isTokenValid(request,true)) {
//implement order submit functionality here
} else {
return mapping.findForward("failure");
}
}
catch(Exception ex){//exception}
}
}
Add this to jsp if you don't use <html:form> to enable store token on jsp
<input type="hidden" name="<%=Constants.TOKEN_KEY %>" value="<%=session.getAttribute(Globals.TRANSACTION_TOKEN_KEY) %>">
The problem of duplicate form submission arises when a user clicks the Submit button more than once before the response is sent back or when a client accesses a view by returning to a previously bookmarked page. This may result in inconsistent transactions and must be avoided. In our sample application, a similar problem will arise if the customer clicks the submit button more than once while submitting the purchase order.
In Struts this problem can be handled by using the saveToken() and isTokenValid() methods of Action class. saveToken() method creates a token (a unique string) and saves that in the user's current session, while isTokenValid() checks if the token stored in the user's current session is the same as that was passed as the request parameter.
To do this the JSP has to be loaded through an Action. Before loading the JSP call saveToken() to save the token in the user session. When the form is submitted, check the token against that in the session by calling isTokenValid(), as shown in the following code snippet:
Listing 3: Using saveToken() and isTokenValid()
public class PurchaseOrderAction extends DispatchAction
{
public ActionForward load(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception
{
try
{ //save the token
saveToken(request)
// rest of the code for loading the form
}
catch(Exception ex){//exception}
}
public ActionForward submitOrder(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception
{
try
{
// check the token. Proceed only if token is valid
if(isTokenValid(request,true)) {
//implement order submit functionality here
} else {
return mapping.findForward("failure");
}
}
catch(Exception ex){//exception}
}
}
Add this to jsp if you don't use <html:form> to enable store token on jsp
<input type="hidden" name="<%=Constants.TOKEN_KEY %>" value="<%=session.getAttribute(Globals.TRANSACTION_TOKEN_KEY) %>">
Subscribe to:
Posts (Atom)