Spring ibatis example

Spring ibatis example

Here I am describing a spring ibatis example. It is a very simple Spring project with iBatis and Display tag. let me describe the working environment. my another post shows how to set up your environment.

note – this project is available at google code.
project name – springibatis
# Non-members may check out a read-only working copy anonymously over HTTP.

url(springibatis-read-only): svn checkout http://springibatis.googlecode.com/svn/trunk/

Eclipse 3.4: Ganymede;

Plugs in: svn, Maven, spring-ide, tomcat lunher, ant.

Tomcat: 5.5

FireFox: 3

Create a new project in Eclipse;

spring ibatis example - Eclipse create new project

Eclipse create new project

spring ibatis example - newproject1

create one package name:  click the right button on the src folder and select new -> Package and put  com.rajib.spring.ibatis value.

create a class Person under the ibatis folder. similar way create some other files – Person.xml, PersonDao.java, PersonDaoImpl.java

create applicationContext-ibatis.xml under src folder. we will describe at web.xml that where the applicationContext file is located. it looks

——————  applicationContext-ibatis.xm

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" id="dataSource">
<!-- property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/-->
<property name="driverClassName" value="org.gjt.mm.mysql.Driver"/>
<property name="url" value="jdbc:mysql://localhost/development"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</bean>

<!-- Transaction manager for a single JDBC DataSource -->
<bean  class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="dataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- SqlMap setup for iBATIS Database Layer -->
<bean class="org.springframework.orm.ibatis.SqlMapClientFactoryBean" id="sqlMapClient">
<property name="configLocation">
<value>classpath:SqlMapConfig.xml</value>
</property>
<property name="dataSource" ref="dataSource"/>
</bean>

<bean id="personDao" class="com.rajib.spring.ibatis.PersonDaoImpl">
<property name="dataSource" ref="dataSource"></property>
<property name="sqlMapClient" ref="sqlMapClient"></property>
</bean>

</beans>

 

here we create one bean ‘dataSource’ that store database connnection. we create another bean sqlMapClient that will be use all ibatis query. we push datasource bean to sqlMapClient bean. these 2 bean will use personDao later.

I used a new display tag that does column display, sorting, paging, cropping, grouping, exporting, smart linking and decoration of a table.

In index.jsp,

BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(
"applicationContext-ibatis.xml"));
PersonDao personDao = (PersonDao)beanFactory.getBean("personDao");
List<Person> allPersons = personDao.getAllPersons();
request.setAttribute( "persons", allPersons );

this is used to collecting data from database. the persons list is put into request so that the display tag can used it easily.

<display:table name="persons"  class="mars" pagesize="25">
<display:column property="id" title="ID" />
<display:column property="name" />
</display:table>

the output looks-

Spring ibatis example - output1

Spring tutorial

Spring tutorial

Here I will describe on Spring tutorial. let me describe the working environment. my another blog shows how to set up your environment. To know more on springframework please visit here.

Spring tutorial – step by step

In this example we are using following tools

Eclipse 3.4: Ganymede;

Plugs in: svn, Maven, spring-ide, tomcat lunher, ant.

Tomcat: 5.5

FireFox: 3

Create a new project in Eclipse;

Spring tutorial - Eclipse create new project

Spring tutorial – Eclipse create new project

Spring tutorial - set project name

Spring tutorial – set project name

create one package name:  click the right button on the src folder and select new -> Package and put  com.rajib.spring.samplespring.model value.

create a class Information under the model folder. In this Spring tutorial have used couple of java classes, here are they

——————Information.java

package com.rajib.spring.samplespring.model;

public class Information {
	private String projectName = "Spring demo1";
	private String version = " 1.1";

	public String getProjectName() {
		return projectName;
	}

	public void setProjectName(String projectName) {
		this.projectName = projectName;
	}

	public String getVersion() {
		return version;
	}

	public void setVersion(String version) {
		this.version = version;
	}
}

create an xml file  applicationContext.xml under the src file. by default spring is looking this under web-inf folder but we put his under class path intentionally thats why we will mention the conetx file location at the web.xml. In this spring tutorial, I am trying to show you can create a spring application. We can mention all beans under <beans> tag.

————- applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
  <bean id="information"      
    class="com.rajib.spring.samplespring.model.Information"/>
</beans>

we will show information.project name and information.version at index.jsp page. we used the information class as bean.

Create WebContent folder under the project. create WEB-INF folder under the WebContent folder. Create lib folder under WEB-INF folder. I used lot of jar files as library file. My lib contains jarlist jar files.

Create log4j.properties and web.xml file under WEB-INF folder.

————–log4j.properties

