Posts Tagged ‘enterprise-it’

 

Today we will create a Spring MVC based application that uses Freemarker FTL as view instead of JSP. This would give you a good insight in Spring MVC + Freemarker integration. The application is similar to previous tutorial’s User app, where a list of users will be displayed and also we can add new user.

The application is very simple:

  1. There is a table that displays user info like firstname, lastname.
  2. New user can be added via Add User form.

Below is the wireframe of our final freemarker based spring mvc 3 app.
freemarker-servlet-wireframe

So lets get started.

Things We Need

Before we starts with our Spring MVC 3 + FreeMarker example, we will need few tools.

  1. JDK 1.6 or above (download)
  2. Tomcat 6.x or above or any other container (Glassfish, JBoss, Websphere, Weblogic etc) (download)
  3. Eclipse 3.4.x or above (download)
  4. Spring MVC 3.1.2 or above (download)
  5. Freemarker JAR v2.3.15 or above(download)

Let us start with our Spring MVC based Freemarker application.

Step 1: Getting Started

Open Eclipse and goto File -> New -> Project and select Dynamic Web Project in the New Project wizard screen.

dynamic web project in eclipse

After selecting Dynamic Web Project, press Next.

eclipse dynamic web project

Write the name of the project. For example Freemarker_SpringMVC_example. Once this is done, select the target runtime environment (e.g. Apache Tomcat v6.0). This is to run the project inside Eclipse environment. After this press Finish.

Once the project is created, you can see its structure in Project Explorer. This is how the project structure would look like when we finish the tutorial and add all source code.

springmvc-freemarker-ftl-project-structure

Till this step, our basic Eclipse web project is ready. We will now add Spring MVC and Freemarker support to this project.

Step 2: Adding Spring MVC Support

First copy all required Spring MVC and supporting JAR files in WebContent > WEB-INF > lib folder. Create this folder if it does not exists. Don’t worry if you do not have these JARs. You can download the complete source code with JAR files at the end of this tutorial.

Next we change web.xml (deployment descriptor) and add Spring MVC support to it. If you do not know why we do this, I strongly recommends you to go through Spring 3 MVC Tutorial series.

Related: Spring 3 MVC hello world example

Update the web.xml with following code:

File: /WebContent/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        id="WebApp_ID" version="3.0">
        
  <display-name>Freemarker_SpringMVC_example</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
</web-app>

The above code in web.xml will map DispatcherServlet with url pattern *.html. One thing to note here is the name of servlet in <servlet-name> tag in web.xml. Once the DispatcherServlet is initialized, it will look for a file name [servlet-name]-servlet.xml in WEB-INF folder of web application. In this example, the framework will look for file called spring-servlet.xml.

Create a new file spring-servlet.xml under /WebContent/WEB-INF/ folder. This is the spring configuration. Copy following code into it.
File: /WebContent/WEB-INF/spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    <!-- freemarker config -->
    <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
      <property name="templateLoaderPath" value="/WEB-INF/ftl/"/>
    </bean>
    
    <!--
      View resolvers can also be configured with ResourceBundles or XML files. If you need
      different view resolving based on Locale, you have to use the resource bundle resolver.
    -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
      <property name="cache" value="true"/>
      <property name="prefix" value=""/>
      <property name="suffix" value=".ftl"/>
    </bean>
    <context:component-scan
        base-package="net.viralpatel" />
         
</beans>

In the above xml configuration file, we have defined a tag <context:component-scan>. This will allow Spring to load all the components from package net.viralpatel and all its child packages. This will load our UserController class. Also we have defined a bean viewResolver. We uses org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver as view resolver. Also notice how we defined bean freemarkerConfig. This defines Freemarker configuration, in our case just one property templateLoaderPath; the path where we will store all our .ftl template files.

Thus the bean viewResolver will resolve the freemarker template view. Note that in our UserController class, we have return a view name “index”. This will be resolved to path /WEB-INF/ftl/index.ftl by FreeMarkerViewResolver.

Step 3: Create Spring MVC Controller

File: /src/net/viralpatel/UserController.java

