Websphere Commerce Developer installation is really intensive. It's perfectly fine to have multiple Toolkit setup on the same machine for multiple profiles, for example, two different fix pack versions.
Steps:
1. Install or reuse existing installation of RAD/WAS
2. Install Commerce to a new location
3. Run setup.bat if you don't have a setup.log in ${WCToolkitEE60_ROOT}\logs
4. Run setdbtype to point the Commerce to the right database
That's it.
Wednesday, August 5, 2009
Wednesday, October 1, 2008
Spawn a Thread in a Servlet
When I search this topic on Google, the first impression is that, 'Stop! Just Don't Do It'. Threading code is error prone, not mentioning in a managed container. Additionally there are alternatives like Message Driven Beans or Java Message System, which are specially designed for this purpose. However, you may have a specific situation where threading in Servlet seems to be the only viable solution, for example the JSP page kicks off a long running process at the backend. What can you do? Fortunately it's totally doable if you are careful enough.
First, let's evaluate the risks. Obviously if your servlet is going to spawn multiple threads, this servlet cannot serve many concurrent users at the same time. Otherwise the thread pool will easily dry up and brings the server down to its knees. Concurrent access may cause race conditions and subtle synchronization problems too, especially in a load-balanced or clustered environment. Thread leak may be another risk. If not cleaned up appropriately, each leaked thread will have a reference to its classloader and prevent this classloader from being garbage collected. After enough reload of the application, you may run into out of PermGen space memory errors.
If the risks mentioned above do not apply to your particular situation or didn't scare you off, let's continue. The solution is as the following:
1. Instantiate your thread object as a daemon in your Servlet or ServletContextListener and call yourThread.start();
2. Store it as an attribute in your application context;
3. Return the HttpServletResponse;
4. Clean up the thread when the servlet or the application context is destroyed
5. Don't pass HttpservletRequest/Response/Session objects to the thread
First, let's evaluate the risks. Obviously if your servlet is going to spawn multiple threads, this servlet cannot serve many concurrent users at the same time. Otherwise the thread pool will easily dry up and brings the server down to its knees. Concurrent access may cause race conditions and subtle synchronization problems too, especially in a load-balanced or clustered environment. Thread leak may be another risk. If not cleaned up appropriately, each leaked thread will have a reference to its classloader and prevent this classloader from being garbage collected. After enough reload of the application, you may run into out of PermGen space memory errors.
If the risks mentioned above do not apply to your particular situation or didn't scare you off, let's continue. The solution is as the following:
1. Instantiate your thread object as a daemon in your Servlet or ServletContextListener and call yourThread.start();
2. Store it as an attribute in your application context;
3. Return the HttpServletResponse;
4. Clean up the thread when the servlet or the application context is destroyed
5. Don't pass HttpservletRequest/Response/Session objects to the thread
Monday, August 18, 2008
List JNDI Names
Sometimes we need to list all the JNDI names in an application server for debugging purpose. Other times, we may wish to list available datasources in a dropdown list for end-users to choose from. How to do this? In a nutshell, the JNDI bindings are organized in a tree strucuture. The following code is a simple example to recursively exhaust this binding tree:
Context ctx = (Context)new InitialContext().lookup("java:comp/env");
listContext(ctx, "");
/**
* Recursively exhaust the JNDI tree
*/
private static final void listContext(Context ctx, String indent) {
try {
NamingEnumeration list = ctx.listBindings("");
while (list.hasMore()) {
Binding item = (Binding) list.next();
String className = item.getClassName();
String name = item.getName();
logger.log(Level.INFO, indent + className + " " + name);
Object o = item.getObject();
if (o instanceof javax.naming.Context) {
listContext((Context) o, indent + " ");
}
}
} catch (NamingException ex) {
logger.log(Level.WARNING, "JNDI failure: ", ex);
}
Tuesday, August 12, 2008
Tag Libraries: JSTL, NetUI, Spring MVC, or Struts Tag Library
Not occasionally JSP developers need to iterate through collections and evaluate conditions before presenting the data. Tag libraries come in handy to provide a solution. However, there are quite a few Tag Libraries available, for example, the JSTL, NetUI, Spring MVC, and Struts tag libraries. Which one to choose? The quick answer is to use JSTL whenever possible. Use other tag libraries only when absolutely necessary.
Tag Libraries are not much different than any other utility libraries. Different vendors provide different features. JavaServer Pages Standard Tag Library (JSTL) is the most-accepted one and still powerful enough for common usages. If a non-standard tag library is chosen for additional features and convenience, other developers may have to climb a learning curve before being productive.
Additionally JSTL is designed to complement the HTML tags with 'logic control'
capabilities. This is in contrast to NetUI tag libraries, who replaces the HTML tags. Another example is Spring MVC's tag library. It is tightly integrated ONLY with the Spring MVC framework for convenient data binding. Tag libraries competing with HTML tags may create further compatibility issues. Sometimes JSP pages are touched by both developers and UI design artists. The UI design artists do not want to see any specialized tags by all means. Struts Tag Library used to gain a lot of popularity due to the success of the legend Struts framework. Now its document website has comments like, 'Some of the features in this taglib are also available in the JavaServer Pages Standard Tag Library (JSTL). The Struts team encourages the use of the standard tags over the Struts specific tags when possible.'
In a conclusion, JSTL tag library is the standard way to provides common logic processing features, such as to iterate through collections and to evaluate conditions. It complements the HTML tags. It will be the best choice for most common situations. Alternative ones, like NetUI, Spring MVC, or Struts Tag Library, may be chosen for additional functionalities.
Tag Libraries are not much different than any other utility libraries. Different vendors provide different features. JavaServer Pages Standard Tag Library (JSTL) is the most-accepted one and still powerful enough for common usages. If a non-standard tag library is chosen for additional features and convenience, other developers may have to climb a learning curve before being productive.
Additionally JSTL is designed to complement the HTML tags with 'logic control'
capabilities. This is in contrast to NetUI tag libraries, who replaces the HTML tags. Another example is Spring MVC's tag library. It is tightly integrated ONLY with the Spring MVC framework for convenient data binding. Tag libraries competing with HTML tags may create further compatibility issues. Sometimes JSP pages are touched by both developers and UI design artists. The UI design artists do not want to see any specialized tags by all means. Struts Tag Library used to gain a lot of popularity due to the success of the legend Struts framework. Now its document website has comments like, 'Some of the features in this taglib are also available in the JavaServer Pages Standard Tag Library (JSTL). The Struts team encourages the use of the standard tags over the Struts specific tags when possible.'
In a conclusion, JSTL tag library is the standard way to provides common logic processing features, such as to iterate through collections and to evaluate conditions. It complements the HTML tags. It will be the best choice for most common situations. Alternative ones, like NetUI, Spring MVC, or Struts Tag Library, may be chosen for additional functionalities.
Wednesday, August 6, 2008
Alternative Ways to Define JSP/Servlet Attribute Scopes
As we know, there are four types of scopes that a JSP/Servlet attribute can use:
Application: The attribute lasts the lifetime of an application instance.
Session: The attribute survives throughout the conversation session.
Request: The attribute will be discarded after the request is serviced.
Page: The attribute is only visible within a particular JSP page.
To keep data integrity, it's important to put attributes into the right scope. Most of the time developers will retrieve attributes from requests and put them into appropriate scopes thereafter. There are alternative ways.
1. Set application scope attributes in a ServletContextListener.
Sometimes "static" information should be loaded once and visible throughout the lifetime of an application. For example,
2. Set application scope attributes in a Servlet with <load-on-startup> features.
This is very similar to the above approach. For example,
3. Use filters to define session attributes.
Sometimes there are multiple entry points where a session attribute can be updated. In this case we'd better use a filter to watch for this kind of update instead of scattering the logic across various JSP's/Servlets. For example,
Application: The attribute lasts the lifetime of an application instance.
Session: The attribute survives throughout the conversation session.
Request: The attribute will be discarded after the request is serviced.
Page: The attribute is only visible within a particular JSP page.
To keep data integrity, it's important to put attributes into the right scope. Most of the time developers will retrieve attributes from requests and put them into appropriate scopes thereafter. There are alternative ways.
1. Set application scope attributes in a ServletContextListener.
Sometimes "static" information should be loaded once and visible throughout the lifetime of an application. For example,
web.xml
<listener>
<listener-class>
com.denistek.SampleListener
</listener-class>
</listener>
Java
public class SampleListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
//... get your attributes
event.getServletContext().setAttribute("attributes", attributes);
}
@Override
public void contextDestroyed(ServletContextEvent event) {
}
}
2. Set application scope attributes in a Servlet with <load-on-startup> features.
This is very similar to the above approach. For example,
web.xml
<servlet>
<servlet-name>SampleServlet</servlet-name>
<servlet-class>com.denistek.servlet.SampleServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
Java
@Override
public void init() throws ServletException {
super.init();
//... get your attributes
getServletContext().setAttribute("attributes", attributes);
}
3. Use filters to define session attributes.
Sometimes there are multiple entry points where a session attribute can be updated. In this case we'd better use a filter to watch for this kind of update instead of scattering the logic across various JSP's/Servlets. For example,
web.xml
<filter>
<filter-name>SampleFilter</filter-name>
<filter-class>com.denistek.SampleFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SampleFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Java
public class SampleFilter implements Filter {
private SampleAttribute[] attributes = null;
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException{
HttpServletRequest rq = (HttpServletRequest) request;
//... populate attributes from request here
rq.getSession().setAttribute("sampleAttributes", attributes);
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig config) {
//... populate attributes from context here
attributes = config.getServletContext().getAttribute("sampleAttributes");
}
@Override
public void destroy() {
}
}
Monday, July 28, 2008
Configure Tomcat 6 DataSource using Sql Server 2005
This is a step-by-step instructions on how to configure Tomcat 6 DataSource using Sql Server 2005. The installation of Tomcat and SqlServer is not covered.
1. Verify that you can login to the SQL Server using 'SQL Server Authentication'. You may wish to change the 'Server Authentication mode' to 'SQL Server and Windows Authentication mode'. You may also wish to check that the particular user's status of Login is 'Enabled'.
2. Verify that 'Local and remote connections' is enabled.
Go to Microsoft SQL Server 2005>Configuration Tools>SQL Server Surface Area Configuration>Remote Connections: Enable TCP/IP
3. Restart the database
4. Download and drop the JDBC driver to tomcat_home/lib. You may find tomcat-dbcp.jar in the directory. This will make the driver available to both the Tomcat internal classes and the web application.
5. Change the context.xml, for example:
6. Change the web.xml, for example:
7. Write a testing JSP page like this:
That's it!
1. Verify that you can login to the SQL Server using 'SQL Server Authentication'. You may wish to change the 'Server Authentication mode' to 'SQL Server and Windows Authentication mode'. You may also wish to check that the particular user's status of Login is 'Enabled'.
2. Verify that 'Local and remote connections' is enabled.
Go to Microsoft SQL Server 2005>Configuration Tools>SQL Server Surface Area Configuration>Remote Connections: Enable TCP/IP
3. Restart the database
4. Download and drop the JDBC driver to tomcat_home/lib. You may find tomcat-dbcp.jar in the directory. This will make the driver available to both the Tomcat internal classes and the web application.
5. Change the context.xml, for example:
<?xml version="1.0" encoding="UTF-8"?>
<context path="/BFS2">
<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="sa" password="passw0rd" driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
url="jdbc:sqlserver://localhost:1433;databaseName=TestOne" />
</context>
6. Change the web.xml, for example:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xsi="http://www.w3.org/2001/XMLSchema-instance" schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/TestDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
7. Write a testing JSP page like this:
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ page import="java.sql.*" %>
<%@ page import="javax.sql.*" %>
<%@ page import="javax.naming.*" %>
<HTML>
<HEAD>
<TITLE>JSP example</TITLE>
</HEAD>
<BODY>
<h1>Hello,test JNDI ! </h1>
<%
Context ctx = new InitialContext();
Context envctx = (Context) ctx.lookup("java:comp/env");
DataSource ds = (DataSource) envctx.lookup("jdbc/TestDB");
Connection conn=ds.getConnection();
Statement st=conn.createStatement();
String sql="select * from status";
ResultSet rs=st.executeQuery(sql);
while(rs.next()) {
%>
ID:<%=rs.getInt(1) %>
Value:<%=rs.getString(2) %>
<br>
<%
}
%>
Here is just JNDI datasource SQL Server 2005 + tomcat example
<%
rs.close();
st.close();
conn.close();
%>
</BODY>
</HTML>
That's it!
Labels:
DataSource,
JDBC,
JNDI,
SQL Server 2005,
Tomcat
Thursday, June 19, 2008
5 Minute Introduction to Dependence Injection (DI, IoC)
Newbies are confused by the words, Dependency Injection (DI) and Inversion of Control (IoC). I was confused. This article is for those who dare to add these hot and fancy words onto their resume but have only 5 minutes bandwidth to learn the details. Without any further delay, this is the explanation.
Minute One: Concept Background
Generally in a Object Oriented Language (OOL) like Java, there are no more than three relationships between two classes: inheritance, reference, and aggregation. Inheritance and polymorphisms are powerful features already built-in in the Java language. However, as to the the 'reference' relationship, it was awkward in Java until the appearance of DI.
Minute Two: Traditional Coding Style
Traditionally, we write code like this when ClassB has a reference relationship with ClassA:
If we change our mind to plug in another implementation, say ClassAA, then we have to go back to the ClassB's source code to change at least one line of code:
InterfaceA a = new ClassAA();
In another word, ClassB is still strongly coupled with ClassA.
Minute Three: DI Coding Style
DI code looks like this:
Note that ClassB does not prescribe whether ClassA or ClassAA will be used prematurely. Only at the run time, the container will render either ClassA or ClassAA to ClassB according to the configuration. Details of the container and the configuration file are intentionally ignored here because they are trivial to the concept understanding. By the way, the new setA() method is needed by the container.
Minute Four: So What?
What is the big deal to change one line of code into another line of configuration with more lines of code and a totally new container?
The gain is that, now the hard-coded relationships are minimized. Only ClassB-InterfaceA and ClassA-InterfaceA relationships are maintained. The ClassB-ClassA relationship disappeared! Finally ClassA and ClassB are totally independent to each other. Each one can have it's own changes without affecting the other party and finally we can easily swap ClassA out without touching ClassB.
Minute Five: Spring Framework
DI and AoP are the two fundamental ideas behind the Spring Framework, with which our Plain Old Java Objects (POJO) can be easily enriched by a complete pack of enterprise level features, such as transaction control, persistence, security and etc. See http://www.springframework.org/ for more details.
In my humble opinion, DI is simply the most important concept after Object Oriented concepts in Java.
Minute One: Concept Background
Generally in a Object Oriented Language (OOL) like Java, there are no more than three relationships between two classes: inheritance, reference, and aggregation. Inheritance and polymorphisms are powerful features already built-in in the Java language. However, as to the the 'reference' relationship, it was awkward in Java until the appearance of DI.
Minute Two: Traditional Coding Style
Traditionally, we write code like this when ClassB has a reference relationship with ClassA:
public ClassA implements InterfaceA { ...}
public ClassB {
InterfaceA a = new ClassA();
}
If we change our mind to plug in another implementation, say ClassAA, then we have to go back to the ClassB's source code to change at least one line of code:
InterfaceA a = new ClassAA();
In another word, ClassB is still strongly coupled with ClassA.
Minute Three: DI Coding Style
DI code looks like this:
public ClassA implements InterfaceA { ...}
public ClassB {
InterfaceA a;
public void setA(InterfaceA input) { a = input; }
....
}
Note that ClassB does not prescribe whether ClassA or ClassAA will be used prematurely. Only at the run time, the container will render either ClassA or ClassAA to ClassB according to the configuration. Details of the container and the configuration file are intentionally ignored here because they are trivial to the concept understanding. By the way, the new setA() method is needed by the container.
Minute Four: So What?
What is the big deal to change one line of code into another line of configuration with more lines of code and a totally new container?
The gain is that, now the hard-coded relationships are minimized. Only ClassB-InterfaceA and ClassA-InterfaceA relationships are maintained. The ClassB-ClassA relationship disappeared! Finally ClassA and ClassB are totally independent to each other. Each one can have it's own changes without affecting the other party and finally we can easily swap ClassA out without touching ClassB.
Minute Five: Spring Framework
DI and AoP are the two fundamental ideas behind the Spring Framework, with which our Plain Old Java Objects (POJO) can be easily enriched by a complete pack of enterprise level features, such as transaction control, persistence, security and etc. See http://www.springframework.org/ for more details.
In my humble opinion, DI is simply the most important concept after Object Oriented concepts in Java.
Subscribe to:
Posts (Atom)