log4j.logger.java.sql=DEBUG, STDOUT
log4j.logger.com.ibatis=DEBUG, STDOUT
log4j.logger.java.sql.Statement=INFO,STDOUT
log4j.rootLogger=ERROR,STDOUT

log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender
log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout
log4j.appender.STDOUT.layout.conversionPattern=%-5p - %-26.26c{1} - %mn

————————- web.xml

 <?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<description>Spring simple example</description>
	<display-name>simplespring</display-name>
	<context-param>
		<param-name>webAppRootKey</param-name>
		<param-value>simplespring</param-value>
	</context-param>
	<context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>/WEB-INF/log4j.properties</param-value>
	</context-param>
	<context-param>
		<param-name>ADMIN_EMAIL_ADDRESS</param-name>
		<param-value>rajib_info@yahoo.com</param-value>
	</context-param>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/classes/applicationContext.xml</param-value>
	</context-param>

	<listener>
		<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<session-config>
		<session-timeout>10</session-timeout>
	</session-config>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

Create index.jsp file under WebContent folder.

———– index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@ page
	import="org.springframework.beans.factory.BeanFactory,org.springframework.beans.factory.xml.XmlBeanFactory,org.springframework.core.io.ClassPathResource,com.rajib.spring.samplespring.model.Information"%>
<head>
<title>Simple Spring example</title>
</head>
<body bgcolor="white">
	<h2>(Spring example by rajib_info@yahoo.com)</h2>

	<%
		BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(
				"applicationContext.xml"));
		Information info = (Information) beanFactory.getBean("information");
	%>

	Hello, this is sample spring project!
	<br /> Project Name is :
	<b> <%=info.getProjectName()%>
	</b> Project Version is :
	<b> <%=info.getVersion()%>
	</b>
</body>

to make the build path to do the following

Spring tutorial - eclipse build path

Spring tutorial – eclipse build path

-click right button on the project and select properties select the Java Build Path from the left side. click – Library tab from right side , click Add jar select all jars of  (SimpleSpring->WebContent->lib all jars). click the Ordre and Ecports tab and click on  Select All button.

How to run this project:

for building this project we need buld.xml

 

—————————- build.xml