package net.viralpatel;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class UserController {
    /**
     * Static list of users to simulate Database
     */
    private static List<User> userList = new ArrayList<User>();
    //Initialize the list with some data for index screen
    static {
        userList.add(new User("Bill", "Gates"));
        userList.add(new User("Steve", "Jobs"));
        userList.add(new User("Larry", "Page"));
        userList.add(new User("Sergey", "Brin"));
        userList.add(new User("Larry", "Ellison"));
    }
    /**
     * Saves the static list of users in model and renders it
     * via freemarker template.
     *
     * @param model
     * @return The index view (FTL)
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(@ModelAttribute("model") ModelMap model) {
        model.addAttribute("userList", userList);
        return "index";
    }
    /**
     * Add a new user into static user lists and display the
     * same into FTL via redirect
     *
     * @param user
     * @return Redirect to /index page to display user list
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(@ModelAttribute("user") User user) {
        if (null != user && null != user.getFirstname()
                && null != user.getLastname() && !user.getFirstname().isEmpty()
                && !user.getLastname().isEmpty()) {
            synchronized (userList) {
                userList.add(user);
            }
        }
        return "redirect:index.html";
    }
}

The UserController is a simple Spring 3 MVC controller that handles request/response. We have created a private static List userList which stores the user entries. Note that in ideal example you would like to read data from database. But for sake of simplicity we will stick to static List :)

There are two methods index() and add(), both mapped via @RequestMapping annotation. The index() method will simply store the users list in model object and render “index” view (index.ftl). And the add() method gets the user details from html form and add it inside static List. Once the add() has added user, it simply redirects the request to /index.html which will render the user list.

Apart from the above UserController class, we will also need a bean class User which holds the user information like firstname, lastname etc.

File: /src/net/viralpatel/User.java

package net.viralpatel;
public class User {
    private String firstname;
    private String lastname;
    public User() {
    }
    public User(String firstname, String lastname) {
        this.firstname = firstname;
        this.lastname = lastname;
    }
    //Add Getter and Setter methods
}

Now add Freemarker view in your project.

Step 4: Create Freemarker Template Files

Create a new file index.ftl under folder /WebContent/WEB-INF/ftl/. Copy following content into it.

File: /WebContent/WEB-INF/ftl/index.ftl

<html>
<head><title>ViralPatel.net - FreeMarker Spring MVC Hello World</title>
<body>
<div id="header">
<H2>
    <a href="http://viralpatel.net"><img height="37" width="236" border="0px" src="http://viralpatel.net/blogs/wp-content/themes/vp/images/logo.png" align="left"/></a>
    FreeMarker Spring MVC Hello World
</H2>
</div>
<div id="content">
    
  <fieldset>
    <legend>Add User</legend>
  <form name="user" action="add.html" method="post">
    Firstname: <input type="text" name="firstname" /> <br/>
    Lastname: <input type="text" name="lastname" />   <br/>
    <input type="submit" value="   Save   " />
  </form>
  </fieldset>
  <br/>
  <table class="datatable">
    <tr>
        <th>Firstname</th>  <th>Lastname</th>
    </tr>
    <#list model["userList"] as user>
    <tr>
        <td>${user.firstname}</td> <td>${user.lastname}</td>
    </tr>
    </#list>
  </table>
</div
</body>
</html

This is a simple FTL template file. We just iterate model[“userList”] list in a loop and prints user’s firstname and lastname in table.

That’s All Folks

You may want to run the application see the result. I assume you have already configured Tomcat in eclipse. All you need to do:
Open Server view from Windows > Show View > Server. Right click in this view and select New > Server and add your server details.

To run the project, right click on Project name from Project Explorer and select Run as > Run on Server (Shortcut: Alt+Shift+X, R)

URL: http://localhost:8080/Freemarker_SpringMVC_example/index.html
freemarker-springmvc-ftl-example

Download Source Code

Freemarker_SpringMVC_example.zip (4.4 MB)

Reference : viralpatel.net

 

English: Logo of Apache Struts

Today we will create a Struts2 based application that uses Freemarker FTL as view instead of JSP. This would give you a good insight in Struts2 + Freemarker integration. The application is similar to previous tutorial’s User app, where a list of users will be displayed and we can add new user.

The application is very simple:

  1. There is a table that displays user info like firstname, lastname.
  2. New user can be added via Add User form.

Below is the wireframe of our final Freemarker based Struts2 app.
freemarker-servlet-wireframe

So lets get started.

Things We Need

Before we starts with our Struts2 + FreeMarker example, we will need few tools.

  1. JDK 1.6 or above (download)
  2. Tomcat 6.x or above or any other container (Glassfish, JBoss, Websphere, Weblogic etc) (download)
  3. Eclipse 3.4.x or above (download)
  4. Struts 2.3.4.1 or above (download)
  5. Freemarker JAR v2.3.15 or above(download)

Let us start with our Struts2 based Freemarker application.

Step 1: Getting Started

Open Eclipse and goto File -> New -> Project and select Dynamic Web Project in the New Project wizard screen.

dynamic web project in eclipse

After selecting Dynamic Web Project, press Next.

eclipse dynamic web project

Write the name of the project. For example Freemarker_Struts2_example. Once this is done, select the target runtime environment (e.g. Apache Tomcat v6.0). This is to run the project inside Eclipse environment. After this press Finish.

Once the project is created, you can see its structure in Project Explorer. This is how the project structure would look like when we finish the tutorial and add all source code.

struts2-ftl-eclipse-project-structure

Till this step, our basic Eclipse web project is ready. We will now add Struts2 and Freemarker support to this project.

Step 2: Adding Struts2 Support

First copy all required Struts2 JAR and supporting JAR files in WebContent > WEB-INF > lib folder. Create this folder if it does not exists. Don’t worry if you do not have these JARs. You can download the complete source code with JAR files at the end of this tutorial.

Next we change web.xml (deployment descriptor) and add Struts2 support to it. If you do not know why we do this, I strongly recommends you to go through Struts2 Tutorial series.

Related: Struts2 hello world example

Update the web.xml with following code:

File: /WebContent/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:javaee="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_9" version="2.4">
  <display-name>Freemarker Struts2 example - viralpatel.net</display-name>
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>
          org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
    </filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

The above code in web.xml will define a filter StrutsPrepareAndExecuteFilter and maps it with url pattern /*. Thus each request will go through the Struts2 framework and it will decide wheather an action is available which can be called or default action should be allowed. Also struts framework will try to load its configuration from struts.xml file. It expects this file to be present in classpath (WEB-INF/classes) of the application when the source is compiled. Thus we will create a source folder called Resources and put the struts.xml file in it.

To create a source folder, right click on your project in Project Explorer view of Eclipse and select New > Source Folder.

struts2-resource-folder

Specify folder name Resources and press Finish.

Create a new file struts.xml under Resources folder. Copy following code into it.

File: /Resources/struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

 <struts>
    <constant name="struts.enable.DynamicMethodInvocation"
        value="false" />
    <constant name="struts.devMode" value="false" />

    <package name="default" extends="struts-default" namespace="/">
        <action name="list" method="list"
           >
            <result type="freemarker" name="success">/WEB-INF/ftl/index.ftl</result>
        </action>
        <action name="add" method="add"
           >
            <result type="freemarker" name="success">/WEB-INF/ftl/index.ftl</result>
        </action>
    </package>
</struts>

Note that in above configuration file, we have defined User action of our application. We defined two actions using <action> tag. One to list the users and another to add new user. Note how we used attribute method="add" and method="list" to let Struts2 know which particular method needs to be called within the Action class. Also the result type mapped here is type="freemarker". Struts2 provides a first-class support to Freemarker template. All one has to do is to define result type freemarker. Struts automatically manage the view forwards in this case. On success of the action we forward the request to /WEB-INF/ftl/index.ftl freemarker view.

Step 3: Create Struts2 Action

Create new Struts2 action class UserAction under /src/net/viralpatel/struts2/ folder and copy following source code into it.

File: /src/net/viralpatel/struts2/UserAction.java

package net.viralpatel.struts2;

import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport {

	private static final long serialVersionUID = -8366209797454396351L;

	private static List<User> userList = new ArrayList<User>();

	private User user;

	static {
		userList.add(new User("Bill", "Gates"));
		userList.add(new User("Steve", "Jobs"));
		userList.add(new User("Larry", "Page"));
		userList.add(new User("Sergey", "Brin"));
		userList.add(new User("Larry", "Ellison"));
	}

    /**
     * Action method to display user list. Uses <code>userList</code> array 
     * object defined as class level attribute to display list of users.
     * @return SUCCESS 
     */
    public String list() {
    	return SUCCESS;
    }

    /**
     * Action method to add new user. Read the user information
     * via <code>user</code> object defined as class level attribute.
     * @return SUCCESS if user is added successfully
     */
    public String add() {

    	System.out.println("User:"+user);

        userList.add(user);

    	return SUCCESS;
    }

    public List<User> getUserList() {
	return userList;
    }

    public void setUserList(List<User> userList) {
	UserAction.userList = userList;
    }

    public User getUser() {
	return user;
    }

    public void setUser(User user) {
	this.user = user;
    }
}

