iReport Pie Chart Report

March 17, 2009

This blog i will show how to make a pie chart report. here i used very simple report. I have one table called category it has different categoryno with categroy name. Each category has subcategory. I want to show how many categories are there by pie chart.  Category table struc and data link will give you the table structure and some sample data. I used MySql database for this report.

  • Create New document from iReport. use this band value title = 30, columnHeader = 15, detail = 15 and summary = 300 and others = 0.
  • Add Query:     select category “Cat No”, subcat_name “category Name”, count(category) total from category
    group by category order by 1
  • Add 3 fields – Cat No, Category Name, Total to Detail band.    detail-band
  • Click the char button and select the Pie 3D. I put its width is 268 and height is 203.   ui2
  • right click on chart and select cart properties. select cart data tab, select the Details tab. and put the value as follows -  for Key Expression = $F{category Name} ,  Value Expression = $F{total},  Label Expression = $F{category Name}
  • click close.
  • b4 execute you must select your database connection. now click Execute with data connection. the output file will looks like as follows

output-pie-report


Allow number only in TextField by javascript

March 12, 2009

this example allow only number character in you text field.

—- JavaScript code

function numeralsOnly(thisComp,e,isDecimal) {
var key;
var keychar;
if (window.event) {
key = window.event.keyCode;
}
else if (e) {
key = e.which;
}
else {
return true;
}

// check double period/decimal/point
if (  ((thisComp.value).indexOf(‘.’) > -1) && key == 46){
alert(“Double period is not allow for this field.”);
return false;
}

var str = ‘0123456789′;
str +=isDecimal ? ‘.’:”;
keychar = String.fromCharCode(key);
if ((key==null) || (key==0) || (key==8) ||  (key==9) || (key==13) || (key==27) ) {
return true;
}
else if (((str).indexOf(keychar) > -1)) {
return true;
}

alert(“Enter numerals only in this field.”);
thisComp.focus();
//thisComp.select();
return false;
}

——- html code

<input type=”text” id=”txtSkuPrice”  onkeypress=”return numeralsOnly(this,event,true);”/>

numeralsOnly(this,event,true) -> for Double number use true and for integer number use false.


Get Number value from Currency format String

March 12, 2009

some time we need get the actual number value from a well formated string. this example shows how we get the exact number value.

Lets consider we have a string its value like

$1,221.22

So the actual number is 1221.22 after eliminate the Dollar sign and comma. The javascript code is -

function getNumberFromCurrencyString(currencyString){
var result = currencyString.replace(‘$’,”); //remove dollar
result = result.replace(/\,/g,”); //remove comma
return result;
}


Complete Spring IBatis project

January 24, 2009

here i am describing a very simple Spring project with IBatis and Display tag. let me describe the working environment. my another blog 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;

Eclipse create new project

Eclipse create new project

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-

output1


Spring project step by step

January 17, 2009

here i describe a very simple Spring project. let me describe the working environment. my another blog shows how to set up your environment.

Eclipse 3.4: Ganymede;

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

Tomcat: 5.5

FireFox: 3

Create a new project in Eclipse;

Eclipse create new project

Eclipse create new project

set project name

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. this class looks

——————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.

————- 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 infromation.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} – %m\n

————————- 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

eclipse build path

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.

to build this project builduse 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

run-tomcat

The output looks —

output

the source code is located at -

http://code.google.com/p/simplespringproject/


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

January 16, 2009

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 Files\Java\jdk1.5.0_05

and path – C:\Program Files\Java\jdk1.5.0_05\bin

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

open eclipse.ini from eclipse folder. put this line

-vm
C:\Program Files\Java\jdk1.5.0_05\bin\javaw.exe

so the total file looks-

-showsplash
org.eclipse.platform
–launcher.XXMaxPermSize
256M
-framework
plugins\org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar
-vm
C:\Program Files\Java\jdk1.5.0_05\bin\javaw.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 Files\Java\jdk1.5.0_05\bin\javaw.exe”

save this file.  use this file for opening eclipse.


Fast file copy and move by java

January 11, 2009

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 <p> </p> from TinyMCE editor content value

January 11, 2009

I have described at my another blog 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

January 11, 2009

I have described at my another blog 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

January 10, 2009

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 \webapp\js\tiny_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

Rajib