leejeok

The Remarkable Everyday

Remote Connect to MySQL On OpenSUSE From Different Host

Posted by leejeok on October 16, 2008

Unlike to Ubuntu 8, OpenSUSE 11 is equipped with Firewall and ON by default. You may need to grant the permission to allow remote access to the MySQL server from the client.

 

Computer à YaST (at system menu) à Security and Users à Firewall

 

At the firewall configuration panel à Allowed Services à At Service to Allow, select MySQL Remote Access à Click Add button à Click Next button.

 

Be sure to start the mysql services. If not you can go to the terminal and type this command:

sudo /etc/init.d/mysql start

 

Also, make sure the user had the privilege to access the MySQL database from different host. If not you add the user using MySQL command:

GRANT ALL PRIVILEGES ON *.* TO ‘some_user’@’%’ IDENTIFIED BY ‘some_password’ WITH GRANT OPTION;

Posted in MySQL, OpenSUSE | Leave a Comment »

Install Java, Tomcat and MySQL on OpenSuse 11

Posted by leejeok on October 16, 2008

We will install the JRE, Tomcat and MySQL for hosting JSP web application with database backend. The installation are simple and will be done through the YaST management tools.

 

Launch YaST

Computer à YaST (at system menu) à enter root password à Software (at YaST control center) à Software Management.

 

Install JRE

1. We will require JRE in order to run Tomcat later. If you wish to do a development using Java programming, you may install both JDK and JRE together. At the filter field, type jdk.

 

2. Select java-1_6_0-openjdk for JRE (or java-1_6_0-openjdk-devel for JDK – for development). Next, click the Install button. Click Apply to download and install.

 

 

Install Tomcat

1. Download the tomcat 5.5 from http://tomcat.apache.org/ and saved it to desktop. Here, apache-tomcat-5.5.26.tar.gz been used. Right click on the file and click on Extract Here.

 

2. Rename the folder to tomcat for easier to remember the folder name. It is good idea to move the tomcat to /usr/local directory.

 

3. Type the command sudo mv tomcat-on-your-desktop-path /usr/local

 

4. You need to tell the tomcat where the JRE has been installed and to do this you need to define the JAVA_HOME environment variable in .bashrc file.  At the terminal, type the command: gedit ~/.bashrc

 

5. At the end of the file type export JAVA_HOME=your/java/home and save the file.

 

6. Start the tomcat with the command: sh /usr/loca/tomcat/bin/startup.sh

 

7. Open the Mozilla Firefox browser and browse to http://localhost:8080 and should see the Tomcat welcome screen.

 

8. To stop the tomcat type: sh /usr/loca/tomcat/bin/shutdown.sh

 

Install MySQL

1. Launch YaST. At the filters field type mysql and select the mysql package to install.

 

2. You may prompt to insert the openSuse-DVD 11. Insert the DVD and click retry to continue.

 

3. The installation process will take place.

 

 

 

Posted in Java, JSP, MySQL, OpenSUSE, Tomcat | Leave a Comment »

Setup Java, Tomcat, MySQL, on Ubuntu Linux Machine for JSP hosting

Posted by leejeok on August 14, 2008

** If you had downloaded and installed Ubuntu 8.04 LTS Desktop Edition, you can skip the step below and goto step 8.

 

Install Ubuntu Ubuntu 8.04 LTS Server

 

  1. Download the Ubuntu Server from http://www.ubuntu.com/
  2. Burn the ISO file into CD and boot your machine from CD.
  3. Follow the installation step closely and it is easy to do it.
  4. Once install successfully, you will require to login.
  5. After login, perform the necessary updates. Make sure you have the internet connections ready. Type sudo apt-get update to do the update.

 

Install the GNOME desktop (mostly used within this tutorial)

 

  1. Type sudo apt-get  install ubuntu-desktop to download and install.
  2. Type startx to start the GNOME


** You can install KDE desktop instead of GNOME.

To install KDE, type the command sudo apt-get install kubuntu-desktop

 

Install JDK 6 and JRE (Java)

 

  1. Within the GNOME, open the terminal. Applications à Accessories à Terminal
  2. Type sudo apt-get install sun-java6-jdk
  3. After successful install, you can do some verification to find out the installed JDK and JRE version. At the terminal, type javac –version for JDK and java –version for JRE.

 

Install Apache Tomcat 5.5

 

