Understanding Grails Framework at The 1st Sight

Hi readers, it’s been a long time we haven’t met yet. I’ve been drop to the jail of daily routine that make me hard to find a time to write something here. I wrote some notes on my primary blog, and I can’t find a good idea to write something here. But it will change, I have something to share it here now..:p

I have impressed by Grails Framework, for the past 4 weeks, I’ve spent my time to go deeper to understand this framework. I don’t understand Grails Framework definition and description, but you can open their home page if you find your self in curious about it. What I want to share about Grails Framework here is, my notes when I tried to use this framework. It’s more like a steps for understanding Grails Framework manually. Okay, I’m gonna cut these craps and go straight to the point of this notes.

Okay, before the notes begin, I assumed you have installed the grails framework on your system and set the grails home installed directory to your system environment variables, here we go:

1. Create grails application.

Open the command prompt and execute below command:

E:\Data\MyProject\Grails>grails create-app grails-test
| Created Grails Application at E:\Data\MyProject\Grails\grails-test

This command will create a directory named grails-test containing the grails project skeleton

2. Create the controller

After entering the generated directory, lets create a controller called HomeController by executing this command :

    E:\Data\MyProject\Grails\grails-test>grails create-controller com.mygrails.coba.Home
    | Created file grails-app/controllers/com/mygrails/coba/HomeController.groovy
    | Created file grails-app/views/home
    | Created file test/unit/com/mygrails/coba/HomeControllerTests.groovy

Okay, I also put the prefix com.mygrails.coba before the words Home as a package of the HomeController will be placed. You can see above, when the command executed successfully, the command create a Home Controller file and stored the file at grails-app/controllers/com/mygrails/coba/ folder. by default HomeController file will contained at least with one method. This command also create a folder under the grails-app/views/ named as home too, this is the folder where we will store the viewer layer (gsp’s files) later. When we open the HomeController file, we can see the default method created like this screenshot:

package com.mygrails.coba

class HomeController {

   def index() { }
}

In using of Grails Framework software development. I’m a unit-test ignored person, so let’s ignore the created unit-test file..:P

4. Create the viewer layer.

And then let’s create viewer layer which is gsp file, as mentioned above, this file should be located at grails-app/views/home folder. So use your best text editor to create the index.gsp file and store it to the folder. I use notepad to create the file by executing this command:

E:\Data\MyProject\Grails\grails-test>start notepad grails-app\views\home\index.gsp

I write the content of the index.gsp file using common html tag like this:

<html>
   <head>
       <title></title>
   </head>
   <body>
       Howdy...??
    <p>
     Welcome to Grails Framework
    </p>
   </body>
</html>

5. Run the application.

After the file saved let’s run the application by executing this command:

    E:\Data\MyProject\Grails\grails-test>grails run-app
    | Running Grails application
    Sep 10, 2013 10:19:00 PM org.apache.coyote.AbstractProtocol init
    INFO: Initializing ProtocolHandler ["http-bio-8080"]
    Sep 10, 2013 10:19:01 PM org.apache.catalina.core.StandardService startInternal
    INFO: Starting service Tomcat
    Sep 10, 2013 10:19:01 PM org.apache.catalina.core.StandardEngine startInternal
    INFO: Starting Servlet Engine: Apache Tomcat/7.0.39
    Sep 10, 2013 10:19:01 PM org.apache.catalina.startup.ContextConfig getDefaultWebXmlFragment
    INFO: No global web.xml found
    Sep 10, 2013 10:19:01 PM org.apache.catalina.core.ApplicationContext log
    | Server running. Browse to http://localhost:8080/grails-test

6. Open the application.

Use your favorite browser to open the application by entering this http://localhost:8080/grails-test/home/index to the address bar of the browser. You should see the result like this:

OpenApp5. Proof Grails Framework run time changed code.

Next task is modifying the content of gsp file by adding more words or html tag, remember we do this without stopping the running Grails Application. After we did the task and saved the changed gsp file, try to refresh the browser by pressing F5. When the content of opened page in the browser changed, I can consider we understood that the grails framework doesn’t need to stop and start the running application while we changed the content.

6. Passing data from controller.

Now we ready to move to the next task which is passing the data from controller layer to viewer layer in order to make us understand how these two layers can communicate each others. Open your HomeController.groovy file using your favorite text editor, and insert the code inside the index method, just like below example:

def index() {
  def name = params.name
  [nameToPass:name]
}

and then edit the index.gsp file to display the data from controller just like below:

<body>
    Welcome...<b>${nameToPass}</b><br>
    This application powered by Grails Framework
</body>