<project name="simplespring" basedir="." default="deploy">
	<!-- Project settings -->
	<property name="project.distname" value="simplespring" />
	<!-- Local system paths -->
	<property file="${basedir}/build.properties" />
	<property name="webroot.dir" value="${basedir}/WebContent" />
	<property name="webinf.dir" value="${webroot.dir}/WEB-INF" />
	<property name="build.dir" value="target" />

	<!-- classpath for WEB-INF/lib -->
	<path id="compile.classpath">
		<pathelement path="${webinf.dir}/lib/acegi-security-1.0.3.jar" />
		<pathelement path="${webinf.dir}/lib/activation.jar" />
		<pathelement path="${webinf.dir}/lib/antlr-2.7.6.jar" />
		<pathelement path="${webinf.dir}/lib/aopalliance.jar" />
		<pathelement path="${webinf.dir}/lib/avalon-framework-4.2.0.jar" />
		<pathelement path="${webinf.dir}/lib/barbecue-1.1.jar" />
		<pathelement path="${webinf.dir}/lib/bsf-2.3.jar" />
		<pathelement path="${webinf.dir}/lib/bsh-2.0b4.jar" />
		<pathelement path="${webinf.dir}/lib/cglib-nodep-2.1_3.jar" />
		<pathelement path="${webinf.dir}/lib/commons-annotations.jar" />
		<pathelement path="${webinf.dir}/lib/commons-beanutils.jar" />
		<pathelement path="${webinf.dir}/lib/commons-codec.jar" />
		<pathelement path="${webinf.dir}/lib/commons-collections.jar" />
		<pathelement path="${webinf.dir}/lib/commons-dbcp.jar" />
		<pathelement path="${webinf.dir}/lib/commons-digester-1.8.jar" />
		<pathelement path="${webinf.dir}/lib/commons-discovery-0.4.jar" />
		<pathelement path="${webinf.dir}/lib/commons-fileupload.jar" />
		<pathelement path="${webinf.dir}/lib/commons-io.jar" />
		<pathelement path="${webinf.dir}/lib/commons-javaflow-20060411.jar" />
		<pathelement path="${webinf.dir}/lib/commons-lang.jar" />
		<pathelement path="${webinf.dir}/lib/commons-logging-1.1.1.jar" />
		<pathelement path="${webinf.dir}/lib/commons-pool.jar" />
		<pathelement path="${webinf.dir}/lib/commons-validator-1.3.1.jar" />
		<pathelement path="${webinf.dir}/lib/dom4j-1.6.1.jar" />
		<pathelement path="${webinf.dir}/lib/dwr.jar" />
		<pathelement path="${webinf.dir}/lib/EasySI-0.9.0.jar" />
		<pathelement path="${webinf.dir}/lib/ehcache-1.2.3.jar" />
		<pathelement path="${webinf.dir}/lib/fop.jar" />
		<pathelement path="${webinf.dir}/lib/ibatis-common-2.jar" />
		<pathelement path="${webinf.dir}/lib/ibatis-sqlmap-2.jar" />
		<pathelement path="${webinf.dir}/lib/iReport.jar" />
		<pathelement path="${webinf.dir}/lib/itext-1.3.1.jar" />
		<pathelement path="${webinf.dir}/lib/jakarta-oro-2.0.8.jar" />
		<pathelement path="${webinf.dir}/lib/jaxen-1.1-beta-7.jar" />
		<pathelement path="${webinf.dir}/lib/jazzy-core.jar" />
		<pathelement path="${webinf.dir}/lib/jsf-facelets.jar" />
		<pathelement path="${webinf.dir}/lib/jsf-impl.jar" />
		<pathelement path="${webinf.dir}/lib/jstl.jar" />
		<pathelement path="${webinf.dir}/lib/jta.jar" />
		<pathelement path="${webinf.dir}/lib/log4j-1.2.14.jar" />
		<pathelement path="${webinf.dir}/lib/mail.jar" />
		<pathelement path="${webinf.dir}/lib/myfaces-api-1.2.5.jar" />
		<pathelement path="${webinf.dir}/lib/myfaces-impl-1.2.5.jar" />
		<pathelement path="${webinf.dir}/lib/myfaces-shared-impl-3.0.5.jar" />
		<pathelement path="${webinf.dir}/lib/ojdbc14.jar" />
		<pathelement path="${webinf.dir}/lib/poi-3.0.1-FINAL-20070705.jar" />
		<pathelement path="${webinf.dir}/lib/quartz-all-1.6.1-RC1.jar" />
		<pathelement path="${webinf.dir}/lib/serializer-2.7.0.jar" />
		<pathelement path="${webinf.dir}/lib/spring-aop.jar" />
		<pathelement path="${webinf.dir}/lib/spring-beans.jar" />
		<pathelement path="${webinf.dir}/lib/spring-core.jar" />
		<pathelement path="${webinf.dir}/lib/spring-context.jar" />
		<pathelement path="${webinf.dir}/lib/spring-dao.jar" />
		<pathelement path="${webinf.dir}/lib/spring-ibatis.jar" />
		<pathelement path="${webinf.dir}/lib/spring-jdbc.jar" />
		<pathelement path="${webinf.dir}/lib/spring-support.jar" />
		<pathelement path="${webinf.dir}/lib/spring-web.jar" />
		<pathelement path="${webinf.dir}/lib/spring-webmvc.jar" />
		<pathelement path="${webinf.dir}/lib/standard.jar" />
		<pathelement path="${webinf.dir}/lib/tomahawk12-1.1.8.jar" />
		<pathelement path="${webinf.dir}/lib/xalan-2.7.0.jar" />
		<pathelement path="${webinf.dir}/lib/xercesImpl-2.7.1.jar" />
		<pathelement path="${webinf.dir}/lib/xml-apis-1.3.02.jar" />
		<pathelement path="${webinf.dir}/lib/xmlgraphics-commons-1.1.jar" />
		<pathelement path="${webinf.dir}/classes" />
		<pathelement path="${classpath.external}" />
		<pathelement path="${classpath}" />
	</path>

	<!-- define your folder for deployment -->
	<property name="deploy.dir" value="deploy" />

	<!-- Check timestamp on files -->
	<target name="prepare">
		<tstamp />
	</target>

	<!-- Copy any resource or configuration files -->
	<target name="resources">
		<copy todir="${webinf.dir}/classes" includeEmptyDirs="no">
			<fileset dir="src">
				<patternset>
					<include name="**/*.conf" />
					<include name="**/*.properties" />
					<include name="**/*.xml" />
				</patternset>
			</fileset>
		</copy>
	</target>

	<!-- Normal build of application -->
	<target name="compile" depends="prepare,resources">
		<javac srcdir="src" destdir="${webinf.dir}/classes" encoding="UTF-8">
			<classpath refid="compile.classpath" />
		</javac>
	</target>

	<!-- Remove classes directory for clean build -->
	<target name="clean" description="Prepare for clean build">
		<delete dir="${webinf.dir}/classes" />
		<mkdir dir="${webinf.dir}/classes" />
	</target>

	<!-- Build entire project -->
	<target name="build" depends="prepare,compile" />
	<target name="rebuild" depends="clean,prepare,compile" />

	<!-- Create binary distribution -->
	<target name="war" depends="build">
		<mkdir dir="${build.dir}" />
		<war basedir="${webroot.dir}" warfile="${build.dir}/${project.distname}.war"
			webxml="${webinf.dir}/web.xml">
			<exclude name="WEB-INF/${build.dir}/**" />
			<exclude name="WEB-INF/src/**" />
			<exclude name="WEB-INF/web.xml" />
		</war>
	</target>

	<target name="deploy" depends="war">
		<delete file="${deploy.dir}/${project.distname}.war" />
		<delete dir="${deploy.dir}/${project.distname}" />
		<copy file="${build.dir}/${project.distname}.war" todir="${deploy.dir}" />
	</target>

