Java: A collection of my articles

by JustEtc Publications Ltd




Distributed by justEtc

Differences between Java Bean and EJB



please check http://members.tripod.com/gsraj/ejb/chapter/

A good book on EJB



Opening and reading files with Java JDK 1.0.x



   1. Open the file with the File class;
   2. Create a FileInputStream object using the File object;
   3. Convert the FileInputStream to a BufferedInputStream to greatly increase file reading speed;
   4. Convert the BufferedInputStream to a DataInputStream; the methods of DataInputStream give me a fair amount of flexibility in reading the data.
   5. Read the file until the end


File f = new File("mydata.txt"); 
FileInputStream fis = new FileInputStream(f); 
BufferedInputStream bis = new BufferedInputStream(fis); 
DataInputStream dis = new DataInputStream(bis);  
String record = null; 

try { 

   while ( (record=dis.readLine()) != null ) { 
      // 
      // put your logic here to work with "record" 
      // 
   } 

} catch (IOException e) { 
   // 
   // put your error-handling code here 
   // 
} 



Java XML Example - XML File Parse and Use Attributes



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.



MVC : Struts : Java : Industry Web Application



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.



Linked List and Iterator in Java



/*
 * LinkedList.java
 *
 * Created on January 10, 2008, 8:51 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package linkedlist;

import java.util.List;
import java.util.LinkedList;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Collections;
import java.util.Random;

/**
 *
 * @author Sayed
 */
public class LinkedListTest {
    
    /** Creates a new instance of LinkedList */
    public LinkedListTest() {
    }
    
    /**
     *Example operations using linked lists
     */
    
    public void linkedListOperation(){
        
        final int MAX = 10;
        int counter = 0;

        //create two linked lists
        List listA = new LinkedList();
        List listB = new LinkedList();

        //store data in the linked list A
        for (int i = 0; i < MAX; i++) {
            System.out.println("  - Storing Integer(" + i + ")");
            listA.add(new Integer(i));
        }
       
        //print data from the linked list using iterator 
        Iterator it = listA.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }

        //print data from the linked list using listIterator. 
        counter = 0;
        ListIterator liIt = listA.listIterator();
        while (liIt.hasNext()) {
            System.out.println("Element [" + counter + "] = " + liIt.next());
            System.out.println("  - hasPrevious    = " + liIt.hasPrevious());
            System.out.println("  - hasNext        = " + liIt.hasNext());
            System.out.println("  - previousIndex  = " + liIt.previousIndex());
            System.out.println("  - nextIndex      = " + liIt.nextIndex());
            System.out.println();
            counter++;
        }


        //retrieve data from the linked list using index
        for (int j=0; j < listA.size(); j++) {
            System.out.println("[" + j + "] - " + listA.get(j));
        }

        //find the location of an element
        int locationIndex = listA.indexOf("5");
        System.out.println("Index location of the String \"5\" is: " + locationIndex);  

        //find the first and the last location of an element
        System.out.println("First occurance search for String \"5\".  Index =  " + listA.indexOf("5"));
        System.out.println("Last Index search for String \"5\".       Index =  " + listA.lastIndexOf("5"));

        //create a sublist from the list 
        List listSub = listA.subList(10, listA.size());
        System.out.println("New Sub-List from index 10 to " + listA.size() + ": " + listSub);

        //sort the sub-list
        System.out.println("Original List   : " + listSub);
        Collections.sort(listSub);
        System.out.println("New Sorted List : " + listSub);
        System.out.println();

        //reverse the new sub-list
        System.out.println("Original List     : " + listSub);
        Collections.reverse(listSub);
        System.out.println("New Reversed List : " + listSub);
        System.out.println();

        //check to see if the lists are empty
        System.out.println("Is List A empty?   " + listA.isEmpty());
        System.out.println("Is List B empty?   " + listB.isEmpty());
        System.out.println("Is Sub-List empty? " + listSub.isEmpty());
        
        //compare two lists
        System.out.println("A=B? " + listA.equals(listB));        
        System.out.println();

        //Shuffle the elements around in some Random order for List A
        Collections.shuffle(listA, new Random());

        //convert a list into an array
        Object[] objArray = listA.toArray();
        for (int j=0; j < objArray.length; j++) {
            System.out.println("Array Element [" + j + "] = " + objArray[j]);
        }

        //clear listA
        System.out.println("List A   (before) : " + listA);        
        System.out.println();
        listA.clear();
        System.out.println("List A   (after)  : " + listA);        
        System.out.println();
        
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        LinkedListTest listExample = new LinkedListTest();
        listExample.linkedListOperation();
    }
    
}



Set, TreeSet, Iterator in Java



/*
 * TreeSetExample.java
 *
 *Illustrates mathematical set operations
 *
 * Created on January 10, 2008, 9:28 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package treesetexample;
import java.util.Set;
import java.util.TreeSet;
import java.util.Iterator;

/**
 *
 * @author Sayed
 */

public class TreeSetExample {
    
    /** Creates a new instance of TreeSetExample */
    public TreeSetExample() {
    }
    