After all the files saved, try to refresh the browser and add the url parameter to the URL address like this http://localhost:8080/grails-test/home/index?name=Stevie, we should see the content changed. And I hope we could understand that url parameter name  sent from browser, and then catch by the controller and then the controller send the parameter value to gsp file to display in the browser.

ChangedCodeThat’s it, that’s my way to understand the Grails Framework at the 1st sight. With Integrated Development Editor such as eclipse or Intellijidea, grails framework will be more easier to understand especially the code syntax.

See ya..

Josescalia

Advertisements

Component Binding On Swing Framework

Dear readers, its been a long time for me not update this blog. Please forgive me, if you find there’s no new article every time you back to this blog. Well, a short story about my activity, now I’m work at an IT Consultant company, and now we are doing a government IT project. This project is using Swing framework for it’s interface. Well, I didn’t have much understanding about swing framework, finally have to meet this framework too.
As a reminder, it will be better to share what I’ve got within my new job. one of which is Component Binding on Swing Framework. Component binding on Swing Framework is an easy way to develop a swing application using Netbeans IDE. And now for this practice, we will try to implement a component binding on Swing Framework. Ok, let’s straight to the point, create a new project using netbeans, and then create 3 package as shown as below:SwingTutorial-1.0

And then, create a class in a model package as code-snippet below:

public class Users {

    private Long id;
    private String sureName;
    private String nickName;
    private Integer age;
    private String sex;
    private String phoneNumber;
    private String address;

    //constructor below
    //getter setter below
    //toString below
}

And then, create a dummy data class based on Users class in a data package like below example:

/**
 *
 * @author Josescalia
 */
public class UsersData {

    Users u1,u2,u3,u4;

    private void init(){
        u1 = new Users();
        u1.setId((long) 1);
        u1.setNickName("Syarif");
        u1.setSureName("Ahmad Syarif");
        u1.setAge(28);
        u1.setAddress("Surabaya");
        u1.setSex("male");
        u1.setPhoneNumber("0815468912");

        u2 = new Users();
        u2.setId((long) 2);
        u2.setNickName("Dian");
        u2.setSureName("Dian Sari Puspita");
        u2.setAge(20);
        u2.setAddress("Semarang");
        u2.setSex("female");
        u2.setPhoneNumber("0813657125");

        u3 = new Users();
        u3.setId((long) 3);
        u3.setNickName("Atika");
        u3.setSureName("Purwatika Lestari");
        u3.setAge(23);
        u3.setAddress("Medan");
        u3.setSex("female");
        u3.setPhoneNumber("0813987909");

        u4 = new Users();
        u4.setId((long) 4);
        u4.setNickName("Dodi");
        u4.setSureName("Dodi Sukma");
        u4.setAge(34);
        u4.setAddress("Palangkaraya");
        u4.setSex("male");
        u4.setPhoneNumber("08179809759");
    }

    public UsersData() {
        init();
    }

    public List<Users> getUserList(){
        List<Users> result = new ArrayList<Users>();
        result.add(u1);
        result.add(u2);
        result.add(u3);
        result.add(u4);
        return result;
    }
}

And the next step is design a form using JFrame or JPanel in a gui package just like this below picture :SwingTutorial-1.1

Give a name for each component as you like, in this tutorial I gave a tblUsers as a name for JTable component. And the type a few code like this example:

.....
//import a few standard library, auto generate will be execute by netbeans here

public class FormExampleJTable extends javax.swing.JFrame {

    private UsersData data = new UsersData();
    private List<Users> usersList = new ArrayList<Users>();
    /**
     * Creates new form FormExampleJTable
     */
    public FormExampleJTable() {
        initialize();
        initComponents();
    }

    private void initialize() {
        usersList = data.getUserList();
    }

    public List<Users> getUsersList() {
        return usersList;
    }

    public void setUsersList(List<Users> usersList) {
        this.usersList = usersList;
    }

   ....
   //a few code will be generated by netbeans here
}

Notes : the code that I wrote above is only the main code, others are automatically generated by netbeans. Now let’s understand these codes before we move to the next steps.
There’s a few variable declarations, one of which is a data variable which has UsersData object data type, and the usersList variable which has an object List data type.  And then in the constructor of the class, we have a statement which call initialize method, while the initComponent method, is a method which netbeans auto generated method by default. And we can see getter and setter method for a userList variable also. In this initialize method is a core of our practice for this tutorial, please pay attention at a initialize block method, we call data.getUserList and then we patch the result to userList variable:

private void initialize() {
   usersList = data.getUserList();
}