</project>

there are some supporting file exist for this build.xml these are –

————————- build.properties

classpath.external=external-lib/servlet-api.jar;external-lib/jsp-api.jar;

so we need to create another folder external-lib and put these 2 jar files.

Spring tutorial - build

Spring tutorial

to build this project use these stepts – open build.xml. click – window->show view -> outline . click the right button on rebuild select – Run As -> 1 Ant Build.

set a context configaration file at {Tomcat folder}/conf/Catalina/localhost. lest assume this file name is – simplespring.xml and its looks –

 

 

————-simplespring.xml

<?xml version="1.0" encoding="UTF-8"?>

<Context docBase="D:/workspace/simplespring/WebContent"
privileged="true" antiResourceLocking="false" antiJARLocking="false">
</Context>

if your eclipse has tomcat lunch plugs in so you can deploy from eclipse. click on as picture

Spring tutorial - run-tomcat

Spring tutorial

 

The output looks —

Spring tutorial - output

Spring tutorial

Download Spring tutorial

Click here to download this project.

Eclipse is running in a JRE, but a JDK is required

I got this problem –

“Eclipse is running in a JRE, but a JDK is required
Some Maven plugins may not work when importing projects or updating source folders.”

I put the java home as C:Program FilesJavajdk1.5.0_05

and path – C:Program FilesJavajdk1.5.0_05bin

but i got this problem. let me say how i solve it –

open eclipse.ini from eclipse folder. put this line

-vm
C:Program FilesJavajdk1.5.0_05binjavaw.exe

so the total file looks-

-showsplash
org.eclipse.platform
–launcher.XXMaxPermSize
256M
-framework
pluginsorg.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar
-vm
C:Program FilesJavajdk1.5.0_05binjavaw.exe
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms40m
-Xmx512m

2nd way solution –

create a bat file under the eclipse folder and put this line

eclipse.exe  -vm “C:Program FilesJavajdk1.5.0_05binjavaw.exe”

save this file.  use this file for opening eclipse.

Fast file copy and move by java

The following method does very fast file copy from one location to another location.

public boolean copyTo(File source, File destination) {
	try {
		FileInputStream fis = new FileInputStream(source);
		FileOutputStream fos = new FileOutputStream(destination);

		byte []buf = new byte[4096];
		int loaded = 0;
		while ((loaded = fis.read(buf)) > 0 ) {
			fos.write(buf, 0, loaded);
		}
		fis.close();
		fos.close();
	} catch (IOException e) {
		e.printStackTrace();
		return false;
	}
	return true;
}

Here i used 4096 byte buffer thats the key for fast copy.this value is optimize value from from different tested values.

The following method does very fast file move from one location to another location.

public boolean moveTo(File source, File destination) {
	boolean isRenamed;
	if(isPathExists(destination.getAbsolutePath())){
		destination.delete();
	}

	isRenamed = source.renameTo(destination);
	if(!isRenamed){
		copyTo(source,destination);
		source.delete();
	}
	return isRenamed;

}

public boolean isPathExists(String path){
	File location = new File(path);
	return location.exists();
}

The key of fast moving is the rename function.

remove from TinyMCE editor content value

I have described at my another post how to set up TinyMCE editor to any application. To get/set the content of editor use this function

V3 or later :

text = tinyMCE.activeEditor.getContent() // for get

tinyMCE.activeEditor.setContent(text) // for set

older version:

text = tinyMCE.getInstanceById(’txtNote’).getBody().innerHTML // get

tinyMCE.getInstanceById(’txtNote’).getBody().innerHTML = text //set

but current version has one problem that is every time it add <p> at beginning and </p> at ending. thats why i have created one method that return the exact content.

function tinyMCE_getContent(txtAreaId) { //strips html tags leaving plain text
var content = tinyMCE.get(txtAreaId).getContent();
var re = /(<([^>]+)>)/ig ; //strip all tags
plaintext = content.replace(re, “”);
return plaintext;
}