    //example set operations 
     public static void treeSetOperations() {

        final int MAXIMUM = 20;

        //create a TreeSet
        Set ss = new TreeSet();

        //store data in the set, set can contain only one type of data
        for (int i = 0; i < MAXIMUM; i++) {
            System.out.println("  - Storing Data(" + i + ")");
            ss.add(new Integer(i));
        }

        //display set data using an iterator
        Iterator it = ss.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }

        
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        TreeSetExample treeSet = new TreeSetExample();
        treeSet.treeSetOperations();
    }
    
}



Java Bean : Basic Idea



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 



How to upload data from an excel file to database using servlets?



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/



Java Collections Framework



Some URLs
http://www.javaworld.com/javaworld/jw-11-1998/jw-11-collections.html?page=2
http://www.informit.com/articles/article.aspx?p=781700
http://java.sun.com/docs/books/tutorial/collections/index.html
Vector Vs. ArrayList
Vector vs. Hashtable
ArrayList vs. LinkedList



Unit Testing in Eclipse for Java



Unit Testing in Eclipse for Java: just an overview

Why Unit Test?

Say, you have written some Java classes, before making use of them in real application functionalities, it's always better to check whether the classes (their functions/methods) are working properly. Unit tests simply test a single unit like a single class, or a single function at a time. It's almost always a good practice to design the software first, also design the classes and their methods along with interactions among classes, early in the project. After, classes and their methods are written, you should do some testing to make sure they are working properly.

How to Unit test in Eclipse?

1. You need to add junit.jar in your project build path. You can do that by selecting the project, then right click, then select properties, the java build path, then libraries tab, and then add jars/add external jars and select JUnit.jar.

2. You can create a folder to keep your unit test codes say unittestcodes.

3. The basic idea is, to test a class, you will need to create a test case class with methods like setUp, tearDown, and test methods for all the methods that you want to test (one for one). The setUp() method can be used to create the data for testing [you have to write the code though]. The other test methods will call the corresponding class methods using the data to check if the methods are working properly or not. Methods like assertTrue may come handy in the test methods.

4. How to create these test classes and test methods?

Right click the folder for testcode like unittestcodes, select new, select other, type Junit in the text box, select Junit test case...and then provide other parameters like the name of your test class, which class do you want to test, do you want to have setUp(), tearDown() methods or not?. In the next step, you have to select which methods of the class you want to test. Then the test class (skeleton) will be written for you.

5. In the setUp() method, write code to build test data. From the other test methods call the related class methods to test them.

6. How to run the experiment: right click the name of this test class from the left window, select run as, select Junit test case. Now analyze the output and fix the class methods if required. Try with different data, data from different ranges, boundary value data and you know what to test in your use cases.



What is Spring Framework? What does it mean to J2EE developers



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

  1. Transaction Management: A generic abstraction layer for transaction management that removes low-level interactions
  2. JDBC Exception Handling: An exception hierarchy to simplify the error handling strategy
  3. Integration with Hibernate, JDO, and iBATIS
  4. AOP Framework: Aspect Oriented Programming Framework
  5. MVC Framework: Spring provides MVC web application framework built on core Spring functionality