By finishing this step, actually we finished the coding part, and the next steps are bind the component which in the form that we already created before. Let’s go to the main purpose this article which is Component Binding.
For the first bind we will do it in a JTable, right click the JTable component and the click properties. In the properties window, choose binding tab, and then click a small button which located horizontally to the element row, when the bind window appear, choose Binding Source to Form, and the Binding Expression to a userList variable, as shown to below picture.
SwingTutorial-1.2
If the userList variable is not show up on the list, it’s because we don’t create a getter and setter method.
After that, we can run the form and you can see the data which we created in a UsersData class contained in JTable. If we want to change the JTable looks, we can do it by right click the JTable component and choose Table Content, and then choose Column tab, at that window we can change the header, field size and other JTable settings.
Now, let’s try to bind a JTextField component, which already created on the form. The steps is exactly same with the JTable binding above, but the binding source is not Form anymore, but the JTable its self, and the Binding Expression  is selectedElement_IGNORE_ADJUSTING.[a property name of user class]. What we should noted here is property name of User class. I mean if we want to bind a JTextField to hold a sureName data from the Users class, then the binding expression must point to the selectedElement_IGNORE_ADJUSTING.sureName . As shown as below picture:

SwingTutorial-1.3Ok now, please bind all the JTextField component which exist on the Form by repeating above steps,  and then run the form. And click one of the row on a JTable, the each JTextField should contains the each data according to the row we have clicked on JTable.
That’s all for the practice now, this link is a project source code of our practice that you are free to use, develop and try by your self.
Have good day, and I hope it useful.

Thanks

Josescalia

Using TestNG on Spring Framework and Hibernate Test Case

Dear readers, at the time I wrote this article, I just have 2 months of being an employee at the IT Consultant Company in Jakarta, Indonesia. But that’s not what I want to share in this article. In this company, I was expected to follow the java development stack which is applied in this company. The Spring Framework and Hibernate are include.

I’ve been 6 years in Java programming language, but I admit, I never involve Hibernate framework as an ORM(Object Relational Mapping) method on my projects development stack. While Spring Framework, I’ve been using it since 2 years ago. This condition force me to do a little adaptation of this Hibernate Framework.

I often met some difficulties which is stress me so much, when the codes of the dao layer using a hibernate criteria. For a few developers who always using hibernate framework, it should be easier to use hibernate criteria, but for me, it really stress me so much.

To find a method on a dao layer work or not, sometimes it wouldn’t so effective to test it by deploying whole application just only to test one method. And I decide to use unit-test when testing dao layer methods, so I don’t need to deploy whole application.

Okay, below is the step to create a unit-test in order to test the methods on dao layer which created using Spring Framework and hibernate:

  1. Create a hibernate configuration file, Spring Context file, and all those supported files, and put them onto test/resources folder just like the picture below:
  2. Create a file called TestDao, and put it onto test/java folder. The codes of the files is below:
package com.mojo.maven.test;

import com.mojo.maven.dao.NewsCategoryDao;
import com.mojo.maven.dao.NewsDao;
import com.mojo.maven.model.News;
import com.mojo.maven.model.NewsCategory;
import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.hibernate.context.ManagedSessionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

@ContextConfiguration(locations={"classpath*:maven1ApplicationContext-test.xml"})
public class TestDao extends AbstractTestNGSpringContextTests{
    private Logger logger = Logger.getLogger(TestDao.class);

    @Autowired
    public SessionFactory sessionFactory;
    private Session session;

    @Autowired
    private NewsDao newsDao;

    @Autowired
    private NewsCategoryDao newsCategoryDao;

    /**
     * Inisialisasi hibernate context sebelum test
     */
    @BeforeMethod
    void init() {
        logger.debug("init session factory");
        session = sessionFactory.openSession();
        ManagedSessionContext.bind(session);
    }

    /**
     * cleanup hibernate context setelah test
     */
    @AfterMethod
    void destroy() {
        logger.debug("destroy session factory");
        session.close();
        ManagedSessionContext.unbind(sessionFactory);
    }

    @Test
    public void testGetNews(){
        News news = newsDao.getById(1);
        logger.info("News ID : " + news.getId());
        logger.info("News Title : " + news.getNewsTitle());
        logger.info("News URL : " + news.getNewsUrl());
        logger.info("News Category : " + news.getNewsCategory().getCategoryName());
        logger.info("News Category Description : " + news.getNewsCategory().getCategoryDescription());
    }
}

What we have to pay attention on the class are, the class have an annotation @ContextConfiguration and extends AbstractTestNGSpringContextTests class which is provide as a base class to use it as a test class for TestNG Framework. Also on the annotation @ContextConfiguration  defined the location of the Spring Context, so the compiler can find a Spring Context file when the execution is triggered.