Show word count, remaining char, adding additional event’s function for TinyMCE editor

I have described at my another post how to set up TinyMCE editor to any application. charcount1I added some functions that shows the char remaining values in the initTinyMCE.js file. if you want to add some other function you can do that the same way.the function is –

setup :function(ed) {
/*ed.onClick.add(function(ed, e){ alert(‘click’);   });  */
ed.onBeforeSetContent.add(function(ed, o) {
// o.content = o.content.replace(/&lt;p&gt;/i, “”);
// o.content = o.content.replace(‘&lt;/p&gt;’, “”);
var strip = (tinyMCE.activeEditor.getContent()).replace(/(<([^>]+)>)/ig,””); ///remove <p> and </p>
var text = strip.split(‘ ‘).length + ” Words, ” +  strip.length + ” Characters. You have ” +(characterLimit-strip.length)+” Chracter remaining.”;
tinymce.DOM.setHTML(tinymce.DOM.get(tinyMCE.activeEditor.id + ‘_path_row’), text); //_path_row is used for showing text at status bar of editor
}
);

ed.onKeyUp.add(function(ed, e) {
var strip = (tinyMCE.activeEditor.getContent()).replace(/(<([^>]+)>)/ig,””);
var text = strip.split(‘ ‘).length + ” Words, ” +  strip.length + ” Characters. You have ” +(characterLimit-strip.length)+” Chracter remaining.”;
tinymce.DOM.setHTML(tinymce.DOM.get(tinyMCE.activeEditor.id + ‘_path_row’), text);
if(strip.length > characterLimit){
strip = strip.substring(0,characterLimit);
tinyMCE.execCommand(‘mceSetContent’,false,strip);
alert(“The length of your message is “+strip.length +” the max num of characters n allowed for this text Area is “+characterLimit);
}
});

}

This new version (3+) introduce tinyMCE.activeEditor.getContent() function for getting the content value. for old version use – tinyMCE.getInstanceById(‘txaMainline’).getBody().innerHTML

tinymce.DOM.setHTML(tinymce.DOM.get(tinyMCE.activeEditor.id + ‘_path_row’), text); is used for setting message at the editor status bar.

tinyMCE.execCommand(‘mceSetContent’,false,strip); is used for dynamically set the new value. when editor exceed the max value, the value from zero to max char is set to the content.

so the full text of initTinyMCE.js is

————— initTinyMCE.js
var characterLimit = 2000;
tinyMCE.init({
theme : “advanced”,
mode : “textareas”,
plugins : “searchreplace,print,paste”,
entity_encoding:”named”,
entities : “&quot;,34,&nbsp;,160,&amp;,38,&cent;,162,&euro;,8364,&pound;,163,&yen;,165,&copy;,169,&reg;,174,&trade;,8482,&permil;,8240,&lt;,60,&gt;,62,&le;,8804,&ge;,8805,&deg;,176,&minus;,8722”,
theme_advanced_buttons1 : “print,search,replace,separator,undo,redo”,
theme_advanced_buttons2: “”,
theme_advanced_buttons3 : “”,
theme_advanced_toolbar_location : “top”,
theme_advanced_toolbar_align : “left”,
theme_advanced_path_location : “bottom”,
extended_valid_elements : “a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]”,
theme_advanced_resize_horizontal : true,
theme_advanced_resizing : true,
nonbreaking_force_tab : false,
apply_source_formatting : false,
width : 400,
debug : false,
//handle_event_callback : “myHandleEvent”,
cleanup : true,
theme_advanced_path : false,
setup :function(ed) {
/*ed.onClick.add(function(ed, e){ alert(‘click’);   });  */
ed.onBeforeSetContent.add(function(ed, o) {
// o.content = o.content.replace(/&lt;p&gt;/i, “”);
// o.content = o.content.replace(‘&lt;/p&gt;’, “”);
var strip = (tinyMCE.activeEditor.getContent()).replace(/(<([^>]+)>)/ig,””);
var text = strip.split(‘ ‘).length + ” Words, ” +  strip.length + ” Characters. You have ” +(characterLimit-strip.length)+” Chracter remaining.”;
tinymce.DOM.setHTML(tinymce.DOM.get(tinyMCE.activeEditor.id + ‘_path_row’), text);
}
);

ed.onKeyUp.add(function(ed, e) {
var strip = (tinyMCE.activeEditor.getContent()).replace(/(<([^>]+)>)/ig,””);
var text = strip.split(‘ ‘).length + ” Words, ” +  strip.length + ” Characters. You have ” +(characterLimit-strip.length)+” Chracter remaining.”;
tinymce.DOM.setHTML(tinymce.DOM.get(tinyMCE.activeEditor.id + ‘_path_row’), text);
if(strip.length > characterLimit){
strip = strip.substring(0,characterLimit);
tinyMCE.execCommand(‘mceSetContent’,false,strip);
alert(“The length of your message is “+strip.length +” the max num of characters n allowed for this text Area is “+characterLimit);
}
});
}

});

