Category: java

Hey Ppl!! I am glad to finally get the time to post on my blog again…..

As a part of my curriculum I had to create an online shopping cart. Since I thought of doing it in JSP where in I could some AJAX to make it fancier :).  Well the choice of  IDE for me was to go for RAD (Rational Application Developer) 7.5 with WAS (Websphere Application Server)  CE and DB2 as the back end.This is a basic project but is a good learner for those who are new to JSP, servlets or AJAX. This is also be useful if you are looking to get familiarized with the IDE.


Overview :

Lets draw an outline of the project. We have 2 use cases to the project viz Administrator and Customer. We take them one by one.
ADMIN end:

  • Ability to add products
  • Managing the categories that these products belong to
  • Search Transaction
  • Search Customer
  • Search for product and ability to edit product inf

Next, On the Customer End:

  • View product and its details
  • Register
  • Login
  • Add product to cart and checkout
  • Viewing transaction records

Lets take up the database for such a system. I have taken the snapshot right out of DB2 listing the tables there in (click to expand).



Snapshots :

Lets look at the snapshots of the project first and then we will discuss the problems faced and their solutions.



Hurdles :

Creating & calling stored procedures on DB2.

With RAD thats very easy!! Follow the steps:

  1. Switch to Data Perspective.
  2. If haven’t already create a new project data development proj say
    ‘ShopDev’. While doing so you will be asked to connect to the DB2
    database please make sure you enter the DB2 credentials correctly and
    dont forget to test the connection.
  3. Right click on the ShopDev in the project navigator and select
    new stored procedure. 
  4. Make sure you choose java as the language (unless you want to use
    sqlj) and create the query, set up I/O parameters and you will have a
    stored procedure created for you. This might not be exactly you want so
    you can edit it now. (for eg look in folder
    /workspace/ShoppingDev/JavaSource/com/db2admin/db2admin/*.java)
  5. Once done, you can right click on the procedure and select the
    option generate JavaBean class to get the .java file in your dynamic
    web project. (these can be found in 
    /workspace/ShoppingCart/src/genbeans/ )
  6. Now you can use this class to instantiate it in JSP or as Beans..

Image/File Uploads for products

I have seen a lot of posts over the internet for this. But it was
difficult to find one good solution. Our objective was to upload the
file to database
so the approach that we follow is to first upload the file to a
temporary folder on the server then onto the database.

Uploading To FileSystem On Server:
To do so the Apache Commons FileUpload package will do the work
for us.
Just include the library in your path or add it as a reference.
First lets see the jsp page with form that is going to submit both
variables and upload data. (important to note enctype)


<form id="addProduct" enctype="multipart/form-data"
action="AddProduct" method="post">

The code snippet shows the use we make of it in a servlet. Here the
form sends some variables and 3 image files:


import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.FileUploadException;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**

 * Servlet implementation class AddProduct

 */

public class AddProduct extends HttpServlet {

    private static final long serialVersionUID = 1L;

       

    /**

     * @see HttpServlet#HttpServlet()

     */

    public AddProduct() {

        super();

        // TODO Auto-generated constructor stub

    }

    /**

     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

     */

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // Create a factory for disk-based file items

        

        DiskFileItemFactory factory = new DiskFileItemFactory();

        String SUBCAT = null,Name = null,BRAND = null,Description = null;

        int Price = 0,Qty = 0;

        byte[][] Image=new byte[3][5*1024*1024];

        // Set factory constraints

        factory.setSizeThreshold(5*1024*1024);

        factory.setRepository(new File("/tmp"));

        

        // Create a new file upload handler

        ServletFileUpload upload = new ServletFileUpload(factory);

        int cnt=0;

        // Parse the request

        List items;

        try {

            items = upload.parseRequest(request);

        

        Iterator iter = items.iterator();

        

        while (iter.hasNext()) 

        {

            FileItem item = (FileItem) iter.next();

            // Process a file upload

            if (item.isFormField()) {

                String name = item.getFieldName();

                if(name.equals("SubCat"))

                    SUBCAT = item.getString();

                else if(name.equals("PName"))

                    Name= item.getString();

                else if(name.equals("Brand"))

                    BRAND = item.getString();

                else if(name.equals("Quantity"))

                    Qty = Integer.parseInt(item.getString());      

                else if(name.equals("Price"))

                    Price= Integer.parseInt(item.getString());        

                else if(name.equals("Description"))

                    Description = item.getString();

            }

            if (!item.isFormField()) 

            {

                String fieldName = item.getFieldName();

                String fileName = item.getName();

                String contentType = item.getContentType();

                boolean isInMemory = item.isInMemory();

                long sizeInBytes = item.getSize();

                if (sizeInBytes<=10)

                    continue;

                File uploadedFile = new File("/tmp/up" + ++cnt +".jpg");

                try {

                    

                    item.write(uploadedFile);

                } catch (Exception e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                    return;

                }                

            }

        }

        } catch (FileUploadException e1) {

            // TODO Auto-generated catch block

            e1.printStackTrace();

            return;

        }

        AddProductBean apb=new AddProductBean();

        System.out.println("CNT= " + cnt);

        FileInputStream[] fis=new FileInputStream[3];

        for(int i=1;i<=cnt;i++)

        {

            File f=new File("/tmp/up" + i +".jpg");

            fis[i-1]=new FileInputStream("/tmp/up" + i +".jpg");

            Image[i-1]=new byte[(int) f.length()];

            System.out.println(fis[i-1].read(Image[i-1], 0, (int)f.length()));

        }

        String str="khali";

        byte[] n=str.getBytes();

        System.out.println("Len= " + Image[0].length + " "+ Image[1].length + " "+ Image[2].length + " ");

        try {

            if(cnt==3)

                apb.execute(SUBCAT, Name, BRAND, Price, Qty, Description, Image[0], Image[1], Image[2]);

            else if(cnt==2)

                apb.execute(SUBCAT, Name, BRAND, Price, Qty, Description, Image[0], Image[1], n);

            else if(cnt==1)

                apb.execute(SUBCAT, Name, BRAND, Price, Qty, Description, Image[0], n, n);

            else

                apb.execute(SUBCAT, Name, BRAND, Price, Qty, Description, n, n, n);

            for(int i=0;i<3;i++)

            {

                if(fis[i]!=null)

                    fis[i].close();            

            }

            if(apb.getRes()>=0)

            {

                response.sendRedirect("AddedProduct.jsp");

            }

        } catch (SQLException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

    }

A very common question was getting servlets to work. The error is that
httpservlet is not found.

To correct that you need to add
reference to j2ee.jar that can be found here


Extensions :

  1. Add provision for product offers or discount offers.
  2. Support for preview of multimedia products and downloadable
    products like
    games/softwares.
  3. Recommended products can be evaluated via Apriori algorithm.

Download :

Finally, here you can download the complete workspace for the project.
Download Workspace

java Web

I developed this conference client just for me in my free time….
v Hybrid architecture (Client Server and P2P) based Instant Messenger.
v It has features like text messaging with text formatting inclusive of smiley, audio and video chat.
v It has a Desktop Sharing feature wherein users can view/share their desktop among themselves.
v It is cross platform as it is based on Java and it uses MySql as backend. It is dependent upon JMF (Java Media Framework)

here is a video in which i demonstrate how to go about using my project.

I have also included a log file. Please send me the log file in case you encounter any errors.

Here are the executables.

java

Here is my problem statement :

To Implement these 4 functions

1.// return a list of all the table names in the database

// as an ArrayList<string> which looks like:

// [tableName1, tableName2, tableName3, …, tableNameN]

ArrayList<string> getAllTableNames()

2.
// return the primary key of a given table

// as an ArrayList<string> with the primary key columns in proper

// order

ArrayList<string> getPrimaryKey(String tableName)

OR PREFERABLY:

write a method to return all the primary keys of all the tables at once.

3. // for a given table, return a list of 4-tuples which are

// the relational constraints from foreign tables into this

// table’s primary keys. Each 4-tuple looks like this:

// [PKTABLE_NAME, PKCOLUMN_NAME, FKTABLE_NAME, FKCOLUMN_NAME]

public ArrayList<arraylist<string>> getTableConstraints(String tableName)

OR PREFERABLY:

write a method to return all the relational constraints of all the tables at once.

4.// return a list of all the columns in the database as

// a list of triples. Each triple looks like this:

// [TABLE_NAME, COLUMN_NAME, DATA_TYPE]

ArrayList<arraylist<string>> reallyGetColumns()

My PROPOSED SOLUTION:

For getting the foreign key relationships you’ll have to enable the read permission to system table via access (refer to screenshots).

Next :



For getting the foreign key relationships you’ll have to enable the read permission to system table vi access (refer to screenshots).

Here are the Function Prototypes that are called :

1. private ArrayList<string> gettablenames(Connection con) throws SQLException

2. private ArrayList<string> getprimarykey(Connection con,String tablename) throws SQLException

3. ArrayList<arraylist><string>> getforeignKeys(Connection con,String tablename) throws SQLException

4. ArrayList<arraylist><string>> reallyGetColumns(Connection con) throws SQLException

Test The application by double clicking the jar. I am also attaching the database that i used to test it.


Here is the Executable To Test. Get it Now (sample Db included).

Here is the Source Code And Executable

: NetBeans Project

: Eclipse Project

java