**Before installing the Tomcat 5.5, you will need to ensure that you had installed JDK and JRE.

 

  1. Download the tomcat 5.5 from http://tomcat.apache.org/ and saved it to desktop. Here, apache-tomcat-5.5.26.tar.gz been used.
  2. Right click apache-tomcat-5.5.26.tar.gz and click on Extract Here
  3. After extract, rename the folder to tomcat for easier to remember the folder name.
  4. Is good idea to move the tomcat to /usr/local directory. Type the command sudo mv “tomcat on desktop” to “/usr/local”

 

You need to tell the tomcat where the JDK has been installed and to do this you need to define the JAVA_HOME environment variable in .bashrc file.

 

  1. You are about to edit the .bashrc file. Please backup the file first before make any changes. The .bashrc is a hidden file and is located in your home directory.
  2. Open the terminal and type the command gedit ~/.bashrc (GNOME) or kate ~/.bashrc (KDE)
  3. At the end of the file type export JAVA_HOME=/usr/lib/jvm/java-6-sun-1.6.0.06 and save the file.

 

Start and Stop tomcat

 

  1. At terminal, type sh /usr/local/tomcat/bin/startup.sh
  2. You can verify the success installation by open the Mozilla Firefox browser and browse to http://localhost:8080
  3. To shutdown tomcat – at terminal type sh /usr/local/tomcat/bin/shutdown.sh

 

Install the MySQL Server 5.0

 

  1. At terminal, type sudo apt-get install mysql-server

 

Install MySQL Query Browser.

 

  1. At terminal, type sudo apt-get install mysql-query-browser

 

Install MySQL Administrator

 

  1. Open the terminal and type sudo apt-get install mysql-admin

Here are the screen capture

 

Posted in Java, JSP, MySQL, Tomcat, Ubuntu | 4 Comments »

Firefox 3 Launched

Posted by leejeok on June 18, 2008

The new version of Firefox 3 has been released at June 17, 2008.

Firefox is about to set the world record by breaking through the most downloadable software within 24 hours. Click here…

The moment I download the software, it’s already hitting 3,331,796 of worldwide downloads.

Click on the banner below to donwload Firefox 3.

Download Day

Posted in software | Leave a Comment »

Simple JNDI Accessing MySQL Datasource

Posted by leejeok on May 27, 2008

Base on the previous post, I have used the struts-config.xml to define the datasource to access to the MySQL database. The datasource class is code within the Action class (controller layer) and map to the struts-config.xml.

 

In order to improve the programming pratice, the datasource can be created via JNDI and the java code should be sit within the model layer. As a result, business logic will separate from the controller layer and making the Action class without knowing any relation with business class at all.

 

I am using Apache Tomcat 5.x and so, I will define the datasource resource via JNDI within the context.xml.

 

<Context path=”/bookstore”>

<ResourceLink global=”jdbc/bookstoreDB” name=”jdbc/bookstoreDB” type=”javax.sql.DataSource”/>

</Context>

 

The java code to make the database connection accessing the JNDI would be look like this:

 

    Connection cn(){

        DataSource ds = null;

       

        try {

            Context ctx = new InitialContext();

            if ( ctx == null ) {

                throw new RuntimeException(“JNDI Context could not be found.”);

            }

            ds = (DataSource)ctx.lookup(“java:comp/env/jdbc/bookstorDB”);

           

            if ( ds == null ) {

                throw new RuntimeException(“DataSource could not be found.”);

            }

            return ds.getConnection();

            // Handle any JNDI errors

        } catch (NamingException ne) {

            throw new RuntimeException(“A JNDI error occured. ” + ne.getMessage());

           

        }catch(Exception e){

            System.err.println(“Boom – No Context”);

        }

        return null;

}

 

Alternative, you can use JSP Standard Tag Library (JSTL) without embedding any Java code. I am using JSTL SQL tag here and may look like this:

 

<%@ taglib prefix=”sql” uri=”http://java.sun.com/jsp/jstl/sql&#8221; %>

<%@ taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core&#8221; %>

 

<sql:setDataSource dataSource=”jdbc/bookstoreDB” />

 

<sql:query var=”qryBooks” >

    SELECT bookID, bookTitle, bookAuthor, bookPublisher FROM book

</sql:query>

 

<table>

    <c:forEach var=”row” items=”${qryBooks.rows}”>

        <tr>

            <td>${row.bookID}</td>

            <td>${row.bookTitle}</td>

            <td>${row.bookAuthor}</td>

            <td>${row.bookPublisher}</td>

        </tr>

    </c:forEach>

</table>

Posted in JDBC, JSTL, MySQL, Struts | 1 Comment »

Struts – Database Access with struts-config.xml

Posted by leejeok on May 26, 2008