Setup TinyMCE Editor

TinyMCE is a platform independent web based Javascript HTML WYSIWYG editor. I used here 3.2.1.1 version.lets see how add this editor to an application. first download it and unzipped it and put it in your web application’s js folder. so the folder structure looks –

folderstruc1

I used one configaration file that initialize the TinyMCE editor. this file name is initTinyMCE.js. put this folder into webappjstiny_mce folder.

——————–  initTinyMCE.js

tinyMCE.init({
theme : “advanced”,
mode : “textareas”,
plugins : “searchreplace,print,paste”,
entity_encoding:”named”,
entities : “&quot;,34,&nbsp;,160,&amp;,38,&cent;,162,&euro;,8364,&pound;,163,&yen;,165,&copy;,169,&reg;,174,&trade;,8482,&permil;,8240,&lt;,60,&gt;,62,&le;,8804,&ge;,8805,&deg;,176,&minus;,8722”,
theme_advanced_buttons1 : “print,search,replace,separator,undo,redo”,
theme_advanced_buttons2: “”,
theme_advanced_buttons3 : “”,
theme_advanced_toolbar_location : “top”,
theme_advanced_toolbar_align : “left”,
theme_advanced_path_location : “bottom”,
extended_valid_elements : “a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]”,
theme_advanced_resize_horizontal : true,
theme_advanced_resizing : true,
nonbreaking_force_tab : false,
apply_source_formatting : false,
width : 300,
debug : false,
//handle_event_callback : “myHandleEvent”,
cleanup : true,
theme_advanced_path : false,
});

here i used entities value so that it returns the actual character. there are so many plugins and button i used only some plugins of them. the ‘TinyMCE test.html’ looks like –

——————— TinyMCE Test.html

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html>
<head>
<meta content=”text/html; charset=ISO-8859-1″ http-equiv=”content-type”>
<title>TinyMCE Test</title>
</head>

<body>
<script type=”text/javascript” src=”js/tiny_mce/tiny_mce.js”></script>
<script type=”text/javascript” src=”js/tiny_mce/initTinyMCE.js”></script>

<table width=”100%”>
<tr>
<td align=”center”>
<textarea id=”txtNote1″ name=”txtNote1″ rows=”7″ cols=”10″ >
This is Text1.
</textarea>
</td>
</tr>
<tr>
<td>
&nbsp;
</td>
</tr>
<tr>
<td align=”center”>
<textarea id=”txtNote2″ name=”txtNote2″ rows=”7″ cols=”10″ >
This is Text2.
</textarea>
</td>
</tr>

</table>
</body>
</html>

the TinyMCE test.html page looks like –

tinymce-test1
Thanks

Image Reflection by javascript

I have made one reflection on image using neondragon’s javascript code.

Image reflection by javascript test

Image reflection by javascript test

here i gave the source code of javascript and html file also. for adding reflection you have to add just the class value. here i used class=”reflect”. if your image alreday has class vaule so, you can add reflection separated by space like class=”imageBox reflect”

<img  class=”reflect” style=”width: 384px; height: 276px;”  alt=”” title=”sweet baby” src=”babypic.jpg”>

if you want to change this class name just edit addReflections function156 line from reflection.js

var rimages = document.myGetElementsByClassName(‘reflect’);

i put the default height and opacity in the reflection.js file you can change it  or dynamically it can be change this way – class=”reflect rheight60 ropacity45″

—————————–  Reflection test.html

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<html>
<head>
<meta
content=”text/html; charset=ISO-8859-1″
http-equiv=”content-type”>
<title>Reflection test</title>
</head>
<body>

<script
type=”text/javascript” src=”reflection.js”></script>

<img class=”reflect” style=”width: 384px; height: 276px;” alt=”” title=”sweet baby” src=”babypic.jpg”>
</body>
</html>

Jasper iReport

Jasper iReport

Here I am describing on Jasper iReport and showing some important features of iReport. My another post has described how to create a report using Jasper iReport and how to execute that report by eclipse java project.

What is Jasper iReport

To see Jasper iReport home page, please click here. Yet, I have described another post on it. Here I am gonna show you how to create a report using Jasper iReport.

Jasper iReport : Create a report using iReport

Steps:

# set ClassPath: put your desire database driver jar file into the lib folder of iReport. you can do that Options->class path-> add jar

# Element:

-Static text is used Label and Text field is used for Value.

-Bar Code tools is used for print bar code. Jasper iReport - barcode make sure the font has to select that you are going to use for printing the barcode. to set font for bar code right click on bar code element and select properties and select BarCode tab and set the appropiate type that is font.

-SubReport: this is very important element of Jasper iReport. Jasper iReport - master-details it is mostly used, when you need a master details report. For example,  an itemlist according to category. A report that header portion shows the category details and also show all the items of that category. you can show all the categories group by one paritcular field among category’s details. that time you have to select that field as group by. like ‘Category A’ shows the details of category at the header and body show all the item of ‘Category A’. so this item list of ‘Category A’ is the sub report. for grouping of any category description fileds you have to select that filed group by. to do you have to select that field on right boutton click and select Group selected items.

– Field, Variable & Parameter: We can create variable which will only used as variable, denoted as $V{name}, that scope is the whole report. Field,denoted as $F{name}, that is used for showing a field in the report.Parameter ,denoted as $P{name}, that takes data from java class or master report to subreport.

-Connections/Data Sources: This is the way from where you feed the data to your report. Most common Connection is JDBC connection, you can used this connection for connecting your RDMS Database. Jasper iReport supports most of popular database like Oracle, MySql, MsSql, PostGresql, MSAccess… etc. You can also used XML data source that time you have to select the xml file as a data source. JavaBeans source is suppose your program class file List contains some data, such case report grabbed data from that list. Jasper iReport is really awesome tools. Hibernate Connection is HQL database connection. lets say how you do that, here I described how make your data source as XML datasource, click Data->Connections/DataSources->New->XML file data source -> Next ->Select the xml file. and choose Use the report Xpath, click the test button for confirmation of your datasource connection. if your xml file has master details data like

<Category name=”A” noOfItem=2>

<Item sku=”2322″ productName=”Poland Spring Water”/>

….

</Category>

lets set the datasource in the Report Query.

For masters, Category details, click Data->Report Query select Report Query tab, Query Language: XPath, Query: //Category click the Read Fields button then all the fields of Category will shows.

For sub-report, Item list,  open subreport & click Data->Report Query select Report Query Jasper iReport - reportquery1tab, Query Language: XPath, Query: /Category/Item click the Read Fields button then all the fields of Category will shows.

# Some common error:

1.if Jasper iReport shows casting error so it means it cant convert to desire type to actual type. for example – the text field type is Double and xml data is String such this case we can set the expression as: new Double($F{price}).

2.Boolean converting error. suppose reprot has Sex field and textfiled type is boolean but xml data is like that – sex=”0″ so it will generate error. if we want to show Male/Female or conditionally show a value, do follows this step. change the text file type is java.lang.String and edit Expression as

( $F{sex}.equals(“0”) ? “Male” : “Female”)

# Band: Jasper iReport breaks the report by several bands. we define the band as section or portion of whole report. this is as a good features. you can design as you want. if you want to show the title just set the title band hight value or not set the hieght value is zero, event we can show it conditionally if i used Print when expresstion value. if we used group by for a particular filed then we will get that Column Header and footer so that we can show the some summary information of the group. If there is no data so we can show this information using noData Band.

Another topic, if you want move more element, shift+click for selection and slow move use arrow , fast move use shift+arrow.

Jasper reports

Jasper reports

This time i am describing how make Jasper reports. Lets download iReport which is a tools of Jasper reports. To get more details on Jasper reports and documents please click here. Yet I described on Jasper reports at my another post. Here I am using iReport-3.0.0 zip file. This version i found mysql driver jar found in the lib folder but i did not see the oracle(ojdbc14.jar) driver jar file. If you would like to use oracle please put this jar file into the lib folder.

Jasper Reports step by step

# Create Connection:  Click Data-> Connections/Datasources. Click New button. select Database JDBC Connection -> Next Button ->now put your database information. i gave here one screen shot Jasper reports - dbconnection window

Pressing test button iReport shows the connection status. If you get any error like oracle/mysql class not found, make sure the lib folder contain your database driver jar file. If you get same excepton so go Options -> ClassPath -> Click add jar. now select the related database jar file. iReport supports multiple database so we can produce Jasper reports using different datasource.

# create a report using iReport:  File -> Report Wizard ->

template : none, connection: mysql, SQL Query : Select *from Person.

Next-> select all columns.  Next -> (do not select any group 1 value, if you want to show the report by any group you can select any column.)  Next -> Tabular Layout (ClassicT) Finish.

now you get one report. now you can change the report title. it looks

