Article Collections for Advanced Java Distributed by justEtc |
please check
http://members.tripod.com/gsraj/ejb/chapter/
A good book on EJB
A good example: http://developerlife.com/tutorials/?p=25
Another very good example: http://www.developerfusion.co.uk/show/2064/: I followed this code to extract attribute values from an xml file.
Industries use frameworks for application development quite often.
For example: Java concepts like JSP, Servlet, Swing, Bean, JDBC can
be used directly to create web-applications but when such
applications become big, it becomes difficult to maintain and
develop them further. Hence, frameworks like struts are used to develop
large web-based Java applications. This makes maintenance and
further development easier. If you need to write a very simple web
application with a few pages, then you might consider using
JSP/Servlet directly otherwise Struts like frameworks are better
options.
Struts-1 uses the concept Model View Architecture (MVC) and provides
the controller. In MVC model, Model represents business logic, View
represents user interfaces, and Controller represents/controls control
flow of the application.
Struts' control layer is based on standard technologies like
Java Servlets, JavaBeans, ResourceBundles, and XML, as well as
various Apache Commons packages, like BeanUtils and Chain of
Responsibility.
For the Model, struts-1 framework can interact with standard
data access technologies, like JDBC and EJB, as well as most
any third-party packages, like Hibernate, iBATIS, or Object Relational
Bridge. For the View, the framework works well with JavaServer Pages,
including JSTL and JSF, as well as Velocity Templates, XSLT, and
other presentation systems.
The framework's Controller acts as a bridge between the application's Model and the web View.
When a request is received, the Controller invokes an Action class. The Action class consults
with the Model to examine or update the application's state. The framework provides an ActionForm
class to help transfer data between Model and View.
Struts-1 Configuration
-----------------------
web.xml is one of the configuration files. It is an XML-formatted file that works as a
deployment descriptor.
struts-config.xml is another resource file to initialize the applications resources.
These resources include ActionForms to collect input from users, ActionMappings
to direct input to server-side Actions, and ActionForwards to select output pages.
Sample struts-config.xml file.
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
"http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<form-beans>
<form-bean
name="logonForm"
type="app.LogonForm"/>
</form-beans>
<action-mappings>
<action
path="/Welcome"
forward="/pages/Welcome.jsp"/>
<action
path="/Logon"
forward="/pages/Logon.jsp"/>
<action
path="/LogonSubmit"
type="app.LogonAction"
name="logonForm"
scope="request"
validate="true"
input="/pages/Logon.jsp">
<forward
name="success"
path="/pages/Welcome.jsp"/>
<forward
name="failure"
path="/pages/Logon.jsp"/>
</action>
<action
path="/Logoff"
type="app.LogoffAction">
<forward
name="success"
path="/pages/Logoff.jsp"/>
</action>
</action-mappings>
<message-resources parameter="resources.application"/>
</struts-config>
Other resources like Validators can be initialized here.
What is Java bean?
Just a component technology. You can create platform independent components using Java beans.
Key Bean Concepts:
1. introspection: Through introspection beans expose their properties, methods, and events. Beans support
introspection in two ways:
1.1: Design patterns: The Introspector class examines beans for design patterns to discover bean features
1.2: Through a related bean information class that implements the BeanInfo interface. The class lists the
bean features that are to be exposed
2. Properties: Are the appearance and behavior characteristics of a bean that can be changed at
design time
3. Beans use events to communicate with other beans
4. Persistence enables beans to store and retrieve their state using serialization
5. Beans provide methods that can be called from other beans, or scripting language
Bean Property Types
--------------------
# Simple – with a single value
# Indexed – a range of values
# Bound – a change to the property results in a
notification being sent to some other bean
# Constrained – a change to the property requries
validation by other bean
Bean Properties can be
*Writable – can be changed
o Standard
o Expert
o Preferred
* Read Only – cannot be changed
* Hidden – can be changed. not disclosed with the BeanInfo class
Use third party API bundles like jexcelApi.
http://jexcelapi.sourceforge.net/.
---
create an XML file to define the structure of your excel file like how many columns, column names, corresponding database table/class column/variable name,
Create a Java class that can retrieve information from that xml file. You can use XPATH and DOM for the purpose. check http://www.ibm.com/developerworks/library/x-javaxpathapi.html for ideas
---
write an html form that use input type='file', the form action should point to the servlet that will collect data from the excel file and store it in the database. servlet will collect data from the input stream
-----------
in the servlet use the class that represents the xml file. to get information about the file that will help mapping the excel file data to the corresponding table column. You can also create a class representing the database table. From servlet extract data, create an object of table class type, and create a function that takes the object and inserts into the table.
---------------
How servlet will process the excel file:
jexcelAPI Workbook class represents the total workbook
use getsheet method of workbook class to get the sheet
number 0,1,2....
use getCell method of worksheet to get a particular cell object in the excel file
use getContents on the cell object to get data in string type.
from the XML file having excel file structure, you can get number of columns in the file. So you can write a look that will read data row,column wise from the excel file
----
code to process excel file [in servlet]
Workbook workbook = Workbook.getWorkbook(new File("myfile.xls"));
Sheet sheet = workbook.getSheet(0);
Cell a1 = sheet.getCell(0,0);
Cell b2 = sheet.getCell(1,1);
Cell c2 = sheet.getCell(2,1);
String stringa1 = a1.getContents();
String stringb2 = b2.getContents();
String stringc2 = c2.getContents();
----------------------
check the following webpage, it provides file upload and extract data from input stream in servlet applications
http://jexcelapi.sourceforge.net/resources/faq/
What is Spring Framework? What does it mean to J2EE developers?
Spring is a light-weight framework, very often referred as an alternative/competitor to EJB, for the development of enterprise-type applications. Spring provides many features such as declarative transaction management, access to remote logic using RMI or web services, mailing facilities and database abstraction.
Features of Spring Framework
No need to maintain the state of a bean between calls.
//CalculatorBean.java
@Stateless
public class CalculatorBean implements CalculatorRemote, CalculatorLocal
{
public int add(int x, int y)
{
return x + y;
}
public int subtract(int x, int y)
{
return x - y;
}
}
//CalculatorRemote.java
import javax.ejb.Remote;
@Remote
public interface CalculatorRemote extends Calculator
{
}
//CalculatorLocal.java
import javax.ejb.Local;
@Local
public interface CalculatorLocal extends Calculator
{
}
//Client.java
import tutorial.stateless.bean.Calculator;
import tutorial.stateless.bean.CalculatorRemote;
import javax.naming.InitialContext;
public class Client
{
public static void main(String[] args) throws Exception
{
InitialContext ctx = new InitialContext();
Calculator calculator = (Calculator) ctx.lookup("CalculatorBean/remote");
System.out.println("1 + 1 = " + calculator.add(1, 1));
System.out.println("1 - 1 = " + calculator.subtract(1, 1));
}
}
EJB 2: How to build a stateless EJB
States need to be maintained between calls. In EJB3 all beans are homeless [no home interface]
//ShoppingCartBean.java
import java.io.Serializable;
import java.util.HashMap;
import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.ejb.Remote;
@Stateful
@Remote(ShoppingCart.class)
public class ShoppingCartBean implements ShoppingCart, Serializable
{
private HashMap cart = new HashMap();
public void buy(String product, int quantity)
{
if (cart.containsKey(product))
{
int currq = cart.get(product);
currq += quantity;
cart.put(product, currq);
}
else
{
cart.put(product, quantity);
}
}
public HashMap getCartContents()
{
return cart;
}
@Remove
public void checkout()
{
System.out.println("To be implemented");
}
}
//ShoppingCart.java
//remote interface
import java.util.HashMap;
import javax.ejb.Remove;
public interface ShoppingCart
{
void buy(String product, int quantity);
HashMap getCartContents();
@Remove void checkout();
}
//client
//Client.java
//client uses JNDI to look up for EJB services
import java.util.HashMap;
import javax.naming.InitialContext;
import org.jboss.tutorial.stateful.bean.ShoppingCart;
public class Client
{
public static void main(String[] args) throws Exception
{
InitialContext ctx = new InitialContext();
ShoppingCart cart = (ShoppingCart) ctx.lookup("ShoppingCartBean/remote");
System.out.println("Buying 1 memory stick");
cart.buy("Memory stick", 1);
System.out.println("Buying another memory stick");
cart.buy("Memory stick", 1);
System.out.println("Buying a laptop");
cart.buy("Laptop", 1);
System.out.println("Print cart:");
HashMap fullCart = cart.getCartContents();
for (String product : fullCart.keySet())
{
System.out.println(fullCart.get(product) + " " + product);
}
System.out.println("Checkout");
cart.checkout();
System.out.println("Should throw an object not found exception by invoking on cart after @Remove method");
try
{
cart.getCartContents();
}
catch (javax.ejb.EJBNoSuchObjectException e)
{
System.out.println("Successfully caught no such object exception.");
}
}
}
Plain Java objects with persistence storage. They are not
remotable and must be accessed through the new
javax.persistence.EntityManager service.
An entity bean implementation is provided in the following
three files/classes
Beans
Order.java
LineItem.java
Entity Manager
ShoppingCartBean.java
//Order.java
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue; import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Id;
import javax.persistence.CascadeType;
import javax.persistence.FetchType;
import java.util.ArrayList;
import java.util.Collection;
@Entity
@Table(name = "PURCHASE_ORDER")
public class Order implements java.io.Serializable
{
private int id;
private double total;
private Collection lineItems;
@Id @GeneratedValue(strategy=GenerationType.AUTO)
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public double getTotal()
{
return total;
}
public void setTotal(double total)
{
this.total = total;
}
public void addPurchase(String product, int quantity, double price)
{
if (lineItems == null) lineItems = new ArrayList();
LineItem item = new LineItem();
item.setOrder(this);
item.setProduct(product);
item.setQuantity(quantity);
item.setSubtotal(quantity * price);
lineItems.add(item);
total += quantity * price;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy="order")
public Collection getLineItems()
{
return lineItems;
}
public void setLineItems(Collection lineItems)
{
this.lineItems = lineItems;
}
}
//LineItem.java
import javax.persistence.Entity;
import javax.persistence.GeneratedValue; import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Entity;
@Entity
public class LineItem implements java.io.Serializable
{
private int id;
private double subtotal;
private int quantity;
private String product;
private Order order;
@Id @GeneratedValue(strategy=GenerationType.AUTO)
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public double getSubtotal()
{
return subtotal;
}
public void setSubtotal(double subtotal)
{
this.subtotal = subtotal;
}
public int getQuantity()
{
return quantity;
}
public void setQuantity(int quantity)
{
this.quantity = quantity;
}
public String getProduct()
{
return product;
}
public void setProduct(String product)
{
this.product = product;
}
@ManyToOne
@JoinColumn(name = "order_id")
public Order getOrder()
{
return order;
}
public void setOrder(Order order)
{
this.order = order;
}
}
//ShoppingCartBean.java
Interacts with Order as a plain Java object. The checkout()
method stores orders with persistence storage by using the
required EntityManager service.
import javax.ejb.Remote;
import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContext;
@Stateful
@Remote(ShoppingCart.class)
public class ShoppingCartBean implements ShoppingCart, java.io.Serializable
{
@PersistenceContext
private EntityManager manager;
private Order order;
public void buy(String product, int quantity, double price)
{
if (order == null) order = new Order();
order.addPurchase(product, quantity, price);
}
public Order getOrder()
{
return order;
}
@Remove
public void checkout()
{
manager.persist(order);
}
}
GNU Distribution Without Warranty License
Comparison EJB 2 and EJB 3
Sample stored procedure call using JDBC: Call stored procedure to change/set a value in the database
//set birthday - supply professor name try { String professor= "dylan thomas"; CallableStatement proc = connection.prepareCall("{ call set_birth_date(?, ?) }"); proc.setString(1, professor); proc.setString(2, '1950-01-01'); cs.execute(); } catch (SQLException e) { // .... } Stored procedures can also return result/data to the caller: like //return birth day connection.setAutoCommit(false); CallableStatement proc = connection.prepareCall("{ ? = call birthday_when(?) }"); proc.registerOutParameter(1, Types.Timestamp); proc.setString(2, professorName); cs.execute(); Timestamp age = proc.getString(2); Stored procedures can also return complex data like resultsets. JDBC drivers from oracle, Sql Server, PostgreSQL support this.
Why Have Code Conventions?
Java Code Conventions
Ant can be used to compile and deploy Java applications. Struts and Spring applications also make use of Ant. Here, we have provided the structure of the build.xml file with examples that is used to carry out the functionalities. The redistribution of this file is in compatible with the copyright law of The Apache Foundation.
<!--
General purpose build script for web applications and web services,
including enhanced support for deploying directly to a Tomcat 5
based server.
This build script assumes that the source code of your web application
is organized into the following subdirectories underneath the source
code directory from which you execute the build script:
docs Static documentation files to be copied to
the "docs" subdirectory of your distribution.
src Java source code (and associated resource files)
to be compiled to the "WEB-INF/classes"
subdirectory of your web applicaiton.
web Static HTML, JSP, and other content (such as
image files), including the WEB-INF subdirectory
and its configuration file contents.
$Id: build.xml.txt 565211 2007-08-13 00:09:38Z markt $
-->
<!-- A "project" describes a set of targets that may be requested
when Ant is executed. The "default" attribute defines the
target which is executed if no specific target is requested,
and the "basedir" attribute defines the current working directory
from which Ant executes the requested task. This is normally
set to the current working directory.
-->
<project name="My Project" default="compile" basedir=".">
<!-- ===================== Property Definitions =========================== -->
<!--
Each of the following properties are used in the build script.
Values for these properties are set by the first place they are
defined, from the following list:
* Definitions on the "ant" command line (ant -Dfoo=bar compile).
* Definitions from a "build.properties" file in the top level
source directory of this application.
* Definitions from a "build.properties" file in the developer's
home directory.
* Default definitions in this build.xml file.
You will note below that property values can be composed based on the
contents of previously defined properties. This is a powerful technique
that helps you minimize the number of changes required when your development
environment is modified. Note that property composition is allowed within
"build.properties" files as well as in the "build.xml" script.
-->
<property file="build.properties"/>
<property file="${user.home}/build.properties"/>
<!-- ==================== File and Directory Names ======================== -->
<!--
These properties generally define file and directory names (or paths) that
affect where the build process stores its outputs.
app.name Base name of this application, used to
construct filenames and directories.
Defaults to "myapp".
app.path Context path to which this application should be
deployed (defaults to "/" plus the value of the
"app.name" property).
app.version Version number of this iteration of the application.
build.home The directory into which the "prepare" and
"compile" targets will generate their output.
Defaults to "build".
catalina.home The directory in which you have installed
a binary distribution of Tomcat 5. This will
be used by the "deploy" target.
dist.home The name of the base directory in which
distribution files are created.
Defaults to "dist".
manager.password The login password of a user that is assigned the
"manager" role (so that he or she can execute
commands via the "/manager" web application)
manager.url The URL of the "/manager" web application on the
Tomcat installation to which we will deploy web
applications and web services.
manager.username The login username of a user that is assigned the
"manager" role (so that he or she can execute
commands via the "/manager" web application)
-->
<property name="app.name" value="myapp"/>
<property name="app.path" value="/${app.name}"/>
<property name="app.version" value="0.1-dev"/>
<property name="build.home" value="${basedir}/build"/>
<property name="catalina.home" value="../../../.."/> <!-- UPDATE THIS! -->
<property name="dist.home" value="${basedir}/dist"/>
<property name="docs.home" value="${basedir}/docs"/>
<property name="manager.url" value="http://localhost:8080/manager"/>
<property name="src.home" value="${basedir}/src"/>
<property name="web.home" value="${basedir}/web"/>
<!-- ================== Custom Ant Task Definitions ======================= -->
<!--
These properties define custom tasks for the Ant build tool that interact
with the "/manager" web application installed with Tomcat 5. Before they
can be successfully utilized, you must perform the following steps:
- Copy the file "server/lib/catalina-ant.jar" from your Tomcat 5
installation into the "lib" directory of your Ant installation.
- Create a "build.properties" file in your application's top-level
source directory (or your user login home directory) that defines
appropriate values for the "manager.password", "manager.url", and
"manager.username" properties described above.
For more information about the Manager web application, and the functionality
of these tasks, see <http://localhost:8080/tomcat-docs/manager-howto.html>.
-->
<taskdef name="deploy" classname="org.apache.catalina.ant.DeployTask"/>
<taskdef name="list" classname="org.apache.catalina.ant.ListTask"/>
<taskdef name="reload" classname="org.apache.catalina.ant.ReloadTask"/>
<taskdef name="undeploy" classname="org.apache.catalina.ant.UndeployTask"/>
<!-- ==================== Compilation Control Options ==================== -->
<!--
These properties control option settings on the Javac compiler when it
is invoked using the <javac> task.
compile.debug Should compilation include the debug option?
compile.deprecation Should compilation include the deprecation option?
compile.optimize Should compilation include the optimize option?
-->
<property name="compile.debug" value="true"/>
<property name="compile.deprecation" value="false"/>
<property name="compile.optimize" value="true"/>
<!-- ==================== External Dependencies =========================== -->
<!--
Use property values to define the locations of external JAR files on which
your application will depend. In general, these values will be used for
two purposes:
* Inclusion on the classpath that is passed to the Javac compiler
* Being copied into the "/WEB-INF/lib" directory during execution
of the "deploy" target.
Because we will automatically include all of the Java classes that Tomcat 5
exposes to web applications, we will not need to explicitly list any of those
dependencies. You only need to worry about external dependencies for JAR
files that you are going to include inside your "/WEB-INF/lib" directory.
-->
<!-- Dummy external dependency -->
<!--
<property name="foo.jar"
value="/path/to/foo.jar"/>
-->
<!-- ==================== Compilation Classpath =========================== -->
<!--
Rather than relying on the CLASSPATH environment variable, Ant includes
features that makes it easy to dynamically construct the classpath you
need for each compilation. The example below constructs the compile
classpath to include the servlet.jar file, as well as the other components
that Tomcat makes available to web applications automatically, plus anything
that you explicitly added.
-->
<path id="compile.classpath">
<!-- Include all JAR files that will be included in /WEB-INF/lib -->
<!-- *** CUSTOMIZE HERE AS REQUIRED BY YOUR APPLICATION *** -->
<!--
<pathelement location="${foo.jar}"/>
-->
<!-- Include all elements that Tomcat exposes to applications -->
<pathelement location="${catalina.home}/common/classes"/>
<fileset dir="${catalina.home}/common/endorsed">
<include name="*.jar"/>
</fileset>
<fileset dir="${catalina.home}/common/lib">
<include name="*.jar"/>
</fileset>
<pathelement location="${catalina.home}/shared/classes"/>
<fileset dir="${catalina.home}/shared/lib">
<include name="*.jar"/>
</fileset>
</path>
<!-- ==================== All Target ====================================== -->
<!--
The "all" target is a shortcut for running the "clean" target followed
by the "compile" target, to force a complete recompile.
-->
<target name="all" depends="clean,compile"
description="Clean build and dist directories, then compile"/>
<!-- ==================== Clean Target ==================================== -->
<!--
The "clean" target deletes any previous "build" and "dist" directory,
so that you can be ensured the application can be built from scratch.
-->
<target name="clean"
description="Delete old build and dist directories">
<delete dir="${build.home}"/>
<delete dir="${dist.home}"/>
</target>
<!-- ==================== Compile Target ================================== -->
<!--
The "compile" target transforms source files (from your "src" directory)
into object files in the appropriate location in the build directory.
This example assumes that you will be including your classes in an
unpacked directory hierarchy under "/WEB-INF/classes".
-->
<target name="compile" depends="prepare"
description="Compile Java sources">
<!-- Compile Java classes as necessary -->
<mkdir dir="${build.home}/WEB-INF/classes"/>
<javac srcdir="${src.home}"
destdir="${build.home}/WEB-INF/classes"
debug="${compile.debug}"
deprecation="${compile.deprecation}"
optimize="${compile.optimize}">
<classpath refid="compile.classpath"/>
</javac>
<!-- Copy application resources -->
<copy todir="${build.home}/WEB-INF/classes">
<fileset dir="${src.home}" excludes="**/*.java"/>
</copy>
</target>
<!-- ==================== Dist Target ===================================== -->
<!--
The "dist" target creates a binary distribution of your application
in a directory structure ready to be archived in a tar.gz or zip file.
Note that this target depends on two others:
* "compile" so that the entire web application (including external
dependencies) will have been assembled
* "javadoc" so that the application Javadocs will have been created
-->
<target name="dist" depends="compile,javadoc"
description="Create binary distribution">
<!-- Copy documentation subdirectories -->
<mkdir dir="${dist.home}/docs"/>
<copy todir="${dist.home}/docs">
<fileset dir="${docs.home}"/>
</copy>
<!-- Create application JAR file -->
<jar jarfile="${dist.home}/${app.name}-${app.version}.war"
basedir="${build.home}"/>
<!-- Copy additional files to ${dist.home} as necessary -->
</target>
<!-- ==================== Install Target ================================== -->
<!--
The "install" target tells the specified Tomcat 5 installation to dynamically
install this web application and make it available for execution. It does
*not* cause the existence of this web application to be remembered across
Tomcat restarts; if you restart the server, you will need to re-install all
this web application.
If you have already installed this application, and simply want Tomcat to
recognize that you have updated Java classes (or the web.xml file), use the
"reload" target instead.
NOTE: This target will only succeed if it is run from the same server that
Tomcat is running on.
NOTE: This is the logical opposite of the "remove" target.
-->
<target name="install" depends="compile"
description="Install application to servlet container">
<deploy url="${manager.url}"
username="${manager.username}"
password="${manager.password}"
path="${app.path}"
localWar="file://${build.home}"/>
</target>
<!-- ==================== Javadoc Target ================================== -->
<!--
The "javadoc" target creates Javadoc API documentation for the Java
classes included in your application. Normally, this is only required
when preparing a distribution release, but is available as a separate
target in case the developer wants to create Javadocs independently.
-->
<target name="javadoc" depends="compile"
description="Create Javadoc API documentation">
<mkdir dir="${dist.home}/docs/api"/>
<javadoc sourcepath="${src.home}"
destdir="${dist.home}/docs/api"
packagenames="*">
<classpath refid="compile.classpath"/>
</javadoc>
</target>
<!-- ====================== List Target =================================== -->
<!--
The "list" target asks the specified Tomcat 5 installation to list the
currently running web applications, either loaded at startup time or
installed dynamically. It is useful to determine whether or not the
application you are currently developing has been installed.
-->
<target name="list"
description="List installed applications on servlet container">
<list url="${manager.url}"
username="${manager.username}"
password="${manager.password}"/>
</target>
<!-- ==================== Prepare Target ================================== -->
<!--
The "prepare" target is used to create the "build" destination directory,
and copy the static contents of your web application to it. If you need
to copy static files from external dependencies, you can customize the
contents of this task.
Normally, this task is executed indirectly when needed.
-->
<target name="prepare">
<!-- Create build directories as needed -->
<mkdir dir="${build.home}"/>
<mkdir dir="${build.home}/WEB-INF"/>
<mkdir dir="${build.home}/WEB-INF/classes"/>
<!-- Copy static content of this web application -->
<copy todir="${build.home}">
<fileset dir="${web.home}"/>
</copy>
<!-- Copy external dependencies as required -->
<!-- *** CUSTOMIZE HERE AS REQUIRED BY YOUR APPLICATION *** -->
<mkdir dir="${build.home}/WEB-INF/lib"/>
<!--
<copy todir="${build.home}/WEB-INF/lib" file="${foo.jar}"/>
-->
<!-- Copy static files from external dependencies as needed -->
<!-- *** CUSTOMIZE HERE AS REQUIRED BY YOUR APPLICATION *** -->
</target>
<!-- ==================== Reload Target =================================== -->
<!--
The "reload" signals the specified application Tomcat 5 to shut itself down
and reload. This can be useful when the web application context is not
reloadable and you have updated classes or property files in the
/WEB-INF/classes directory or when you have added or updated jar files in the
/WEB-INF/lib directory.
NOTE: The /WEB-INF/web.xml web application configuration file is not reread
on a reload. If you have made changes to your web.xml file you must stop
then start the web application.
-->
<target name="reload" depends="compile"
description="Reload application on servlet container">
<reload url="${manager.url}"
username="${manager.username}"
password="${manager.password}"
path="${app.path}"/>
</target>
<!-- ==================== Remove Target =================================== -->
<!--
The "remove" target tells the specified Tomcat 5 installation to dynamically
remove this web application from service.
NOTE: This is the logical opposite of the "install" target.
-->
<target name="remove"
description="Remove application on servlet container">
<undeploy url="${manager.url}"
username="${manager.username}"
password="${manager.password}"
path="${app.path}"/>
</target>
</project>
Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
public class ExampleServletConnector extends HttpServlet{
private Connection con;
private ConnectionFactory cf;
private String user;
public void init() throws ServletException{
try{
//establish JNDI interface
InitialContext ic = new InitialContext();
//look up user and password
user = (String) ic.lookup("java:comp/env/user");
String password = (String) ic.lookup("java:comp/env/password");
//reference to the connection factory
for the CCI black box resource adapter -
coded name CCIEIS
cf = (ConnectionFactory) ic.lookup("java:comp/env/CCIEIS");
//collect connection specification, connect to the database
ConnectionSpec conSpec = new ConnectionSpec (user,password);
con = cf.getConnection(conSpec);
}catch(ResourceException rex){
rex.printStackTrace();
}catch(NamingException nex){
nex.printStackTrace();
}
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException {
PrintWriter output = null;
res.setContentType("text/html");
try{
PrintWriter out = res.getWriter();
//find the number of rows in the account table -
check getAccountAccountCount method in the next item
int accCount = getAccountAccountCount();
out.println("Account Count" + accCount);
}catch(Exception ex){
ex.printStackTrace();
}
}
public int getAccountCount(){
int count = -1;
try{
Interaction ix = con.createInteraction();
CciInteractionSpec iSpec = new CciInteractionSpec();
iSpec.setSchema(user);
iSpec.setCatalog(null);
//stored procedure name to calculate the number of rows
iSpec.setFunctionName("ACCOUNTCOUNT");
RecordFactory rf = cf.getRecordFactory();
IndexedRecord iRec = rf.createIndexedRecord("InputRecord");
Record oRec = ix.execute(iSpec, iRec);
Iterator it = ((IndexedRecord)oRec).iterator();
//process
while(it.hasNext()){
Object obj = it.next();
if (obj instanceof Integer){
count = ((Integer) obj).intValue();
}else if (obj instanceOf BigDecimal){
count = ((BigDecimal) obj).intValue();
}
}
}catch(Exception ex){
}
return count;
}
// for remote references to objects such as EJBs
import javax.rmi.PortableRemoteObject;
//banking system ejb package
import bankingSystemEjbClasses.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.naming.*;
public class ServletEjb extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException{
float credit = 10;
float debit = 20;
String custName = "";
float initBalance = 0, endBalance = 0;
try{
//locate and instantiate the account manager bean
Context context = new InitialContext();
Object ref = context.lookup("AccountManager");
AccountManagerHome accountManagerHome = (AccountManagerHome)
PortableRemoteObject.narrow
(ref, AccountManagerHome.class);
AccountManager accountManager = accountManagerHome.create();
//create a savings account and manipulate it
accountManager.createSavingsAccount(1,"John Smith")
initBalance = accountManager.getInitialBalance("1");
//create customer
accountManager.createCustomer(1,"John Smith")
custName = accountManager.getCustomerName();
//generate output
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("Customer Name:" + custName);
out.println("Initial Balance:" + initBalance);
out.println("</body>");
out.println("</html>");
}catch(Exception ex){
}
}
}
synchronized(sharedResource) {
}
Core J2EE Component Technologies
J2EE Services