A sample program which connecting to the MySQL database to display the data. I am using the Struts framework to developed this program. The main idea is of this post is to use the struts-config.xml to define the datasource and using Action class to access and select the data.

Please bear in mind, the Action class which represent as controller layer, should not contain any business logic code and database access code. The best pratice is to apply the DAO mechanism by putting your business logic or database access code within the model layer.

The datasource should only define within the struts-config.xml when there is a limitation of connectivity to the database within the model layer. Alternative, you can use the JNDI to define the datasource and that would be the best recommendation in best pratice. However, that will be my next post on my blog.

 

Sample of the datasource used within the struts-config.xml:

    <data-sources>
        <data-source type=”org.apache.commons.dbcp.BasicDataSource” key=”dbSource”>
            <set-property property=”driverClassName” value=”com.mysql.jdbc.Driver” />
            <set-property property=”url” value=”jdbc:mysql://localhost:3306/bookstore” />
            <set-property property=”username” value=”someuser” />
            <set-property property=”password” value=”somepassword” />
        </data-source>
    </data-sources>

 

Here are the summary of development been used.

  • Struts 1.2.9 framework
  • index.jsp, selectBook.jsp, SelectBookActionForm.java – view layer
  • SelectBookAction.java – controller layer
  • Book.java – data layer
  • Defining datasouce at struts-config.xml
  • MySQL database

Source Code: Click Here

Posted in Struts | 5 Comments »

Struts: Build HTML Options Tag Elements from MySQL data

Posted by leejeok on May 25, 2008

Some sample program developed using STRUTS framework to access the MySQL database and retrieve data to build the html options elements. This post is consider as an enhancement from the previous post Struts: HTML Options Tag Sample Code.

 

The previous post was hardcoded to build the html options tag. Meanwhile, this post will build the html options’ elements by retrieving data from MySQL database.

 

I have used the struts-config.xml to define the datasouce to access to the MySQL database. Some simple explanation will be define within this blog here.

 

1. Defining the datasource within the struts-config.xml.

 

    <data-sources>

        <data-source type=”org.apache.commons.dbcp.BasicDataSource” key=”dbSource”>

            <set-property property=”driverClassName” value=”com.mysql.jdbc.Driver” />

            <set-property property=”url” value=”jdbc:mysql://localhost:3306/itemdb” />

            <set-property property=”username” value=”someuser” />

            <set-property property=”password” value=”somepassword ” />

        </data-source>

</data-sources>

 

2. Code the ActionForm and Action class.

 

Within this tutorial, the ActionForm and Action class will not do any much of process. In real world programming, you may want to use both class for building you validation process here.

 

I have use the Action class to create the datasource and map to the struts-config.xml.

 

    public ActionForward execute(ActionMapping mapping, ActionForm  form,

            HttpServletRequest request, HttpServletResponse response)

            throws Exception {

       

        /** Here ‘dbSource’ maps to the datasource key defined in struts-config.xml: */

        DataSource dataSource = (DataSource)servlet.getServletContext().getAttribute(“dbSource”);

       

        ArrayList menuList = new ArrayList();

        MenuData menuData = new MenuData();

       

        //pass the dataSource to menuList within MenuData class.

        //assign elements to menuList.

        menuList = menuData.menuList(dataSource);

 

        //set the attribute to be use for the menu.jsp

        HttpSession session = request.getSession();

        session.setAttribute( “menuList”, menuList);

       

        return mapping.findForward(SUCCESS);

       

    }

 

3. Code the database access and business logic.

 

The created datasource will be pass to the MenuData class to be override by menuList. The business logic and database access will be developed within the MenuData class.

 

public ArrayList menuList(DataSource dataSource) {

       

        Connection conn = null;

        Statement  stmt = null;

        PreparedStatement prpStmt = null;

        ResultSet rs = null;

       

        ArrayList menuList = new ArrayList();

        Menu menu = null;

       

        try{

           

            conn = dataSource.getConnection();

            String sqlQuery = “SELECT itemid, itemname FROM itemtable”;

            prpStmt = conn.prepareStatement(sqlQuery);

            rs = prpStmt.executeQuery();

           

            while (rs.next()) {

                menu = new Menu(rs.getString(1), rs.getString(2));

                menuList.add(menu);

            }

           

            rs.close();

            prpStmt.close();

            conn.close();

           

        } catch ( SQLException e ) {

            System.err.println(“SQL Exception occured while accessing the table.” );

            e.printStackTrace();

            return null;

           

        } finally {

            try {

                conn.close();

            } catch (SQLException e) {

                System.err.println(“Unable to close connection.” );

                e.printStackTrace();

            }

        }

       

        return menuList;

       

    }

 