Jasper reports - mainscreen1Now you can test this Jasper reports by clicking  Build->Complie or Build->Execute(emptyconnection) or Build-> Execute (active connection). after compile the jaspar file will generatewhere the iReport.exe file is located. empty connection will show only report withoutdata butactive connection will show the data.

Since we want to show only first 30 id records, so we have create a parameter variable. this parameter determine how many record we want to show. to create a parameter click View -> Parameter then a window will come, here we can create variable which will only used as variable that scope is the whole report, field that is used for showing a field in the report and finally parameter that takes data from java class.  Click New button ->parameter name: p_id, class type: java.lang.Integer, use as Prompt uncheckd, default Value expression : new Integer(0) that means we assing a default value for this parameter. iReport always consider all the value as Object not primitive thats why i set write as new Integer(0) Paramete Description: paraeter ID . now click OK.

Now lets set the condition in the query. Click Data-> Report Query now put the following line – select *from person where id < $P{p_id}  here $P{p_id} is the parameter. Jasper reports - reportquery in iReport $F { name } is means field and $V{ name } is indicate variable. now click OK.

Now save the report as person.jrxml. if you complie this report you will get person.jasper file. let see the description of person table.

create table person ( id number(6), name varchar(20));

# Execute iReport From Java: I used eclipse to create one java program that execute Jasper reports.  Open eclipse, click New -> New Java Project  Project Name: SimpleiReprot , select Create new project in workspace, select default JRE, select Create separate folders now click Next -> FInish. now create 3 folders ( lib, report-out, report-src) under this project. The project folder structure looks this Jasper reports - folder_arch3

now put the person.jrxml and person.jaspar file into report-src folder. report-out folder will use for the pdf report file. Here I should mention jrxml file is xml formatted file and .jasper file is generated after compiling .jrxml file. Jasper engine using .jasper file to produce Jasper report at runtime. Now copy all the jar files from ireport’s lib folder into your project lib folder.  now refresh the eclipse project.now set the build path for this project. click the right button on the project and select properties and select the Java Build Path from the left side menu and click the Libraries Tab. it looks as

Jasper reports - eclipse project buildpath

Jasper reports – eclipse project buildpath

Now Add Jar button from the right side. Now select SimpleiReprot project and explore the lib folder and select all the jar files of lib folder. now click OK. Select Order and Exprot tab and Select All button from right side. Click OK.

I used 2 java files. DBConnector.java used for creating the database connection and SimpleiReport.java used for execute the Jasper reports.

Jasper reports  are generated by java class

DBConnector class

import java.sql.Connection;
import java.sql.DriverManager;
/*
 * Database connection class.
 * it return single instance of connection
 * author: rajib_info@yahoo.com
 */
public class DBConnector {
	public static Connection getConnection() {
		Connection connection = null;
		if (connection != null) {
			return connection;
		}
		try {
			Class.forName("org.gjt.mm.mysql.Driver").newInstance();
			connection = DriverManager.getConnection(
					"jdbc:mysql://localhost/development", "root", "");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return connection;
	}
}

SimpleiReport Class

import java.sql.Connection;
import java.util.HashMap;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;

/*
 * this class generates one pdf file from jaspar file. here i used one condition that filter
 * only first 30 records.
 * author: rajib_info@yahoo.com
 */
public class SimpleiReport {
	public static void main(String[] args) {
		// database connection
		Connection connection = null;
		String jasperFile = "./report-src/person.jasper";
		String pdfFile = "./report-out/personList.pdf";
		// params used for passing the parameter.
		HashMap&lt;String,Integer&gt; params = new HashMap&lt;String,Integer&gt;();
		params.put("p_id", 30);
		try {
			// get database connection.
			connection = DBConnector.getConnection();

			JasperPrint print = JasperFillManager.fillReport(jasperFile, params,
					connection);
			JRExporter exporter = new net.sf.jasperreports.engine.export.JRPdfExporter();
			exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,
					pdfFile);
			exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
			exporter.exportReport();
			System.out.println("Created file: " + pdfFile);
		} catch (JRException e) {
			e.printStackTrace();
			System.exit(1);
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
	}
}

If you want to use other database change the DBConnector class.Jasper reports - eclipse-mainClick the right button on the SimpleiReport file and select Run As ->  Java Application. Or you can set Run configaration from the Run->Run Configuration. this run configuration window you have to select the main class. the output console looks

——- output console

Created file: ./report-out/personList.pdf

and personList.pdf file will generate under the report-out folder. the pdf looks as

Jasper reports - output as pdf

Jasper reports – output as pdf

Please ask me if you have any problem or can give me any suggestion.

Thanks