In above Struts2 action class, we defined two methods: add() and list() for our application. Also note that we have created a static ArrayList userList, which holds the user information. This is a dummy list just to mimic database values. In an ideal application, you may have to call Database and fetch list of users from a table. But for sake of simplicity we stores users in an arraylist.

Other than userList, we also defined User user object as class attribute. This object will store the user information when a new user is added. It act as a form bean object for action class.

Apart from the above UserController class, we will also need a bean class User which holds the user information like firstname, lastname etc.

File: /src/net/viralpatel/struts2/User.java

package net.viralpatel;

public class User {
	private String firstname;
	private String lastname;

	public User() {
	}

	public User(String firstname, String lastname) {
		this.firstname = firstname;
		this.lastname = lastname;

	}

	//Add Getter and Setter methods

}

Now add Freemarker view in your project.

Step 4: Create Freemarker Template File

Create a new file index.ftl under folder /WebContent/WEB-INF/ftl/. Copy following content into it.

File: /WebContent/WEB-INF/ftl/index.ftl

<html>
<head>
  <meta name="generator" content=
  "HTML Tidy for Linux/x86 (vers 11 February 2007), see www.w3.org" />

  <title>ViralPatel.net - FreeMarker Spring MVC Hello World</title>
</head>

<body>
  <div id="header">
    <h2><a href="http://viralpatel.net"><img height="37" width="236" border="0px" src=
    "http://viralpatel.net/blogs/wp-content/themes/vp/images/logo.png" align=
    "left" /></a> FreeMarker Struts2 Hello World</h2>
  </div>

  <div id="content">
    <fieldset>
      <legend>Add User</legend>

	<@s.form action="add" method="post">
	    <@s.textfield label="First name" name="user.firstname"/>
	    <@s.textfield label="Last name" name="user.lastname"/>
	    <@s.submit value="Save"/>
	</@s.form>    </fieldset><br />    <table>
      <tr>
        <th>Firstname</th>
        <th>Lastname</th>
      </tr>
	<#list userList as user>
  	<tr>
  		<td>${user.firstname}</td> <td>${user.lastname}</td>
  	</tr>
    </#list>	  
    </table>
  </div>
</body>
</html>

This is a simple FTL template file. We just iterate model userList list in a loop and prints user’s firstname and lastname in table.

One last thing, the default index.jsp is opened when you tries to execute your application in eclipse. So just update it and add link to our User page. Modify the /WebContent/index.jsp file and add following code into it.

File: /WebContent/index.jsp

<html>
<head>
    <title>Welcome</title>
</head>
<body>
    <a href="list">Freemarker Struts2 example</a>
</body>
</html>

That’s All Folks

You may want to run the application see the result. I assume you have already configured Tomcat in eclipse. All you need to do:
Open Server view from Windows > Show View > Server. Right click in this view and select New > Server and add your server details.

To run the project, right click on Project name from Project Explorer and select Run as > Run on Server (Shortcut: Alt+Shift+X, R)