The next thing which have to note are 2 methods which is defined on the class, those are void init() method and void destroy() method. void init() method, given an annotation @BeforeMethod which have a function as an hibernate context initializations before all other the test method executed. While void destroy() method given an annotation @AfterMethod which have a function to close a hibernate session after all test method executed.

Well, that’s all that I can share for this time. If you feel the codes need more improvement, so go head, to make it perfect.

I’ll hope it usefull.

Josescalia

———————————————-

The quick brown fox jump over the lazy dog

The Quick Brown Fox

One day, I read, that this sentence “the quick brown fox jump over the lazy dog” contains all the character of the alphabet,  just because I’m so curious,  I thought to create a simple java application that checks whether the sentence is actually using all the letters in the alphabet or not.

The pseudo code of the application will look like this:

  1. Declare the string.
  2. Remove all spaces between the words from the sentence.
  3. Remove duplicate character.
  4. Convert the string into Character Arrays.
  5. Sort the Character Arrays.
  6. Loop the Character Array and print out to console.

First, I need to create a function that can remove duplicate character from a given parameter and the return of the function have to be a string. Ok, here’s the code:

    public static String removeDuplicates(String s) {
        StringBuilder noDupes = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            String si = s.substring(i, i + 1);
            if (noDupes.indexOf(si) == -1) {
                noDupes.append(si);
            }
        }
        return noDupes.toString();
    }

The function above using StringBuilder object as a container to process removing duplicate character, and the function will return the string formed by StringBuilder object. And then, I will use this function in the application. Ok, here’s the code:

import java.util.Arrays;

/**
 * Created by IntelliJ IDEA.
 * User: Josescalia
 * Date: 7/8/11
 * Time: 8:24 PM
 * To change this template use File | Settings | File Templates.
 */
public class ArrayTest {
    public static void main(String[] args) {
        //the string declaration
        String sStr = "the quick brown fox jumps over the lazy dog";
        //remove the spaces
        sStr = sStr.replace(" ", "");
        //remove the duplicate character using the function
        sStr = removeDuplicates(sStr);
        //Convert string into Character Array
        char[] a = sStr.toCharArray();
        //Sort the Array
        Arrays.sort(a);
        //let's loop and print out...is is correct, using all the character of the alphabet ????
        for (int i = 0; i < a.length; i++) {
            char c = a[i];
            System.out.print(c);
        }
        //it's true :P
    }

    public static String removeDuplicates(String s) {
        StringBuilder noDupes = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            String si = s.substring(i, i + 1);
            if (noDupes.indexOf(si) == -1) {
                noDupes.append(si);
            }
        }
        return noDupes.toString();
    }
}

Well, that’s all. Feel free to use and explore for your creations and needs.

I Hope that’s usefull

Thanks

Josescalia


An Easy Way to Create JSP’s and MySQL Web Application

Dear readers, this time I would like to share about how to create a JSP’s and MySQL web application. This time we will create it using easy way, means that we wouldn’t create this web application by coding java classes that we might needed to support this application. We only create JSP, yes only JSP, and of course few configuration that I hope easy enough too.
Before we start, let’s prepare a database and a table that will be one of our material of this creation. Let’s create a database and name it as “test_jsp” and for the table, the structure of the table is looked like this sketch.

or we can copy and paste sql query below:

create database test_jsp;
use test_jsp;
CREATE TABLE `identitas` (
  `NO` int(10) NOT NULL AUTO_INCREMENT,
  `NAMA` varchar(100) NOT NULL,
  `ALAMAT` varchar(255) DEFAULT NULL,
  `NO_TELP` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`NO`));

The above Sql Query is a query to create a database named as test_jsp, and creating a table named as identitas with the following field described above on the image. The please fill up the table with few necessary data, in order to make the table containing data like the picture below.

By that, one of our material for this application is created.

To do this development, actually we need or we will use a library, this library has an ability to support the creation of a web application only using jsp. The needed library is Jakarta Taglibs library.

Jakarta Taglibs is one of the open source project of Jakarta Tag Libraries which supporting a creation of a web application using JSP and without coding java classes. With the Taglibs concept means that will use this library supported API by calling it using the JSP’s tags. Since this web application using a database, so we need a library called DBTags (database tags), so please download the library here http://jakarta.apache.org/site/downloads/downloads_taglibs.html, and we will need other library which have a function as a MySQL database driver which is called as mysql-connector-java.jar, please also download this library here http://dev.mysql.com/downloads/connector/j/