Spring Architecture

  1. Spring AOP: Provides declarative enterprise services such as declarative transaction management
  2. Spring ORM: Provides integration layers for object-relational mapping APIs, including JDO, Hibernate and iBatis for database access.
  3. Spring Web: Provides web application development stack that includes Spring MVC.
  4. Spring DAO: Provides standardization to data access using the technologies like JDBC, Hibernate or JDO.
  5. Spring Context: Provides support for using message sources, and resources. It is based on Java bean.
  6. Spring Web MVC: Provides MVC for web applications.
  7. Spring Core: Provides Dependency Injection features



    EJB 3: Stateless Bean



    
    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



    EJB 2: How to build a stateless EJB

    1. Install an EJB Server
    2. Specify the EJB Remote Interface
    3. Specify the Home Interface
    4. Write the EJB bean Class
    5. Create the ejb-jar File
    6. Deploy the EJB bean
    7. Write the EJB Client
    8. Run the Client



    EJB 3: Statefull 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.");
          }
    
    
       }
    }
    



    EJB 3: Entity Bean Basic



    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



    Comparison EJB 2 and EJB 3

    1. EJB 2.0 has deployment descriptors but EJB 3.0 has no deployment descriptor
    2. In EJB 2.0 you have to write Home and Remote Interfaces But in EJB3.0 you do not need to write Home interfaces
    3. In EJB 3.0, all entities are identified with '@'
    4. In EJB 3.0 methods like ejbPassivate, ejbActivate, ejbLoad, ejbStore, etc. are not required
    5. EJB 3.0 is totally newly designed including the entity manager
    6. EJB 3.0 entity beans are just POJO
    7. No EJB container required to run
    8. EJB 3.0 supports Java Persistence API for all of its data needs
    9. No XMLDeployment Descriptors but annotations
    10. EJB 3.0 entity beans/JPA becomes local
    11. Queries are very flexible. Multiple levels of joins are enabled
    12. EJB 3.0 pluggable, security enabled



    JDBC: Stored Procedure



    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.



    SCJA: Java Really Basic Stuffs - But you may need to know them for exams like SCJA



    SCJA: Syllabus

    http://www.sun.com/training/catalog/courses/CX-310-019.xml

    Floating point types: http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html
    Enumerated types in Java: http://java.sun.com/docs/books/tutorial/java/javaOO/enum.html
    is a finite set of symbolic literals
    is represented as first-class object
    are allowed in case statements
    the literals may be any valid Java identifier

    Java Interface
    an interface may NOT contain any concrete method implementations
    an interface is NOT a class of any style
    an interface is NOT a member of a class
    An interface defines a set of abstract methods that may have many implementations.

    Class Association, Class Composition, dependency:
    Compositions may also have navigation methods, but these methods must NOT pass references to the owned objects. This is usually achieved by passing back a copy of the object rather than the owned object itself.
    Composition implies that the owning object controls the life cycle of the owned object
    Dependency merely imply that one object uses another object during computations.

    disadvantages of proper information hiding?
    Access to object attributes incur a runtime penalty.However, the Sun hotspot JVM usually can eliminate the added overhead by "inlining" the methods where they are called.
    a mutator method is longer than an assignment operation
    it is time consuming to use methods to access object attributes rather than direct access.

    program to an interface
    References to objects should be declared as interfaces rather than concrete classes
    the reference variables to objects that need to be as generic as possible. This is the "program to an interface" principle.

    correct representation of an attribute in UML

    - attr : int uml

    0..1 indicates zero or one multiplicity, which is how you can represent an optional association.

    ? is NOT a valid multiplicity indicator.
    * is an abbreviation for 0..*.
    M is NOT a valid multiplicity indicator.
    ? is NOT a valid multiplicity indicator.
    0..* is exactly how to indicate zero or more.

    Statement types



    Java: Some basic important stuffs



    Data types to represent telephone numbers:

    a string of ten digits can represent all ten-digit telephone numbers.
    an object can hold data (integers or strings) of the elements of a telephone number
    an integer data type can represent all ten-digit numbers
    -- a boolean can only represent two values
    an enumerated type can only represent a fixed number of constant



    Abstract Class:

    An abstract class may have constructors, but it is illegal to invoke the new operator on an abstract class
    An abstract class is allowed to have method implementations
    There is no restriction about the placement of abstract classes in a class hierarchy
    It is legal for an abstract class to implement an interface and implement one or more interface methods



    Design a role player game:

    creating an abstract superclass for a generic player will simplify the design.
    This is because the maintenance of the common methods will be simplified.
    An abstract class is the perfect container, as a superclass, for the common methods



    Model

    A sports team with fixed number of players in which players may participate in other teams
    a many-to-many association from players to team Will work

    Java Bean convention for setter methods

    void setFirstName(String value)



    Data Hiding

    A well-encapsulated class must have all of its attributes marked private.
    A well-encapsulated class must hide all internal methods. This is because this is NOT part of the class's public interface.
    NOT all attributes require accessor or mutator methods.

    The principle of "programming to an interface"?

    Generalize the return type of a method. The return type of a method should be as abstract as possible, such that any object of that type could be returned. If a concrete class is used as the return type, then only an object of that type (or its subclasses) can be returned.

    A class hierarchy is a static part of the code structure. Polymorphism and program to an interface are principles that apply to the dynamic aspects of the code, such as the objects that are stored in variables and passed through methods.

    The parameter type of a method should be as abstract as possible, such that any object of that type could be passed in to the method. If a concrete class is used as the parameter type, then only an object of that type (or its subclasses) can be used as a parameter.

    The type of an instance variable should be as abstract as possible, such that any object of that type could be held by the owning object. If a concrete class is used as an instance variable type, then only an object of that type (or its subclasses) can be held in that variable.

    The relationship between classes and interfaces form only a static part of the code structure. Polymorphism and program to an interface are principles that apply to the dynamic aspects of the code



    JAVA: Some links: useful for exams like scjp/scja



    Assertions in Java: http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html
    Enum in Java:http://www.java2s.com/Code/Java/Language-Basics/Enum.htm
    StringBuffer and StringBuilder Classes have similar methods where StringBuffer is synchronized: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuilder.html
    Serialize and Deserialize: http://java.sun.com/j2se/1.4.2/docs/api/java/io/Serializable.html
    java.util package is very important: http://java.sun.com/j2se/1.4.2/docs/api/java/util/package-summary.html



    SCJP: Java Operators



    Exams like SCJP test your understanding of Java operators and how to use them like:
    assignment operators: =, +=, -=
    arithmetic operators: +, -, *, /, %, ++, --
    relational operators: <, <=, >, >=, ==, !=
    logical operators: &, |, ^, !, &&, ||
    conditional operators: ? :
    Also operators to check the equality of two objects or two primitives

    In the following table operators and their precedences are shown. Upper rows operators have higher precedence. Same row operators have equal precedence. For equal precedence operators, All binary operators except the assignment operators work from left to right while assignment operators work from right to left.

    Operator Precedence
    OperatorsPrecedence
    postfixexpr++ expr--
    unary++expr --expr +expr -expr ~ !
    multiplicative* / %
    additive+ -
    shift<< >> >>>
    relational< > <= >= instanceof
    equality== !=
    bitwise AND&
    bitwise exclusive OR^
    bitwise inclusive OR|
    logical AND&&
    logical OR||
    ternary? :
    assignment= += -= *= /= %= &= ^= |= <<= >>= >>>=
    The following quick reference summarizes the operators supported by the Java programming language.

    Simple Assignment Operator

    =	Simple assignment operator
    

    Arithmetic Operators

    + 	Additive operator (also used for String concatenation)
    - 	Subtraction operator
    *	Multiplication operator
    / 	Division operator
    %	Remainder operator
    

    Unary Operators

    + 	Unary plus operator; indicates positive value (numbers are positive without this, however)
    - 	Unary minus operator; negates an expression
    ++  	Increment operator; increments a value by 1
    --    	Decrement operator; decrements a value by 1
    !     	Logical compliment operator; inverts the value of a boolean
    

    Equality and Relational Operators

    ==	Equal to
    !=	Not equal to
    >	Greater than
    >=	Greater than or equal to
    <	Less than
    <=	Less than or equal to
    

    Conditional Operators

    && 	Conditional-AND
    || 	Conditional-OR
    ?:      Ternary (shorthand for if-then-else statement)
    

    Type Comparison Operator

    instanceof	Compares an object to a specified type 
    

    Bitwise and Bit Shift Operators

    ~	Unary bitwise complement
    <<	Signed left shift
    >>	Signed right shift
    >>>	Unsigned right shift
    &	Bitwise AND
    ^	Bitwise exclusive OR
    |	Bitwise inclusive OR
    



    Details about java operators



    SCJP: Classpath and Jar



    Java certification exams like SCJP test your knowledge about java classpath. Check here for an excellent resource on the topic .

    System classpath

    We can specify classpath in the command line or make use of a `system' class path. The IDEs have their own way of maintaining class paths. System class paths will be used by both the Java compiler and the JVM in the absence of specific instructions.

    Set Linux System Classpath:
    CLASSPATH=/myclasses/myclasses.jar;export CLASSPATH

    Windows:
    set CLASSPATH=c:\myclasses\myclasses.jar

    For permanent result, in Linux, put the commands in the file .bashrc in your home directory. On Windows 2000/NT, set it from `Control Panel', System, Environment Variables.

    You can also specify .jar files full of your required classes in your classpath.

    CLASSPATH=/usr/j2ee/j2ee.jar:.;export CLASSPATH

    where the `.' indicates `current directory'.

    From command line, if you want to add more paths to the classpath use:

    Linux:javac -classpath $CLASSPATH:dir1:dir2 ...

    Windows:javac -classpath %CLASSPATH%;dir1:dir2 ...

    if you have spaces in your path use double quote to concatenate words.

    Also check this resource



    SCJP: Topics and Resources : will be continued



    SCJP topics and related resources are provided. I have skimed through the resources at least one time.

    Garbage Collection

    Parameter Passing Command Line Parameter
    Access Modifiers, Package Declaration, Import
    Concurrency:java.lang.Thread and java.lang.Runnable Java Thread:wait/notify/notifyall-lock OOP Concept 1



    Java Collection Framework



    Array
    Benefits Constraints
    • Data access is fast.
    • Good for ordered data, which is not changed or searched frequently.
    • Inefficient if number of elements grow.
    • Inefficient if an element to be inserted in middle of collection.
    • Provides no special search mechanism.


    Linked List
    Benefits Constraints
    • Allows efficient inserts/delete at any location
    • Allows arbitrary growth of collection.
    • Applying order to the elements is easy.
    • Slower while accessing elements by index.
    • No special search mechanism is provided.



    Tree
    Benefits Constraints
    • Easy addition/deletion in middle.
    • Allows arbitrary growth.
    • A better and efficient search mechanism.
    • Ordering is peculiar and some comparison mechanism is required.
    • Searching is not efficient for unevenly distributed data.



    Hashtable
    Benefits Constraints
    • Efficient searching.
    • Good access mechanism.
    • Allows arbitrary growth of collection.
    • Not good for small data set because of overheads.
    • Overhead for storing keys for the values in collection.
    • Overhead of hashing scheme.



    SCJP: Language Fundamentals



    Class declaration and java source file.

    Keywords and Identifiers

    abstract do import public transient
    boolean double instanceof return try
    break else int short void
    byte extends interface static volatile
    case final long super while
    catch finally native switch
    char float new synchronized
    class for package this
    continue if private throw
    default implements protected throws

    Default Values, Local Variables

    Arrays

    Argument passing during method calls



    SCJP: Garbage Collection



    Garbage Collection



    SCJP: Flow controls and exception



    Flow Control and Exceptions Flow control statements

    switch statement

    switch(expression){
    case ConstantExpression: statement(s);
    case ConstantExpression: statement(s);
    .
    .
    .
    default: statement(s);
    }

    break and continue

    Checked and Unchecked Exceptions

    Checked Exceptions Unchecked Exceptions



    Code Conventions for the Java Programming Language



    Why Have Code Conventions?

    Java Code Conventions



    SCJP: Class Declarations



    class declarations

    Abstract Classes

    Nested Classes



    SCJP: Interfaces



    Interface



    SCJP: Random Stuffs





    Java : SCJP: Important Resources





    SCJP: Basic Java I/O





    SCJP: Java Concurrency





    Java: Collections Frameworks





    SCJP: Rules





    Sun certifications: Topics





    SCEA:Security in Java: Potential threats to a system and how to address the threats:Java Enterprise Architect





    SCJP: Short Notes





    Java Design Patterns: Architectural Frameworks





    Java: Common Architectures





    SCJP: More Rules





    SCJP Practice Exams



    Check these practice exams. Be careful that many java rules may have changed over the time. Check that which jdk version or the exam these practice exams support



    SCJP Essential Knowledge





    SCWCD: Essential Knowledge : Web Development in Java





    Regular Expressions





    Generics in Java





    Basic Java But Essential Knowledge for exams like SCJA, or to the project managers new to Java technologies





    Java Rules





    Java Web-sites ad Forums





    Maven 1.0: A pretty good article: Compare Ant and Maven





    Essential Knowledge on Web Component Development





    Servlet, JSP Specifications





    JSP: Reference Manuals





    EJB 3.0: Specifications : Simplified API





    A simple EJB 3.0 application: Explanation of EJB 3.0 technology: EJB => Spring Framework





    Java Design Patterns and Examples





    Your First EJB Application





    Java Fundamentals





    Java File Operation Example



    Code that helped me to create http://add.justEtc.net - the Bangladesh section based on the the web-site http://winnipeg.justEtc.net

    package hello;
    
    import javax.swing.JOptionPane;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.io.*;
    
    /**
     * Created by IntelliJ IDEA.
     * User: Sayed Ahmed
     * Date: May 30, 2008
     * Time: 9:45:08 PM
     * To change this template use File | Settings | File Templates.
     */
    
    /**
    Class containing major methods - operation methods
    */
    class Process{
        private FileReader src = null; //source folder
        private FileWriter dest = null; //destination folder
        private ArrayList cityList = new ArrayList(); //arraylist to contain the names of all cities
    
        private String cityFileName; //reference to the file containing all city names
        private String folderToCopy; //path to the folder to be copied
        private String destination; // path  to the folder where the copy will be kept
    
        /**
         * Constructor
         */
        Process(){
    //JOptionPane.showInputDialog(null,"City File Name");
            cityFileName = "C:\\test_development\\java\\resources\\cityList.txt";  
    //JOptionPane.showInputDialog(null,"Folder to Copy");
            folderToCopy = "C:\\test_development\\java\\hello\\src\\resources\\source\\Winnipeg";  
    //JOptionPane.showInputDialog(null,"Destination Path"); 
            destination = "C:\\test_development\\java\\hello\\src\\resources\\destination";         
    
            //load city list from the file to an arraylist
            copyCityList(cityFileName);
    
            //to create a file with links to all the cities of Bangladesh
            createFile();
    
            //copy a folder (winnipeg) and rename it to all the city names of Bangladesh -- one by one
            Iterator it = cityList.iterator();
            while(it.hasNext()){
                copyDirectory((String) it.next());
            }
    
        }
    
        /**
         * load city list into an ArrayList
         */
        private void copyCityList(String cityFileName){
            String city = "";
            try {
                BufferedReader bfCity = new BufferedReader(new FileReader(cityFileName));
                while(null != (city = bfCity.readLine())){
                    cityList.add(city);
                }
            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            } finally {
            }
        }
    
        /**
         * copy a folder , name the folder as the city name
         */
        private void copyDirectory(String city){
            try {
                copyDirectory(new File(folderToCopy), new File(destination+"/"+city), city);
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        /**
         * Copies all files under srcDir to dstDir.
         * If dstDir does not exist, it will be created.
         * @param srcDir - folder to copy
         * @param dstDir - where to keep
         * @param city  - new folder name
         * @throws IOException
         */
        public void copyDirectory(File srcDir, File dstDir, String city) throws IOException {
            //if srcDirectory is a directory , create the directory
            if (srcDir.isDirectory()) {
                if (!dstDir.exists()) {
                    dstDir.mkdir();
                }
                //if srcDir has child directories , create child directories - Recursively
                String[] children = srcDir.list();
                for (int i=0; i
    
    



    Hello World: Web Service Application: IntelliJ, Tomcat, Apache Axis/Glassfish



    This is an excellent document to start with. A sample server and a sample client are built in both Apache Axis and Glassfish



    Skeleton of the Ant File



    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.



    Java Connector Overview and an Example



    • Java Connector Architecture (JCA) enables integration of the J2EE components to any Enterprise Information Systems (EIS). EIS can be heterogeneous where scalability is a must.
    • JDBC assumes DBMS/RDBMS in the back-end, JCA targets any kind of EIS.
    • One of the key parts of JCA is the Resource Adapter - usually a part of the application servers. Multiple resource adapters can be used to connect to different EISs of heterogeneous types.
    • When resource adapters are plugged into the Application Servers they provide necessary transaction, security, and connection pooling mechanisms
    • In the JCA, an application contract defines the API that provides the client view to access EISs. The API can be EIS/resource adapter specific or standard.
    • Common Client Interface (CCI) - a set of interfaces and classes that allows J2EE applications to interact with heterogeneous EISs.
    • Example of JCA
      • EJBs, Servlets can connect to EISs through CCI and then access the EISs as required
      • J2EE SDK provides a black box resource adapter that we will use in our example to connect to EISs. We will assume RDBMS as the EIS in the example
      • Example: The flow of the application: client->servlet->resource adapter->EIS Tier (RDBMS - stored procedure)
      • In a servlet example: first step: import javax.resource.cci.*;
      • javax.resource.cci.*; - for ResourceException class
      • import cci blackbox classes: import com.sun.connector.cciblackbox.*;
      • Also, import servlet and application specific classes
      • 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();
              }
          }
        
      • Now define the doGet method for processing. An example doGet method is as follows
      • 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();
          }
        }
        
      • getAccountAccountCount() method: to query the database and determine the number of rows in the account table
      • 
        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;
        }
        
        



    EJB Overview: EJB in a nutshell



    • Objects provide encapsulation/re-usability at the class level.
    • A component can be comprised of multiple objects
    • Component = logical groups of classes = distributed objects = business objects
    • A component can be developed to address a specific enterprise applications.
    • Hence, components can provide significant encapsulation/re-usability in the partitioned enterprise problems.
    • Component model = components + their environments + contracts for interaction
    • EJB is a server side component model. Used to create application server side components
    • Most sophisticated application server = CTM = Transaction Processing Monitors + Object Request Brokers = J2EE Servers
    • EJB components: entity, session, message-driven
    • Entity beans = real world objects = business objects = data objects = customers = products = may be contained as records in the database = persistent
    • Multiple clients can access entity beans concurrently
    • Session beans = processes + tasks. Example: the act of reserving a ticket = to control work flow = to handle a series of tasks carried out by the entity beans = can also access/(help to access) data = do not represent data = transient = after the task is done - no need to maintain states = do not need to support concurrent access
    • Message-driven beans = stateless beans = no component interface = respond to client requests = clients place requests through JMS = support concurrent client access = can be used to perform tasks and manage interactions among beans = asynchronous = request and response two separate processes, RMI = synchronous



    Accessing EJBS from Servlet



    • EJBs can be used to create enterprise applications like banking systems. Clients will interact with such systems for operations like: withdraw cash, transfer cash, pay bills
    • When clients directly access EJBs it poses concerns such as: security risks, firewall blocking, EJB architecture becomes transparent to the clients
    • Servlets can act as the middleman between the EJBs and clients.
      • Change to EJB becomes easier - hidden from the user
      • Data in EJB better protected
      • Central control of EJBs
    • When servlets work as the proxy, smaller devices become capable to access EJBs through http protocol (light weight protocol - good for smaller devices )
    • Servlets can work as a front controller
    • Supports different types of clients
    • Better separation of responsibilities that is desirable - web: flow control logic, EJBs: business logic, EIS: Enterprise Information Systems
    • Remember: servlets can be bottlenecks here, better servlet design strategy is required - synchronization may help
    • For small applications - may be overkill
    How to use EJBs from servlets
    • Think about a banking system implemented in EJBs.
    • Entity beans = Customers, Accounts
    • Session beans = operations like withdraw cash
    • In this scenario, servlets can call the session beans and return the results to the clients
    • A sample servlet to access the EJBs: Here remote ejbs are assumed : EJB2 is assumed : just example is shown - the coding style may not be great ... just an example
    • // 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){
      }
      
      }
      }
      
      
      



    Servlet Random Information



    • Web component information sharing: web context (ServletContext), request, session, and page
    • ServletContext - Scope: entire web-application (Servlets & JSPs)
    • page/PageContext : A single point of access for many of the attributes of a JSP page
    • For each access of the servlet a thread is created. In applications a thread can be accessed concurrently by many threads.
    • If the servlet accesses and edits some external resources, then data inconsistency, and data loss may occur
    • Synchronized access should help:
    • public class TestServlet extends HttpServlet implements SingleThreadModel will provide synchronization and concurrency
    • In JSP, you can include <%@ page isThreadSafe="false" %> - to provide thread safety
    • For SingleThreadModel: you still have to synchronize access to class variables and to any shared resources that are stored outside the servlet. example:
      
       synchronized(sharedResource) {
       }
      
      
    • For high-traffic servlets, you should use explicit synchronization blocks rather than implementing SingleThreadModel
    • Synchronization is only an issue if the servlet accesses external data resources -- returns data from another source: not for a servlet that just performs a task with no data access



    Java 2 Security Architecture



    • Security Services Provide
      • Data Integrity
      • Data Confidentiality
      • Access Control - Authentication and Authorization
    • Encryption helps to provide such security services
    • Core Java Security Architecture
      • -- Core Java 2 Security Architecture
      • -- Java Cryptography Architecture (JCA)
      • -- Java Cryptography Extension (JCE)
      • -- Java Secure Socket Extension (JSSE)
      • -- Java Authentication and Authorization Service
      • -- JCE and JSSE extends JCA
    • JCA - Platform Packages
      • java.security - core security classes and interfaces
      • java.security.cert - certificate management
      • java.security.interfaces - Interfaces used to manage DSA and RSA keys
      • java.security.spec - key specification, algorithm parameter specification
    • JCA - not useful for data encryption
    • JCE provides the data encryption
    • JCE packages: javax.crypto, javax.crypto.interfaces, javax.crypto.spec
    • JSSE includes a Java implementation of SSL and Transport Layer Security (TLS) - server authentication, message integrity, optional client authentication.
    • JSSE Packages: javax.net.ssl, javax.net, javax.security.cert
    • JAAS : limit access to resources based on user identity. JAAS implements PAM (Pluggable Authentication Module Framework) - user-based, group-based, role-based access control
    • JAAS packages: javax.security.auth, javax.security.auth.callback, javax.security.auth.login, javax.security.auth.spi
    • Core Security
      • java.security.Permission, PermissionCollection, Permissions - specify level of access to resources in J2EE applications
      • Permissions - sets of diverse permissions
      • Permission Example:
      • Permission has many subclasses like FilePermission, SerializablePermission, SocketPermission, NetPermission
      • FilePermission prm = new FilePermission("c:\\test.img","read,write");
      • Security Policy - list permissions in files System Policy - jre/lib/security/java.policy file User Policy - java.policy file under user's directory
      • Java 2 has a policy tool under [JAVA_HOME\bin\policytool]- GUI based - to create/edit policy files - type policytool in the command prompt
      • Java Security Manager - determines whether requests to the access valued resources should be allowed? - core java security classes also ask security manager
      • For access permission check
      • Access Controller controlls access to critical system resources. Security Manager calls Access Controller methods to delegate tasks
    • J2EE Application Security
      • J2EE Role Based Security
      • J2EE applications can contain both protected and unprotected resources. Access to the protected resources can be controlled using authorization mechanisms.
      • Authorization
        • Identification : recognize an entity - device or person
        • Authentication : process to identify
      • Role based security: create logical privileges known as roles - may be based on customer/user/job profile
      • Users are grouped together into the roles - same role users into the same role group
      • Creating roles for J2EE Applications: Create roles, associate them with an application, WAR file, JAR files
      • At the time of deployment, the deployer maps roles to the security identities
      • Principle: identity assigned to a user or group after authentication
      • A tool named deploytool can be used to add users and groups to a J2EE server.
      • You can get J2EE and deploytool at: http://java.sun.com/javaee/downloads/index.jsp
      • In deploytool menu->tools->server configuration->select users from left -> select reals from right ->
      • Provide ID/Password for the user. Assign a group to the user. - Rest will be common sense, play with the tool
      • You can also use realmtool to add users and groups example: realmtool -add 5006 5006admin admin,staff Syntax: -add user password groups add, import, userGroups
      • Under deployment tool, afterwards, you can apply permissions to the different applications. You can also view and modify the descriptor file from : menu->tools>view configuration.



    J2EE:Java EE Code Samples & Apps





    J2EE Architecture: J2EE Design Patterns: Related Concepts



    • Design Patterns
      • What are design patterns? Design patterns are specific/(context-based) solutions/approaches to address specific problems/situations. Some problems are general/open problems and very common problems in a particular type of applications. Design patterns can be created to solve such problems in a specific context and that can be re-used every time that type of situations arise. Design patterns help designers to easily communicate their ideas (in a common concept).
      • Benefits: Proven solution to a specific problem, saves time as you don't have to come up with an original solution each time you encounter a particular problem
      • Design patterns can be applied at different levels of abstractions such as, Analysis, Architectural, Behavioral, Creational, Design, and Structural
      • J2EE patterns are mostly for design and architecture purpose and for three architectural tiers: Presentation, Business, and Integration
    • J2EE Applications: Client Tier (Clients for J2EE Applications): Design Issues
      • J2EE supports many types of clients. Hence, you need to decide which type of client you want to make use. Also, based on the clients you need to decide how to solve a specific problem. Design patterns can be client-specific and problem-specific
      • J2EE clients: laptops, desktops, palmtops, and cell phones.
      • Connection Mechanisms (to J2EE Applications): an intranet, the Internet, a wireless network, a wired network, and a combination of wired and wireless networks
      • Clients can be thin, server dependent, browser based, rich, and stand-alone
      • Client design issues: Concerns: which types of clients to use, should more than one type of clients be supported?, network types to support, security considerations, platform considerations, and unreliability of networks
      • Clients should: Connect to the network on an ad-hoc basis, transmit minimum amount of data, should consider situations when firewalls may block particular protocols, mobile clients should consider that they have small display screens and limited resources
      • More design issues for J2EE clients: Logic for user interface presentation, validate user inputs, communicate with the server using a common protocol, maintain the conversational state
      • Browser clients - design issues: can not function independently of the server, easy to design and implement, widely available, well-familiar to the users, provide limited functionality, can perform user input validation, servers can also do the validation, uses HTTP protocol, needs to maintain conversational states using Cookies, URL rewriting, or server side session
      • Java clients - design issues:
      • Client types: applications, applets, MIDlets are the Java client options
      • Applications like usual desktop applications - can run offline, use JFC/Swing for user interface, provide richer user experience, more responsive than thin clients, use less bandwidth than browser clients, and can create fewer connections than browser clients
      • Applets run mostly under browsers, use JFC/Swing for user interface
      • MIDlets are mostly for small applications for cell phones, two-way pagers, and palmtops - use MIDP user interface APIs
      • Java clients (Applications, applets, MIDlets) can handle most user input validation and hence, reduce network overhead, can connect to J2EE applications, directly to the web tier (using HTTP though face some complexity of translation), EJBs, EISs,
      • Applets and applications can connect to EJBs directly,
      • Java clients can access EIS tier directly (not recommended as it would bypass J2EE server and transaction management)
      • Java clients have the facility to cache and manipulate large amounts of state in memory and manage session effectively
    • Web Tier
      • Servlets, and JSPs are web-tier component
      • Manage the interaction between web-clients and the application's business logic.
      • Output from this tier: mostly HTML and XML content
      • Business logic can be implemented entirely here, though, enterprise beans are recommended
      • Servlets should be used to: implement web-application logic, generate binary content, act as a web-tier controller
      • JSPs are better suited to generate static HTML text
      • JSP Purpose: produce structured textual content, generate XML messages, act as templates
      • In JSP, custom tags are more desirable than scriptlets. Why? scriplets - not reusable, mix logic with content, make JSP pages difficult to read and update, errors can be difficult to interpret, difficult to test (including unit testing)
      • Web-Tier Application Framework
        • Many web-tier application requirements are not met by the actual J2EE platform. A framework working on top of J2EE can meet these requirements such as, dispatching requests, invoking model methods, and compiling views.
        • Making use of existing ready-built and proven application framework is recommended than creating your own [it takes time and may be all your designs will not be the best]
        • Some frameworks: J2EE blueprints Web Application Framework, Apache Struts, JavaServer Faces
      • Model View Controller (MVC)
        • Well-suited for interactive applications such as web-applications.
        • Divides applications into three modules - model, view, controller
        • model: data representation and business logic, view: data presentation and user input, controller: controls information flow
        • Benefits: separation of design and implement, decreased code duplication, centralized control
        • Servlets are ideal as controllers
        • Controllers receive all incoming client requests and direct them to the appropriate business logic component, after processing the requests, the controller selects the right view to return to the client.
      • Model 1 and Model 2
        • Model 1: No controller, direct access to the JSP pages, decentralized application, simpler and hence suited for small and static applications
        • Model 2: Uses a controller, are favored as they are easy to maintain and extend, provide a single point for security and logging
    • EJB Tier
      • Hosts business logic of a J2EE application
      • Provides system level services to the business components
      • Developers can focus on business-logic problems
      • J2EE platform handles the system related problems (complex many times) such as, state maintenance, transaction management, and availability to local and remote clients
      • EJBs provide a good interface between presentation components in the web-tier and business data and systems in the EIS tier
      • EJBs - entity, session, message driven
      • EJBs can provide remote or local access by providing remote or local interfaces. EJBs are mostly designed for distributed environments and hence typically provide remote interfaces
      • When to use entity beans: for business objects when it represents persistent data and requires persistent storage, multiple client access, data access in portable manners, server managed transaction handling is preferable
      • Entity beans: Persistence can be managed by yourself or by the EJB container
      • When to use Stateful Session-beans: for client centric business logic, business objects are short-lived, and non-persistent. Works for the client to maintain conversational state
      • When to use Stateless session beans: Provide server side behavior, do not maintain states for a specific client, good for reusable service objects, to minimize resources and support a large number of clients, when the business object does not operate on instance variables.
    • EIS Tier
      • J2EE EIS technologies: J2EE Connectors to integrate J2EE applications with existing EISs using resource adapters - synchronous
      • Java Message Service: To be used with enterprise messaging systems - asynchronous
      • JDBC - integrates J2EE applications with relational database systems
      • asynchronous: high quality and reliable message-delivery service, provide higher volume of messaging, more work for the developers
      • synchronous - suitable to handle two or more EISs synchronously.