4. Remark

  • I am using the NetBeans IDE tool to developed the code and MySQL as the database.
  • Create the database, table and insert some data. I had included the database and please use the MySQLAdministrator to restore the data.
  • Within the struts-config.xml, you may want to change the value of username and password. Remember within the struts-config.xml, the element type of <data-sources> must define earlier <form-beans>.

Overall, there is 6 pieces code have been used for this Struts tutorial.

 

View Layer

  • index.jsp
  • begin.jsp
  • ManuForm.java

 

Controller Layer

  • MenuAction.java

 

Data Layer

  • MenuData.java
  • Menu.java

Download Sample Code and Database: Click Here

Posted in Struts | 1 Comment »

Java MySQL – Mass Update Using Batch Updating

Posted by leejeok on May 21, 2008

//Some sample of the code to perform the mass update of database.

 

//The ideas behind of this code is to

//improve the database performance

//by reduce the cost of query executions.

//This is refer to the INSERT, UPDATE and DELETE

//of any rows within the database.

//

//Some developer may execute the query statement within

//the WHILE or FOR loop condition.

//

//With batch updating, a set of SQL query can be writen and execute together

//to improve the performance.

 

 

import java.sql.*;

 

public class Main {

   

    public static void main(String[] args) {

        Connection conn = null;

        PreparedStatement stat = null;

       

        int result = 0;

        int totalRowUpdate = 0;

        boolean updateAll = false;

        boolean updateEmpty = false;

        boolean updateFail = false;

       

        try {

            // Load the JDBC driver

            String driver = “org.gjt.mm.mysql.Driver”;

            Class.forName(driver);

           

            // Create a connection to the database

            String serverName = “localhost”;

            String database = “navigation”;

            String url = “jdbc:mysql://” + serverName +  “/” + database;

            String username = “someroot”;

            String password = “somepassword”;

           

            conn = DriverManager.getConnection(url, username, password);

           

            //Disabled the auto commit. By default, it is always true.

            conn.setAutoCommit(false);

            

            //Create the prepared statement

            String updateSQL = “UPDATE customer SET country = ? WHERE id = ?”;

            stat = conn.prepareStatement(updateSQL);

           

            //Insert the country and hardcoded id.

            for(int i = 0; i <= 5; i++){

                stat.setString(1, “Malaysia”);

                stat.setInt(2, i);

                stat.addBatch();

            }

           

            //Execute the batch.

            int [] updateCounts = stat.executeBatch();

           

            //Validate update.

            //If the row value in the updateCounts array is 0 or greater,

            //the update was successfully executed.

            //A value of SUCCESS_NO_INFO means update was successfully executed

            //but MySQL server unable to determind the number of rows affected.

            //A value of EXECUTE_FAILED means MySQL server rejected the query for error.

            for (int i=1; i<updateCounts.length; i++) {

                if (updateCounts[i] >= 1) {

                    totalRowUpdate = totalRowUpdate + 1;

                    updateAll = true;

                } else if (updateCounts[i] == Statement.SUCCESS_NO_INFO) {

                    updateEmpty = true;

                } else if (updateCounts[i] == Statement.EXECUTE_FAILED) {

                    updateFail = true;

                }

            }

           

            //Error found. Rollback.

            //No error, Commit the batch

            if(updateEmpty || updateFail){

                conn.rollback();

            } else if (updateAll){

                conn.commit();

                System.out.println(“Total Row Update: “+totalRowUpdate);

            }

           

            //Once the batch is executed, it is a good pratice to clear the batch

            //before adding any new query.

            stat.clearBatch();

           

            // Throw BatchUpdateException for any queries fail.

            // Throw ClassNotFoundException for database driver error.

            // Throw SQLException for database error.

        } catch (BatchUpdateException  e) {

            System.err.println(e);

        } catch (ClassNotFoundException e) {

            System.err.println(e);

        } catch (SQLException e) {

            System.err.println(e);

        }

    }

}

Posted in Java, JDBC, MySQL | 1 Comment »

Struts: HTML Options Tag Sample Code

Posted by leejeok on May 14, 2008

I have been doing some research on the internet recently and notice not much of the sample code been provided to build the drop down menu using struts html options tag.

Here are the sample program which I develop using Struts framework by applying the html options tag. The screenshot will look similar as below.

 

Here are the list of pieces code been used.

index.jsp

<%@ taglib uri=”http://struts.apache.org/tags-html&#8221; prefix=”html” %>

 