After finished downloading those libraries, then please extract the both files. And the next step is preparing a web application on an Application Server or Servlet Container, for this exercise we using Tomcat as a Servlet Container.

  1. Create a folder on a WebApps folder on tomcat installation directory. Let’s give a name “MySimpleJSP”. This folder will be a folder path on our web application.
  2. Inside the folder is MySimpleJSP again, we make two more folders named WEB-INF and libs.
  3. Copy mysql-connector-java.5.1.6.jar file (I use the connector 5.1.6 here) from the mysql connector library, and taglibs-dbtags.jar files from libraries Jakarta Tablibs which we downloaded earlier into the libs folder.
  4. And also copy the taglibs-dbtags.tld file from Jakarta Taglibs library that we have extracted onto WEB-INF folder.
  5. Create a file called web.xml and then save the file also in the WEB-INF folder, while the contents of the web.xml file write the following directions:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
          http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
           version="2.5">

      <jsp-config>
           <taglib>
               <taglib-uri>http://jakarta.apache.org/taglibs/dbtags</taglib-uri>
               <taglib-location>/WEB-INF/taglibs-dbtags.tld</taglib-location>
           </taglib>
       </jsp-config>
</web-app>

Until here, we have completed preparations for web-applications for our experiment this time. And the next step is to simply make jsp files that we need to be able to access the MySQL database we have made earlier, all jsp files which later we will create will be placed in MySimpleJSP folder or parallel with WEB-INF folder and the libs folder. Let’s create a jsp file.

The first JSP file we will create is get_identity.jsp, this file is a jsp file in charge of taking the data in the tables located on the identitas table on test_jsp database. Let’s look at the codes below get_identity.jsp file:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://jakarta.apache.org/taglibs/dbtags" prefix="sql" %>
<html>
<head><title>My Simple JSP MYSQL Page</title></head>
<body>
<%-- Step 1) create a database connection --%>
<sql:connection id="connect">
    <sql:url>jdbc:mysql://localhost/test_jsp</sql:url>
    <sql:driver>com.mysql.jdbc.Driver</sql:driver>
    <sql:userId>root</sql:userId>
    <sql:password>admin99</sql:password>
</sql:connection>
<%--End Creating database Connection--%>

<%-- Step 2) Create a SQL query --%>
<sql:statement id="statement" conn="connect">
    <sql:query>
        SELECT * FROM identitas
    </sql:query>

    <table border="1">
        <tr>
            <th>NO</th>
            <th>NAMA</th>
            <th>ALAMAT</th>
            <th>NO TELP</th>
        </tr>
            <%--Step 2.1) Loop the result--%>
        <sql:resultSet id="data">
            <tr>
                <td><sql:getColumn position="1"/> </td>
                <td><sql:getColumn position="2"/> </td>
                <td><sql:getColumn position="3"/> </td>
                <td><sql:getColumn position="4"/> </td>
            </tr>
        </sql:resultSet>
    </table>
</sql:statement>

<%--Step 3) Close Database Connection--%>
<sql:closeConnection conn="connect"/>
</body>
</html>

Let’s make an attention the JSP’s code above:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://jakarta.apache.org/taglibs/dbtags" prefix="sql" %>

On the second line we make a declaration tag that we shall use in this jsp file. Uri must be in line with taglib-uri which we declared in the web.xml file before. And if this web application run, the web.xml file have a responsibilities to find tags reference with sql prefix on taglibs-dbtags.tld file.

<%-- Step 1) create a database connection --%>
<sql:connection id="connect">
    <sql:url>jdbc:mysql://localhost/test_jsp</sql:url>
    <sql:driver>com.mysql.jdbc.Driver</sql:driver>
    <sql:userId>root</sql:userId>
    <sql:password>admin99</sql:password>
</sql:connection>
<%--End Creating database Connection--%>

While the above code block, we make declarations tags to connect to the mysql database that we created earlier.Please make attention each line above, the database is test_jsp then the driver is com.mysql.jdbc.Driver, and userid to connect to the mysql database is the root, and password to connect to the mysql database is admin99. My mysql database username is root and password is admin99, please adjust your database with the settings of each. Please make more attention in the code above, all of this configuration should be in block sql: connection

<%-- Step 2) Create a SQL query --%>
<sql:statement id="statement" conn="connect">
    <sql:query>
        SELECT * FROM identitas
    </sql:query>

    <table border="1">
        <tr>
            <th>NO</th>
            <th>NAMA</th>
            <th>ALAMAT</th>
            <th>NO TELP</th>
        </tr>
            <%--Step 2.1) Loop the result--%>
        <sql:resultSet id="data">
            <tr>
                <td><sql:getColumn position="1"/> </td>
                <td><sql:getColumn position="2"/> </td>
                <td><sql:getColumn position="3"/> </td>
                <td><sql:getColumn position="4"/> </td>
            </tr>
        </sql:resultSet>
    </table>
</sql:statement>