URL: http://localhost:8080/Freemarker_Struts2_example/list
struts2-freemarker-ftl-example

Download Source Code

Freemarker_Struts2_example.zip (3.3 MB)

Reference : viralpatel.net

English: Coogee Beach

Scroll down and copy/paste the last script in the head of your page. Add onLoad=”initializeMaps” to you body tag and put an element with id=”map_canvas” in your page. Be sure to give it dimensions and your ready to go! Oh, and don’t forget to include the Google Maps API..

Lets keep it simple. Take the base map script that we also used in our previous tutorials:

function initializeMaps() {
var latlng = new google.maps.LatLng(-33.92, 151.25);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
var map = new google.maps.Map(document.getElementById(“map_canvas”),myOptions);
}

Before we initialize this map you need an array (that’s a list) with locations and titles. That looks like this:

var markers = [
[‘Bondi Beach‘, -33.890542, 151.274856],
[‘Coogee Beach‘, -33.923036, 151.259052],
[‘Cronulla Beach‘, -34.028249, 151.157507],
[‘Manly Beach‘, -33.80010128657071, 151.28747820854187],
[‘Maroubra Beach‘, -33.950198, 151.259302]
];

This code is quite easy. Every line in this array stands for a marker. First value is the title of the marker and the second and last form the locational latitude and longitude.

Now lets add a few lines of code to out base script to loop through these marker list and place those markers on the map:

var infowindow = new google.maps.InfoWindow(), marker, i;
for (i = 0; i < markers.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(markers[i][1], markers[i][2]),
map: map
});
google.maps.event.addListener(marker, ‘click’, (function(marker, i) {
return function() {
infowindow.setContent(markers[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}

That’s all. It’s that easy!

The complete copy-and-paste script

var markers = [
[‘Bondi Beach’, -33.890542, 151.274856],
[‘Coogee Beach’, -33.923036, 151.259052],
[‘Cronulla Beach’, -34.028249, 151.157507],
[‘Manly Beach’, -33.80010128657071, 151.28747820854187],
[‘Maroubra Beach’, -33.950198, 151.259302]
];

function initializeMaps() {
var latlng = new google.maps.LatLng(-33.92, 151.25);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
var map = new google.maps.Map(document.getElementById(“map_canvas”),myOptions);
var infowindow = new google.maps.InfoWindow(), marker, i;
for (i = 0; i < markers.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(markers[i][1], markers[i][2]),
map: map
});
google.maps.event.addListener(marker, ‘click’, (function(marker, i) {
return function() {
infowindow.setContent(markers[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}

Auto-center map around markers

I changed the above script and added a few lines of code to automatically center and zoom the map around the markers. This can easilly be done with the LatLngBounds() function from the Google Maps API (v3):

var bounds = new google.maps.LatLngBounds();
// in the marker-drawing loop:
bounds.extend(pos);
// after the loop:
map.fitBounds(bounds);

If these lines are included in the script, it looks like this:

var markers = [
[‘Bondi Beach’, -33.890542, 151.274856],
[‘Coogee Beach’, -33.923036, 151.259052],
[‘Cronulla Beach’, -34.028249, 151.157507],
[‘Manly Beach’, -33.80010128657071, 151.28747820854187],
[‘Maroubra Beach’, -33.950198, 151.259302]
];

function initializeMaps() {
var myOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
var map = new google.maps.Map(document.getElementById(“map_canvas”),myOptions);
var infowindow = new google.maps.InfoWindow();
var marker, i;
var bounds = new google.maps.LatLngBounds();

for (i = 0; i < markers.length; i++) {
var pos = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(pos);
marker = new google.maps.Marker({
position: pos,
map: map
});
google.maps.event.addListener(marker, ‘click’, (function(marker, i) {
return function() {
infowindow.setContent(markers[i][0]);
infowindow.open(map, marker);
}
}
})(marker, i));
map.fitBounds(bounds);
}

International Bibliography of Periodical Liter...

There are major differences between iBatis and Hibernate but both the solutions work well, given their specific domain. Personally I would suggest you should use iBATIS if:

  • You want to create your own SQL‘s and are willing to maintain them.
  • your environment is driven by relational data model.
  • you have to work existing and complex schema’s.

And simply use Hibernate if:

  • Your environment is driven by object model and wants generates SQL automatically.

To count there are few differences:

  • iBATIS is:
    • Simpler
    • Faster development time
    • Flixable
    • Much smaller in package size
  • Hibernate:
    • Generates SQL for you which means you don’t spend time on SQL
    • Provides much more advance cache
    • Highly scalable

Other difference is that iBATIS makes use of SQL which could be database dependent where as Hibernate makes use of HQL which is relatively independent of databases and it is easier to change db in Hibernate.

Hibernate maps your Java POJO objects to the Database tables where as iBatis maps the ResultSet from JDBC API to your POJO Objets.

If you are using stored procedures, well you can do it in Hibernate but it is little difficult in comparision of iBATIS. As an alternative solution iBATIS maps results sets to objects, so no need to care about table structures. This works very well for stored procedures, works very well for reporting applications, etc

Finally, Hibernate and iBATIS both are open source Object Relational Mapping(ORM) tools available in the industry. Use of each of these tools depends on the context you are using them. Hibernate and iBatis both also have good support from SPRING framework so it should not be a problem to chose one of them.

 

English: example of a data table with rollup f...

 

This tag is used to create table on the page. The component is rendered as an html element. UIColumn child components are responsible for rendering columns of the table. In these columns you can put any type of component like input text box, output text, command button etc.

<h:column> tag is used to create column. There can be many column tags within dataTable tag. You can set header and footer in this table. For this <f:facet> tag is used. data table component and its children column component can use header and footer facet.

 

 

We can associate this table element to backing bean. So we can obtain data from this backing bean and display it on the table. Association of backing bean can also be helpful for event handling purpose. Suppose we inserted command button in columns of the table then event handling can be applied here. If you want to customize the table then cascading stylesheet (CSS) can be used. This will help you to enhance the appearance of the table’s headers, footer, rows, columns.

 

This section provides you the code to which uses this tag and some of its attributes. It uses backing bean that supplies data to the data table to be rendered to the cells of the columns of the table.

code description :

 

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<f:view><html><body>
<h:form>
<br><br><br>
<h:dataTable id="dt1" value="#{TableBean.perInfoAll}" var="item" bgcolor="#F1F1F1" border="10" cellpadding="5" cellspacing="3" first="0" rows="4" width="50%" dir="LTR" frame="hsides" rules="all" summary="This is a JSF code to create dataTable." >

<f:facet name="header">
<h:outputText value="This is 'dataTable' demo" />
</f:facet>

<h:column>
<f:facet name="header">
<h:outputText value="id" />
</f:facet>
<h:outputText value="#{item.id}"></h:outputText>
</h:column>

<h:column>
<f:facet name="header">
<h:outputText value="name"/>
</f:facet>
<h:outputText value="#{item.name}"></h:outputText>
</h:column>

<h:column>
<f:facet name="header">
<h:outputText value="phone"/>
</f:facet>
<h:outputText value="#{item.phone}"></h:outputText>
</h:column>

<h:column>
<f:facet name="header">
<h:outputText value="city"/>
</f:facet>
<h:outputText value="#{item.city}"></h:outputText>
</h:column>

<h:column>
<f:facet name="header">
<h:outputText value="pin"/>
</f:facet>
<h:outputText value="#{item.pin}"></h:outputText>
</h:column>

<f:facet name="footer">
"The End" />
</f:facet>

</h:dataTable><br><br>

</h:form>
</body></html></f:view>

 

Rendered Output :

 



In this example we have used <h:dataTable> tag. This <h:dataTable> tag has many attributes to give form and shape to the table and getting data from backing bean’s attribute to display this data to the columns of the table. <f:facet> tag is used to create a header and a
footer for a dataTable component and it can create the same for columns also. So in this example we have used facet tag in dataTabe tag to create header and footer of the table component and in column tag also to create header for column. In this example, “This is ‘dataTable’ demo” is the header and “The End” is the footer for the table and “id” “name” “phone” “city” “pin” are headers for columns. In his example we have populated data to the table from bean named “TableBean”. It contains an attribute “perInfoAll” that is an array of objects of type “perInfo” class which contains some attributes like id, name, phone, city, pin that is to be displayed on the table. In the value attribute of dataTable tag, we have specified the binding expression to bind this component to the bean (
value="#{TableBean.perInfoAll}") and value specified in var attribute is used to populate data to the column of the table from attributes defined in class perInfo (value="#{item.id}"). The code for the bean has been given below (remember to specify it in faces-cocfig.xml file) :

 

public class TableBean {

private perInfo[] perInfoAll = new perInfo[]{
new perInfo(101, "CHANDAN", "9891444444", "aaa", 11111),
new perInfo(102, "RAVI", "9911666666", "bbb" ,22222),
new perInfo(103, "JOHN", "9313888888", "ccc", 33333),
new perInfo(104, "ANDREW", "9911222222", "ddd" , 44444),
new perInfo(105, "SYMONDS", "9313999999", "eee", 55555),
};

public perInfo[] getperInfoAll() {
return perInfoAll;
}

public class perInfo {
int id;
String name;
String phone;
String city;
int pin;

public perInfo(int id, String name, String phone, String city, int pin) {
this.id = id;
this.name = name;
this.phone = phone;
this.city = city;
this.pin= pin;
}

public int getid() {
return id;
}

public String getname() {
return name;
}

public String getphone() {
return phone;
}

public String getcity() {
return city;
}

public int getpin() {
return pin;
}

}

}

 

HTML Source Code:

 

<html>
     <body>
          <form id="_id0" method="post" action="/dt/data.jsf;jsessionid
=B95AF7B5F7D80BCB5638B91AC8154C33" enctype="application/x-www-form-urlencoded">
              <br><br><br>
		<table id="_id0:dt1" bgcolor="#F1F1F1" border="10"
 cellpadding="5" cellspacing="3" dir="LTR" frame="hsides" rules="all"
 summary="This is a JSF code to create dataTable." width="50%">
                    <thead>
                       <tr><th colspan="5" scope="colgroup">This is
 'dataTable' demo</th></tr>
                       <tr>
                          <th scope="col">id</th>
                          <th scope="col">name</th>
                          <th scope="col">phone</th>
                          <th scope="col">city</th>
                          <th scope="col">pin</th>
                       </tr>
                    </thead>
                    <tfoot>
                       <tr><td colspan="5">The End</td></tr>
                    </tfoot>
                    <tbody>
                        <tr>
                           <td>101</td>
                           <td>CHANDAN</td>
                           <td>9891444444</td>
                           <td>aaa</td>
                           <td>11111</td>
                        </tr>
                        <tr>
                           <td>102</td>
                           <td>RAVI</td>
                           <td>9911666666</td>
                           <td>bbb</td>
                           <td>22222</td>
                        </tr>
                        <tr>
                           <td>103</td>
                           <td>JOHN</td>
                           <td>9313888888</td>
                           <td>ccc</td>
                           <td>33333</td>
                        </tr>
                        <tr>
                           <td>104</td>
                           <td>ANDREW</td>
                           <td>9911222222</td>
                           <td>ddd</td>
                           <td>44444</td>
                        </tr>
                    </tbody>
                </table>
                <br><br>
		<input type="hidden" name="_id0" value="_id0" />
         </form>
    </body>
</html>

 

This tag has some attributes. These are listed below :

 

  • id : This is used to uniquely identify the table component. This must be unique within the closest parent component.
  • value : It represents the value of the component. It represents the value over which iteration is to be done. It may be an array or any iterator object .
  • var : This is the name of the variable created by the data table that represents the current item in the value. This attribute helps exposing the data in the rows of the table.
  • bgcolor : This attribute is used to set the background color for the table.
  • border : We can set the width of the table’s border around the table.
  • cellpadding : This sets the space between the content and the border of the cell.
  • cellspacing : It specifies the amount of space to leave between cells.
  • first : This is used to specify the row number of the first row from which displaying is to be started onwards. Suppose, this property is set to 3,displaying will be started from the third row of the underlying data.
  • rows : This attribute specifies the number of rows to display. This displaying will be started from the index specified in the “first” attribute. If we set this attribute to zero then all rows will be displayed.
  • width : This is used to set the width of the entire table. Its value is specified in %. Suppose we set it to 50% then this table will be shown in the 50% space of the width of your screen.
  • dir : This attribute indicates the direction of the text to be displayed in the cell. It takes “LTR” (left-to-right) and “RTL” (right-to-left) values. If we don’t specify this attribute then the content will be displayed in center.
  • frame : This attribute specifyes which sides of the frame surrounding this table will be visible. This attribute can take some values shown below :

 

  1. none  No side, Default Value
  2. above  Top side only
  3. below  Bottom side only
  4. hsides   Top and bottom sides only
  5. vsides   Right and left sides only
  6. lhs   Left hand side only
  7. rhs  Right hand side only
  8. box   All four sides 
  9. border  All four sides

 

  • rules : This attribute is used to draw lines between cells. It can take some values given below :
    1. none   No rules, default value
    2. groups  Between row groups
    3. rows   Between rows only
    4. cols  Between columns only
    5. all   Between all rows and columns
  • summary : You can specify summary of the purpose of the table.
  • rendered : It takes boolean value.This indicates whether or not this component should be rendered. Its default value is “true”. If it is set to false then it prevents rendering of this component to the page.
  • captionClass : Space separated list of CSS class or classes that will be applied to any caption generated for this table.
  • captionStyle : It specifies CSS style or styles to be applied when this caption is rendered.
  • columnClasses : Comma seperated list of CSS classes that will be applied to the columns of this table.
  • footerClass : This attribute takes Space-separated list of CSS style class or classes that will be applied to aheaderter generated for this table.
  • headerClass : This attribute takes Space-separated list of CSS style class or classes that will be
    applied to any header generated for this table.
  • rowClasses : It is a list of CSS classes applied to the rows of the table.These classes should be separated by comma. If we want to apply CSS class for individual rows then we can specify space separated list of CSS classes. Style classes are applied to rows in the same order that they are
    defined. If we have two CSS classes then first class is applied to the first row and the second one is applied to the second. Then again in the third row, the first CSS is applied and so on. This process goes on till the last row of the table. 
  • lang :  It sets the base language of an element?s attributes and text i.e. the language used in the generated markup for this component.
  • styleClass : It sets the name of CSS classor classes that is applied at the time of rendering the element.
  • title : The title attribute is used to set the tooltip text to display for the rendered  component.Tooltip describes an element when rendered to the client. 
  • binding : It is a value binding expression that is used to link component to a property in a backing bean.
  • onclick : It sets the JavaScript code to execute when a pointer button is clicked over this element.
  • ondblclick : It sets the JavaScript code to execute when a pointer button is double clicked over this element.
  • onkeydown : It sets the JavaScript code to execute when a key is pressed down over this element.
  • onkeypress : It sets the JavaScript code to execute when a key is pressed and released over this element.
  • onkeyup : It sets the JavaScript code to execute when a key is released over this element.
  • onmousedown : It sets the JavaScript code to execute when a pointer button is pressed down over this element.
  • onmousemove : It sets the JavaScript code to execute when a pointer button is moved within this element.
  • onmouseout : It sets the JavaScript code to execute when a pointer button is moved away from this element.
  • onmouseover : It sets the JavaScript code to execute when a pointer button is moved onto this element.
  • onmouseup : It sets the JavaScript code to execute when a pointer button is released over this element.

 

 

Image representing Google as depicted in Crunc...

Google Map API has been a great way to show geographical information on web. A lot of mashup tools like this, have been created around Google Maps to show a wide variety of data. In my previous article about Introduction to Google Maps API, I had described basic APIs to integrate Google Map in your webpage. In this small article we will discuss a great feature of Google Maps API that can be used to locate any City/Country/Place on Map. This is called Geocoding.

Google Maps API provides a wonderful API called Geocoding API that enables you to fetch any location and pin point it on Google Map. GClientGeocoder is the class that we use to get the geocoder that get us the location. We will use getLatLng() method to get latitude/longitude of any location.
Check the following code.

01
02
03
04
05
06
07
08
09
10
11
12
var place =  "New York";
geocoder = new GClientGeocoder();
geocoder.getLatLng(place, function(point) {
    if (!point) {
        alert(place + " not found");
    } else {
        var info = "<h3>"+place+"</h3>Latitude: "+point.y+"  Longitude:"+point.x;
        var marker = new GMarker(point);
        map.addOverlay(marker);
        marker.openInfoWindowHtml(info);
    }
});

In above code snippet we passed string “New York” and a handler function to getLatLng() method of GClientGeocoder. GClientGeocoder class will call google server for the location and when it gets the result, it pass the result to the handler function that we specified. Thus handler function will get point (GPoint) object from which we can get the latitude and longitude of location. In above code we have created a marker and placed it on the map.

Online Demo

Google Map Reverse Geocode Example

English: Iceland, from the NASA Visible Earth ...

To start with let us see how to integrate Image Gallery with your App. Consider a requirement, you want your app user to select Image from the Gallery and use that image to do some stuff. For example, in Facebook app you can select Picture from your phone and upload directly to your profile.

Let us create an example with following requirement:

  1. First screen shows user with and Image view and a button to loan Picture.
  2. On click of “Load Picture” button, user will be redirected to Android’s Image Gallery where she can select one image.
  3. Once the image is selected, the image will be loaded in Image view on main screen.

So lets start.

Step 1: Create Basic Android Project in Eclipse

Create a Hello World Android project in Eclipse. Go to New > Project > Android Project. Give the project name as ImageGalleryDemo and select Android Runtime 2.1 or sdk 7.

Once you are done with above steps, you will have a basic hello world Android App.

Step 2: Change the Layout

For our demo, we need simple layout. One Image view to display user selected image and one button to trigger Image gallery.

Open layout/main.xml in your android project and replace its content with following:

File: res/layout/main.xml

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ImageView
        android:id="@+id/imgView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"></ImageView>
    <Button
        android:id="@+id/buttonLoadPicture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:text="Load Picture"
        android:layout_gravity="center"></Button>
</LinearLayout>

So our Android’s app UI is very simple, One LinearLayout to organize Image view and Button linearly. Note that the id of Image view is imgView and that of Button is buttonLoadPicture.

Step 3: Android Java Code to trigger Image Gallery Intent

We now need to write some Java code to actually handle the button click. On click of buttonLoadPicture button, we need to trigger the intent for Image Gallery.

Thus, on click of button we will trigger following code:

1
2
3
4
Intent i = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);

Note how we passed an integer RESULT_LOAD_IMAGE to startActivityForResult() method. This is to handle the result back when an image is selected from Image Gallery.

So the above code will trigger Image Gallery. But how to retrieve back the image selected by user in our main activity?

Step 4: Getting back selected Image details in Main Activity

Once user will select an image, the method onActivityResult() of our main activity will be called. We need to handle the data in this method as follows:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     super.onActivityResult(requestCode, resultCode, data);
     
     if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
         Uri selectedImage = data.getData();
         String[] filePathColumn = { MediaStore.Images.Media.DATA };
         Cursor cursor = getContentResolver().query(selectedImage,
                 filePathColumn, null, null, null);
         cursor.moveToFirst();
         int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
         String picturePath = cursor.getString(columnIndex);
         cursor.close();
                     
         // String picturePath contains the path of selected Image
     }

Note that method onActivityResult gets called once an Image is selected. In this method, we check if the activity that was triggered was indeed Image Gallery (It is common to trigger different intents from the same activity and expects result from each). For this we used RESULT_LOAD_IMAGE integer that we passed previously to startActivityForResult() method.

Final Code

Below is the final code of ImageGalleryDemoActivity class.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package net.viralpatel.android.imagegalleray;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class ImageGalleryDemoActivity extends Activity {
    
    
    private static int RESULT_LOAD_IMAGE = 1;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
        buttonLoadImage.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
                
                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                
                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });
    }
    
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            
            ImageView imageView = (ImageView) findViewById(R.id.imgView);
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
        
        }
    
    
    }
}

Screen shots of Android app

First screen: Lets user to trigger Image Gallery
android-gallery-intent-example

User can select an image from Image Gallery
android-gallery-intent-select-image

Once user selects an image, the same will be displayed on our main activity
android-gallery-intent-example-demo

Download Source Code

ImageGalleryDemo.zip (46 KB)

Image representing Dropbox as depicted in Crun...

Recently, the popular Cloud based startup Dropboxis getting lot of attention on Internet. It is a free file synchronization/backup service where you can backup, save and share files. Dropbox gives 2 GB of free space to every user where one can save / backup their files.

One of the interesting usage of Dropbox can be to use it as Subversion Repository to store your projects. We can create a local SVN repository on Dropbox which can be synchronized on Cloud by Dropbox. You can checkout this repository and add your projects / files into it. This way you can access your project anywhere. Also it is possible to share your repository with other users if you want to. Simply by sharing Dropbox folder where you have stored subversion repository can enables you to share it with other users.

Here is an example of hosting a local SVN repository on Dropbox.

Step 1: Create Dropbox repository

cd ~Dropbox
mkdir SVNRepository
cd SVNRepository

If you are using subversion command line utilities in Windows or using Unix box, we can create a new subversion repository by using svnadmin.

svnadmin create .

If you are using TortoiseSVN client then you may want to create repository using following:

Right-click on the newly created folder SVNRepository and select TortoiseSVNCreate Repository here….

We just created a Subversion repository on top of Dropbox folder. Don’t edit those files yourself!!. If you get any errors make sure that the folder is empty and not write protected.

Step 2: Checkout Dropbox repository

Our Dropbox repository is ready and we can do checkin / checkout in this now. Before we add any project / files in this repository, we need to make sure we add proper directory structure in this SVN repository. It is a good practice to divide an SVN repositories in three directory: trunk, branches and tags.

First create a working folder where you want to checkout your SVN repository.

mkdir ~MyWorkspace
cd MyWorkspace
svn checkout file:///~Dropbox/SVNRepository

This will checkout the newly created repository in folder MyWorkspace.

Now create 3 directories in MyWorkspace: trunk, branches and tags and commit the change back to repository.

mkdir trunk
mkdir branches
mkdir tags
svn commit -m "Initial setup (committing trunk, branches, tags)"

Step 3: Checkout Trunk of Dropbox SVN repository

We are done with the setup.. Just checkout the Trunk of this newly created SVN repository and start committing your changes.

svn checkout file:///~Dropbox/SVNRepository/trunk

That’s it. Now you can checkout the SVN repository “file:///~Dropbox/SVNRepository/trunk” anywhere and commit your changes to it. Ofcourse this is now hosted on Dropbox so you can easily synchronize your changes between different computers. You can also share this repository with other Dropbox users letting them SVN your repository access.

Nuvola-inspired File Icons for MediaWiki-filei...

you can extract files form zip file using java
String LOCATION_ZIP_FILE = “C:\\Documents and Settings\\zeeshan\\Desktop\\ztestzip.zip”;
// declare helper constants
try {
String destinationname = “c:\\zip\\”;
byte[] buf = new byte[1024];
ZipInputStream zipinputstream = null;
ZipEntry zipentry;
File newFile = null;
zipinputstream = new ZipInputStream(
new FileInputStream(LOCATION_ZIP_FILE));

zipentry = zipinputstream.getNextEntry();
while (zipentry != null) {
//for each entry to be extracted
String entryName = destinationname + zipentry.getName();
entryName = entryName.replace(‘/’, File.separatorChar);
entryName = entryName.replace(‘\\’, File.separatorChar);
System.out.println(“entryname ” + entryName+”\n”+zipentry.getName());
int n;
FileOutputStream fileoutputstream;
newFile = new File(entryName);
if (zipentry.isDirectory()) {
if (!newFile.mkdirs()) {
break;
}
zipentry = zipinputstream.getNextEntry();
continue;
}

fileoutputstream = new FileOutputStream(entryName);

while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
fileoutputstream.write(buf, 0, n);

}

fileoutputstream.close();
zipinputstream.closeEntry();
zipentry = zipinputstream.getNextEntry();
newFile.delete();
}//while

zipinputstream.close();
} catch (Exception e) {
e.printStackTrace();
}

 

}

Image representing Google Search as depicted i...

Despite most operating systems nowadays have graphical user interface and most of the tools are implemented using one, the command line prompt (cmd) is still a powerful tool. This is especially true when it comes to performing administrative tasks or advanced networking information queries. In this article, we’ll show you how to find many network related information about a website using the command prompt. For examples, the article will be using the Google website.

Steps

  1. 1

    Start the command-line prompt. This is usually done by one of the following methods:

    • Going to Start >> All Programs >> Accessories >> Command Prompt on Windows Vista/7. According to your settings, in older systems (XP, 2000, etc), you might find “Accessories” directly on “Start”
    • Go to Start >> Run and then type cmd in the run dialog and press Enter.

IP Address and Connectivity

 

A screenshot of the ping command

 

  1. 1

    Type the following command to the command-line prompt, replacing google.com with the website you want to get the information for:

    • ping google.com
  2. 2

    Find the IP address of the website (more precisely, the server) on the first line, where it says “Pinging Website_Address_You_Entered [X.X.X.X] with 32 bytes of data:”

  3. 3

    Notice the connectivity between you machine and the server from the line where it says: “Packets: Sent = X, Received = X, Lost = X (X% loss),” where all the Xs will be replaced by numbers. This gives you an idea of how much percent of the packets sent to the server will be lost.

Routing Information

 

A screenshot of a tracert session

 

A screenshot of a pathping command execution

 

  1. 1

    Type the following command to the command-line prompt, replacing google.com with the website or server you want routing information for:

    • tracert google.com
  2. 2

    Notice the listing of hops along the route path of packets from your machine to the server. This gives you an idea of how many routers/hops the packet has to travel before reaching the server, starting from your machine.

  3. 3

    Use the pathping utility to find information about network latency and network loss at intermediate hops between a source and destination. Pathping sends multiple Echo Request messages to each router between a source and destination over a period of time and then computes results based on the packets returned from each router. Type the following to the command-line prompt:

    • pathping google.com

DNS information

 

A screenshot of nslookup execution

 

  1. 1

    Type the following on the command-line prompt, replacing google.com with the website or server you want DNS information for:

    • nslookup google.com
  2. 2

    Find the DNS server (first lines) and the IP addresses of the server you queried about.

Tips

  • Some of the commands explained above have other options that might be useful for finding out information about your internal network.
  • If you’re using these command in a corporate network or a school network, some of these commands might not give you results. Most institutions have firewalls with settings to deny services provided by these tools.