<html>

    <head>

        <title>HTML Options Tag</title>

    </head>

    <body>

        <h1>Struts: Using HTML Options Tag Example</h1>

        <html:link action=”login”>Begin</html:link>

    </body>

</html>

 

 

menu.jsp

 

<%@ taglib uri=”http://jakarta.apache.org/struts/tags-html&#8221; prefix=”html” %>

 

<html>

    <head>

        <title>HTML Options Tag</title>

    </head>

    <body>

        <h1>Struts: Using HTML Options Tag Example</h1>

        Please select the menu.

        <html:form action=”login”>

            <html:select property=”menu” >

                <html:option value=””>–SELECT–</html:option>

                <html:options collection=”menuList” property=”value” labelProperty=”label” />

            </html:select> 

        </html:form>

    </body>

</html>

 

 

MenuForm.java

 

package com.selection.struts;

 

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;

import org.apache.struts.action.ActionMapping;

import org.apache.struts.action.ActionMessage;

 

public class MenuForm extends org.apache.struts.action.ActionForm {

   

    public String menu;

   

    public String getMenu() {

        return menu;

    }

   

    public void setMenu(String menu) {

        this.menu = menu;

    }

   

  

    public MenuForm() {

        super();

        // TODO Auto-generated constructor stub

    }

   

}

 

MenuAction.java

 

package com.selection.struts;

 

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import org.apache.struts.action.Action;

import org.apache.struts.action.ActionForm;

import org.apache.struts.action.ActionMapping;

import org.apache.struts.action.ActionForward;

 

import javax.servlet.http.HttpSession;

import java.util.ArrayList;

 

public class MenuAction extends Action {

   

    private final static String SUCCESS = “success”;

   

    public ActionForward execute(ActionMapping mapping, ActionForm  form,

            HttpServletRequest request, HttpServletResponse response)

            throws Exception {

       

        ArrayList menuList = new ArrayList();

        MenuData menuData = new MenuData();

        menuList = menuData.menuList();

       

        HttpSession session = request.getSession();

        session.setAttribute( “menuList”, menuList);

       

        return mapping.findForward(SUCCESS);

       

    }

}

 

In real world programming, some developer would prefer to display the options to be retrieved from the database. Here, I will hardcode the options and you may want to change the code to suit yourself.

 

 

 

MenuData.java

 

package com.selection.struts;

 

import java.util.ArrayList;

 

public class MenuData {

   

    public MenuData() {

    }

   

    public ArrayList menuList() {

                

        ArrayList menuList = new ArrayList();

       

        Menu menu = null;

        menu = new Menu(“1”, “First Option”);

        menuList.add(menu);

        menu = new Menu(“2”, “Second Option”);

        menuList.add(menu);

        menu = new Menu(“3”, “Third Option”);

        menuList.add(menu);

        menu = new Menu(“4”, “Forth Option”);

        menuList.add(menu);

       

        return menuList;

       

    }

   

}

 

Menu.java

 

package com.selection.struts;

 

public class Menu {

   

    /** Creates a new instance of Menu */

    public Menu() {

    }

   

    String value;

    String label;

   

    public Menu(String value, String label){

        this.value = value;

        this.label = label;

    }

   

   

    public String getValue() {

        return value;

    }

   

    public void setLabel(String label) {

        this.label = label;

    }

   

    public String getLabel() {

        return label;

    }

}

 

 

Each code contains some comments inside. Hope it helps. I have been using NetBeans 5.5 to build this sample. You can get the full code here or deploy the war to your web services.

Click Here

 

Posted in Struts | 8 Comments »

Struts for navigation between JSP pages

Posted by leejeok on May 8, 2008

I will use the ActionClass to navigate the client to the proper JSP pages. The ActionClass will decide which JSP page to be display on the browser.

By having the configurations file, I will specified the pages within here.

 

<action

          path= “/somerequest”

          type=”com.somepackage.someAction”

          scope=”request”

          name=”someForm”

          validate=”true”

          input=”somePage.jsp”>

          <forward name=”Success” path=”/successPage.jsp” redirect=”true”/>

             <forward name=”Failure” path=”/errorPage.jsp” redirect=”true”/>

</action>

 If you are building a login page and would like to redirect client to the menu page after success login, perhaps your configuration file would look similar like this:

<action

input=”/login.jsp”

name=”loginForm”

path=”/myapplication”

scope=”request”

type=”com.myapplication.struts.loginAction”>

      <forward name=”success” path=”/mainmenu.jsp”/>       

</action>

Here, I included with the program which require client to enter some input before allow to proceed to the next page. Click HERE

Posted in Struts | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.