Then look at the rows of the following code, we create a block of tag sql:statement. Where in this block we write the block tag sql:query and tag sql:ResultSet, and in the block sql:ResultSet, we extract the data from the database to be displayed to the web page using tag sql:getColumn. If we try to understand the tags, the description may look like this: tag sql:query is a tag to write sql query which will be executed by the application. Then tag sql:ResultSet is a tag where the captured data from the database placed in the form to an array collection. And the last is the tag sql:getColumn is a way to extract the collection array and then sorted based on the basic view of our application web pages.

<%--Step 3) Close Database Connection--%>
<sql:closeConnection conn="connect"/>

And finally the last in this code is, that we then terminate the connection to our MySQL database.

Then after that, we can test this MySimpleJSP application by running our Tomcat and then call the get_identity.jsp files on your favorite browser pointed to the address: http://localhost:8000/MySimpleJSP/get_identity.jsp (I have configured tomcat to port 8000, please replace with the appropriate port in your tomcat configuration). If successful, it should display the web page is like this

With the appearance of the data into a web page of our JSP application, then we can describe that this exercise is successful done. For further step you can create more jsp pages, such as a jsp file to insert the data into the table, etc.

I Hope this usefull.

Thanks

Josescalia

Error Page Customizing on Java Web Application

Have we ever seen this web page:

tomcat 404

Or this one:

This web page is standard error page produced by Apache Tomcat when our web application have some errors. These error occurred because the logic of our application had a mistake or user do some mistaken when requesting via HTTP browser.

We can change these pages into our custom page but have same function just like the page above. The advantages is we can redesign the page just like we  desired to. And other function is we could hide some error points, so the user can’t find out what’s the problem behind.

Before that, we can divide type of error that probably occurred on our web application. 1st, caused by user fault such as accesing file that’s not exist on the server, and the 2nd caused by error logic on our web application.

Let’s try to customize the error page that could be happen like above.

1. Creating error page caused by user:

When creating this type of error page, we can create it by adding some lines on deployment descriptor (web.xml) like this:

    <error-page>
        <error-code>404</error-code>
        <location>/404.jsp</location>
    </error-page>

On the source above, we can see clearly, if File Not Found Error occurred when user requesting via HTTP browser and the web application will automatically redirect to a 404.jsp file, and of course we have created this file before and customed like this one:

2.  Creating Error Page caused by Programming mistakes:

While configuring the error page caused by our programming mistakes, we can do it by adding these lines on deployment descriptor:

    <error-page>
        <exception-type>java.lang.NullPointerException</exception-type>
        <location>/errorpage.jsp</location>
    </error-page>

    <error-page>
        <exception-type>java.lang.NumberFormatException</exception-type>
        <location>/errorpage.jsp</location>
    </error-page>

On the example source, we can see that the error can be define one by one, such as Null Pointer Exception Error, nor Number Format Exception Error.

On the sampe source too, we can only create one jsp page to accommodate and informing the stacktrace that occurred caused by our programming mistakesl.

The source code of this jsp file is:

<%@ page import="java.io.ByteArrayOutputStream" %>
<%@ page import="java.io.PrintStream" %>
<%--
  User: Muhammad Yusuf
  Date: Aug 30, 2005
  Time: 5:56:29 PM
--%>
<%@ page isErrorPage="true" %>
<html>
<head>
    <title>JSP Error Page</title>
    <meta http-equiv="Pragma" content="no-cache">
    <style type="text/css">
        body {
            background-color: #cccccc;
            font-family: verdana, sans-serif, monospace;
            font-size: medium;
        }
    </style>
</head>

<body bgcolor=#ffffff>
<font face="Verdana">
    <center>
        <h2><font color=#DB1260>Error Page</font></h2>
    </center>
    <p> An exception was thrown: <b> <%=exception %>
        <p> With the following stack trace:
<pre>

<%
    ByteArrayOutputStream ostr = new ByteArrayOutputStream();
    exception.printStackTrace(new PrintStream(ostr));
    out.print(ostr);
%>
</pre>
        <br><a class="Verdana" href="#">Back To Main</a>

        <p>
</body>
</html>

On this source code, the occurred exception can be defined by using this tag <%=exception%> and the stack-trace that probably occurred can be print-out to the page like this:

<%
    ByteArrayOutputStream ostr = new ByteArrayOutputStream();
    exception.printStackTrace(new PrintStream(ostr));
    out.print(ostr);
%>

And here’s the final result of the 2nd error page caused by our programming mistaken.

Or like this:

Hope this will helpfull

Menteng, 29 November 2009.

josescalia

Creating Java Download Application

On internet activity, we often do download or upload. Download is an internet activity which takes a file from remote computer to our local computer.

Basically, when we download a file from a remote computer or a server, actually our computer reading byte by byte of a file that we want to download. And after all the byte read then the computer will pack it onto a file that contains perfectly same with the file that we like to download.

With this concept, let’s try to make a little experiment and this experiments will implement all the steps above, we can complete this experiment with another steps that we can gather base on our knowledge that we can find out from the above download process concept.

Let’s try to arrange the steps:

  1. URL identification.

To download a file, we need a valid URL address for sure, and the path location of a file that we want to download. Example: http://www.wayofmuslim.com/ebook-islam/AlQuranDigital.zip. this have a meaning that we want to download a file named AlQuranDigital.zip from a remote computer wayofmuslim.com and the path location of this file at ebook-islam/

  1. The size of file.

Each file that we want to download, have to find out the size of it. The purpose of this are we will be able to compare the bytes length that already read and stored in our local computer with the file that exist on remote computer, so we can find out whether the byte we have downloaded is corrupted or not before we can pack it up onto a file.

  1. The content type of file.

This is optional, we can use this concept or not, it’s an option. But knowing the content type of a file in internet technology is the basic knowledge.

With those concept actually we can create our own application that have ability to download a file from a remote computer, yes we can, because the download concept is that simple.

Now let’s proof it by arrange a scenario based on the concept above to create our own Java Download Application. The scenario is:

  1. Identifying URL.

Checking whether the supplied URL valid or not, we will use URL class that exist on Java.

  1. Valid URL.

If the URL is valid, then go straight to create a HTTP Connection to check whether our computer is connected to the internet or not. And if the URL is not valid then just exit the application and show some screens out telling that the connection is not available.

  1. Identifying the Content Type

If the Http Connection status is good, meaning that the host or remote computer can be contacted, the next step is identifying the content type of a file that we would like to download. In this try-it-out let’s just limit it, if the content type of a file is text/html, then we don’t have to download it. Why? The Http Status 404 (File Not Found) can be occurred on a file that we want to download, and we don’t need this html page to download to our computer rite?

  1. Identifying the byte length (Content Length).

Just because we will to read byte by byte of file that we want to download, so it’s very important to store information of a byte length of the file that we want to download into a variable. And for the next usage this information can be some useful things in order to compare the byte length of downloaded byte with the length of byte that exist on remote computer, to find out whether the downloaded file corrupted or not.

  1. Reading byte by byte.

This is the essential things on our try-it-out. Our application should have an ability to read byte by byte of the file that we want to download and the result of the bytes reading will put on a variable which have byte data-type. The way of bytes reading is using the looping from 0 to the content length that we have store it into a variable before.

  1. Comparing local file to a remote file.

The next step is comparing the length of bytes that already read with the length of byte that stored before on a variable. If the both are not same that’s mean the downloaded file is corrupted and this byte will not be packed onto a file.

  1. Pack the read bytes.

After we knew exactly that the length of read bytes is similar to byte length of remote computer, so it’s time to pack it up onto a file. Let’s just make it easier by naming the file exactly same with the name of file that exist on remote computer.

Using the above scenario, let’s try to code just like the source code below:

package org.mojo.download.agent;

import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.net.URL;
import java.net.MalformedURLException;
import java.net.URLConnection;

/**
 * Created by IntelliJ IDEA.
 * User: Mojo
 * Date: May 2, 2009
 * Time: 11:39:49 AM
 * To change this template use File | Settings | File Templates.
 */
public class SingleDownloadAgent {

    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("Usage : java SingleDownloadAgent <URL>" );
            return;
        } else {
            SingleDownloadAgent agent = new SingleDownloadAgent();
            try {
                doDownload(args[0]);
            } catch (IOException e) {
                System.err.println("Exception e");
            }
        }
    }
    public static void doDownload(String sURL) throws IOException {
       URL u = null;
        //try URL
        try {
            u = new URL(sURL);
        } catch (MalformedURLException ex) {
            System.err.println("Malformed URL : " + ex);
            return;
        }
        catch (IOException ex) {
            System.err.println("An Error Occured : " + ex);
            return;
        }
       //reading Connection
        URLConnection uc = null;
        try {
            uc = u.openConnection();
            //identifying connection
            uc.connect();
        } catch (IOException e) {
            System.out.println("Cannot Connect: Please Check Connection");
            return;
        }

        String contentType = uc.getContentType();
        System.out.println("contentType :" + contentType);

        int contentLength = uc.getContentLength();
        if (contentType.startsWith("text/html") || contentLength == -1) {
            throw new IOException("This is html file.");
        }

        //collecting byte in var data
        InputStream raw = uc.getInputStream();
        InputStream in = new BufferedInputStream(raw);
        byte[] data = new byte[contentLength];
        int bytesRead = 0;
        int offset = 0;
        while (offset < contentLength) {
            bytesRead = in.read(data, offset, data.length - offset);
            if (bytesRead == -1) break;
            offset += bytesRead;
        }
        in.close();

        //file corrupted
        if (offset != contentLength) {
            throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes ? File Corrupted…");
        }

        //writing byte data to a file
        String filename = u.getFile();
        filename = filename.substring(filename.lastIndexOf('/') + 1);
        FileOutputStream fout = new FileOutputStream(filename);
        fout.write(data);
        fout.flush();
        fout.close();

    }
}

On the above source-code we have two methods, which is the main method and the doDownload method with sURL string as it’s parameter. Let’s discuss it line by line the above source-code:

As usual, at the beginning of the code we declare the package where this class is located and the declaration of imported class that we will need later. And then on the main method we check whether the URL parameter supplied when this class is called. Indeed, this application designed has to supply the URL parameter when this application called.

package org.mojo.download.agent;

import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.net.URL;
import java.net.MalformedURLException;
import java.net.URLConnection;

/**
 * Created by IntelliJ IDEA.
 * User: Mojo
 * Date: May 2, 2009
 * Time: 11:39:49 AM
 * To change this template use File | Settings | File Templates.
 */
public class SingleDownloadAgent {

    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("Usage : java SingleDownloadAgent <URL>" );
            return;
        } else {
            try {
                doDownload(args[0]);
            } catch (IOException e) {
                System.err.println("Exception e");
            }
        }
    }
………

On this main method, showed that if the URL parameter is not supplied then this application will print out the message of application usage and then directly quit. And if the URL parameter supplied then the application will continuing call the doDownload method with args[0] as it’s parameter.

Now let’s take a look at the second method which is doDownload methods:

   ………
   public static void doDownload(String sURL) throws IOException {
       URL u = null;
        //try URL
        try {
            u = new URL(sURL);
        } catch (MalformedURLException ex) {
            System.err.println("Malformed URL : " + ex);
            return;
        }
        catch (IOException ex) {
            System.err.println("An Error Occured : " + ex);
            return;
        }
    ………

On these lines we run out first scenario which is validating the URL, and we put it on a try-catch block. Why we put it on try-catch block? Because we want to know if the error occurred, where it will be happen.

…………
        //reading Connection
        URLConnection uc = null;
        try {
            uc = u.openConnection();
            //identifying connection
            uc.connect();
        } catch (IOException e) {
            System.out.println("Cannot Connect: Please Check Connection");
            return;
        }

        String contentType = uc.getContentType();
        System.out.println("contentType :" + contentType);

        int contentLength = uc.getContentLength();
        if (contentType.startsWith("text/html") || contentLength == -1) {
            throw new IOException("This is html file.");
        }
…………

And after that, on the lines above code we check the connection to host or remote computer by put it once again on try-catch block, and then the next line we find out the content type of the file that we want to download and put the information on a string variable called contentType. And then we check the content length that we want to download and put in on a integer type variable. And the next lines is continue by the branching to make a decision if the content typeof the file is type/html type, then just quit the application.

    …………
        //collecting byte in var data
        InputStream raw = uc.getInputStream();
        InputStream in = new BufferedInputStream(raw);
        byte[] data = new byte[contentLength];
        int bytesRead = 0;
        int offset = 0;
        while (offset < contentLength) {
            bytesRead = in.read(data, offset, data.length - offset);
            if (bytesRead == -1) break;
            offset += bytesRead;
        }
        in.close();

        //file corrupted
        if (offset != contentLength) {
            throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes ? File Corrupted…");
        }
    …………

On the lines above, we can see the reading of byte by byte do by our application, using the open up the output-stream and then read the output stream by looping byte and using the content length as it limitation, and then put it the read result into a data variable that have byte data-type. And after the read process is finished the output-stream is closed and then we create a statement to compare the length of read bytes that stored on offset variable with the contentLength variable.

…………
        //writing byte data to a file
        String filename = u.getFile();
        filename = filename.substring(filename.lastIndexOf('/') + 1);
        FileOutputStream fout = new FileOutputStream(filename);
        fout.write(data);
        fout.flush();
        fout.close();

    }
…………

And this is the last codes that we have created, on this codes we pack up the bytes that we have read and stored into a data variable before, into a file. To naming the file, we just named as a same filename that we want to download.

That’s it, our try-it-out for this time. There’s still a lot that we can explore more from this little experiments, such as we can build a GUI as its interface, or adding some progress bar animation, etc. Please explore more of this concept to creating more perfect things.

 

 

Hope it will be useful.

Menteng, March 3rd 2009

 

Josescalia.