javawaveblogs-20

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Wednesday, November 14, 2012

Camel-Jetty Step by Step using Netbeans IDE


Camel-Jetty Step by Step using Netbeans IDE
1. Create a Maven Java project using Netbeans IDE (Version used - 7.3 beta2)
  1. Go to New project wizard and Create a new maven java project
  2. Here for our sample the project is named as “MyHTTP”
  1. Click on finish
  2. now the IDE will create a Java Maven project for you with the recommended folder structure like below.
  1. Just check the POM.XML found inside the “ProjectFiles” folder. which will have the dependencies and plugin’s added automatically by the IDE. POM created for “MyHTTP” is shown below.
  1. Now its time to add Camel dependencies to our POM.XML file. add the following dependencies to your pom.xml file inside the dependencies tag.
        

       






















       
  1. Once the dependencies are added just clean and build your project. so that maven will download the required jar files listed in the dependencies tag to your project from the central repository. and also will pack the required JAR files to your “\MyHTTP\target\” path with name “MyHTTP-1.0-SNAPSHOT.jar”.
  2. Now in your project you can see a main class created with the name “App.java”.
  3. its time to edit the java class App.java and add the following code to it.
package com.mm.myhttp;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
/**
 *
 * @author Muthu
 */
public class App {
    public static void main(String[] args) {
        DefaultCamelContext camelContext = new DefaultCamelContext();
        try {
            camelContext.addRoutes(new RouteBuilder() {
                @Override
                public void configure() throws Exception {
                    from("jetty:http://0.0.0.0/myapp/myservice/?sessionSupport=true")
                            .process(new Processor() {
                        @Override
                        public void process(Exchange exchng) throws Exception {
                            System.out.println("Inside process exchange");
                            String body = exchng.getIn().getBody(String.class);
                            // this is the way to access HttpServletRequest
                            HttpServletRequest req =
                                    exchng.getIn().getBody(HttpServletRequest.class);
                            // send a html response back to client
                            exchng
                                    .getOut()
                                    .setBody(""
                                    + "Simple Demo for Camel-Jetty component"
                                    + "
");
                        }
                    });
                }
            });
            camelContext.start();
        } catch (Exception ex) {
            Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

  1. the important part of the code is “from("jetty:http://0.0.0.0/myapp/myservice/?sessionSupport=true")” from route which starts jetty server and listens to the http url mentioned in the from route.
  2. then the route flows to the process where a html response is set to the body and returned to the client.
  3. To test this application, just run the Java Maven project with App.java as the main class.
  1. In the Output window you can see the http service running at port 80. and our component uses Jetty-7.5.4 to run the service.
  1. Now hit the url(http://localhost/myapp/myservice/) using your browser and you should be able to see the html response back from the service.

Sunday, May 3, 2009

Convert a String to Lower Case in Java

Here this post will show you how to convert a string to lower case in Java.


String actualValue = "JAVA WAVE";

String lowerCase = actualValue.toLowerCase();

Monday, March 9, 2009

Generate a unique identifier with java.util.UUID

Java SE 5 has introduced the java.util.UUID class to easily generate Universally Unique Identifier (UUID)


import java.util.UUID;

/**
* This class is used to generate UUID and return it as a String object
*
* @author dhanago
*
*/
public class GenerateUUID
{
/**
* method to return UUID as a String object
*
* @return
*/
public static String getUUID()
{
return UUID.randomUUID().toString();
}
}

Tuesday, March 3, 2009

Java utility to read from resource bundle or properties file



/**
* dataSource.properties is loaded to a resource bundle.
*/
public static ResourceBundle resourceBundle = ResourceBundle.getBundle(
"sample.prop.health");

/**
* This method will return the value of the property from the resource
* bundle.
*
* @param key
* property key
* @return property value
*/
public static String getProperty(String key)
{
String value = null;
try
{
value = resourceBundle.getString(key);
}
catch (MissingResourceException missingResourceException)
{
Logger.getLogger(Utility.class.getName()).
log(Level.SEVERE,
"Resource Bundle not found",
missingResourceException);
}
return value;
}

Java method to format the current date to yyyy-MM-dd using SimpleDateFormat.


/**
* This method will format the current date to yyyy-MM-dd.
* @return
* current date as String.
*/
public static String formatedCurrentDate()
{
String toDate = new Date().toString();
SimpleDateFormat formatter = new SimpleDateFormat(
"EEE MMM yyyy hh:mm:ss zzz");
Date date = formatter.parse(toDate,
new ParsePosition(0));

toDate = new SimpleDateFormat("yyyy-MM-dd").format(date);
return toDate;
}

Java method to return a File object from the file path specified


/**
* This method will return a file from the path specified.
*
* @param path
* path of the file name.
* @param fileName
* Name of the file.
* @return File object
*/
public static File readFileFromPath(String path, String fileName)
{
String fileNameWithPath = null;
if (path.endsWith("/"))
{
fileNameWithPath = path + fileName;
}
else
{
fileNameWithPath = path + "/" + fileName;
}
File file = new File(fileNameWithPath);

return file;
}

Reading file as String in Java


/** This method will read a file as String
* @param filePath
* @return file as String
* @throws java.io.IOException
*/
public static String readFileAsString(String filePath)
throws java.io.IOException
{
StringBuffer fileData = new StringBuffer(1000);
BufferedReader reader = new BufferedReader(new FileReader(filePath));
char[] buf = new char[1024];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1)
{
String readData = String.valueOf(buf,
0,
numRead);
fileData.append(readData);
buf = new char[1024];
}
reader.close();
return fileData.toString();
}

Java method to replace every occurences of a string within another string


/**
* This method will replace every occurences of a string within another
* string.
*
* @param target
* is the original string
* @param from
* is the string to be replaced
* @param to
* is the string which will used to replace
* @return
* changed new string
*/
public static String replace(String target, String from, String to)
{
int start = target.indexOf(from);
if (start == -1)
{
return target;
}
int fromLength = from.length();
char[] targetChars = target.toCharArray();
StringBuffer buffer = new StringBuffer();
int copyFrom = 0;
while (start != -1)
{
buffer.append(targetChars,
copyFrom,
start - copyFrom);
buffer.append(to);
copyFrom = start + fromLength;
start = target.indexOf(from,
copyFrom);
}
buffer.append(targetChars,
copyFrom,
targetChars.length - copyFrom);
return buffer.toString();
}

Tuesday, December 2, 2008

Converting Java String to double

The following code will convert Java String into double data type.


package com.javaWave.blogSpot;

public class String2double {

/**
* @param args
*/
public static void main(String[] args) {
// String myString = "javaWave"; // do this if you want an exception

String myString = "100.00";

try {
double convertedValue =
Double.valueOf(myString.trim()).doubleValue();
System.out.println("convertedValue = " + convertedValue);
} catch (NumberFormatException nfe) {
System.out.println("NumberFormatException: "
+ nfe.getMessage());
}

}

}

Saturday, July 26, 2008

Core Java Notes- Part I

Designing a class:
Think about objects created from the class.
· Things the object knows about itself-> instance variable
· Things the object does-> methods.
Note: think of instance as another way of saying object.
Difference between a class and a object:
Note: a class is not an object
->class is used to construct an object
A class is an blueprint for an object
-> tells the virtual machine how to make an object of the particular type.
Example: An object is like one entry in your address book.
The two uses of main:
1. To test your real class.
2. To launch/ start your java application.
The Heap
Each time an object is created in java, it goes into an area of memory known as the Heap. All objects created live on the heap.
Note: The java heap is actually called as Garbage collectable heap.
Java manages the memory for you. When the JVM can see that an object can never be used again, that object becomes eligible for garbage collection. And if you are running low on memory, the garbage collector will run, throw out the unreachable objects, and free up the space, so that the space can be reused.


Marking a method as public and static:
Marking a method as public and static makes it behave much like a ‘global’.
Note: Any code in any class of your application can access a public static method.
If you mark a variable as public, static and final, you have essentially made a globally available constant.
Variables
2 flavours of variables,
· Primitive
· Reference
Primitive: Hold fundamental values including integers, Booleans and floating point numbers.
Object references: hold, well, references to objects.
Two declare a variable you must follow two rules:
1. variables must have a type.
2. variables must have a name.
Example:
int count
here,
int ==> Type, and
count ==> Name.
Note: A variable is just a container that holds something.


You can assign a value to a variable in one of several ways including:
> Type a literal value after the equal sign, eg., x=12, isgod=true; etc.,
> assign the value of one variable to another (x=y).
> use an expression combining the two. Eg.(x=y+43).
Note: You need a name and a type for your variables
int size = 32
here ,
int ==> Type,
size ==> Name, and
32 ==> Literal

Safe naming rules for a class method or variable:
· it must start with a letter, underscore(_), or dollar sign($).you can’t start a name with a number.
· After the first character you can use the number as well.
· It can be anything you like, subject to those two rules, just so long as it isn’t one of java’s reserved words.

Reserved words Table:
Non-Primitive Variables/Objects:
There is actually no such thing as an object variables
There is only an object reference variable.
An object reference variable holds bits that representation way to access an object. And the JVM knows how to use the reference to get to the object.
Note: Objects live in one place-the garbage collectible heap!
Arrays: Arrays are always objects, whether they are declared to hold primitives or object references.
Note: once you have declared an array, you can’t put anything in it except things that are of the declared array type.
Bullet Points:
Variables come in two flavours,
1. Primitive
2. Reference
Variables must always be declared with a name and a type.
A primitive variable value is the bits representing a way to get to an object on the heap.
A reference variable is like a remote control using the dot operator (.) on a reference variable is like pressing a button on the remote control to access a method or instance variable.
A reference variable has a value of null when it is not referencing any object.
An array is always an object, even if the array is declared to hold primitives. There is no such thing as a primitive array, only an array that holds primitives
Note: Java is pass-by-value (i.e) pass-by-copy.
Bullet Points:
· Classes define what an object knows and what an object does.
· Things an object knows are its instance variables(state).
· Things an object does are its methods(behaviour).
· Methods can use instance variables so that objects of the same type can behave differently.
· A method can have parameters, which means you can pass one or more values into the method.
· The number and type of values you pass in must match the order and type of the parameters declared by the method.
· Values passed in and out of methods can be implicitly promoted to a larger type or explicitly cast to a smaller type.
· The value you pass as an argument to a method can be a literal value (2, ‘c’,etc) or a variable of the declared parameter type (for example, x where x is an int variable).
· A method must declare a return type. A void return type means the method doesn’t return type.
Encapsulation ==> Hide the data:
Rule of thumb: Mark your instance variables private and provide public getters and setters for access control.
The difference between instance and local variable.
instance variable are declared inside a class but not within a method.
local variables are declared within a method.
local variables must be initialized before use.
Note: Local variables do not get a default value! The compiler complains if you try to use a local variable before the variable is initialized.
Note: Method parameters are virtually the same as local variables. But method parameters will never get a compiler error telling you that a parameter variable might not have been initialized.

Monday, April 14, 2008

Quartz Job Scheduler -- Part II (Example, Simple Trigger)

In this example we will see how to implement a Simple scheduler with the help of Quartz Framework.

Our application will just print Hello World on console after specified time.

For implementing the scheduler using quartz we need two classes.
1. which will implement org.quartz.Job interface, and the other
2. the scheduler class which will start the scheduler.

Now we will see the code which will implement Job interface:

package com.MyQuartz.simple;

import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

/**
*
* @author dhanago
*/
public class HelloJob implements Job {

public void execute(JobExecutionContext jobExecutionContext)
throws JobExecutionException {
System.out.println("Hello World -- Executed on : " + new Date());
}
}

Here,
execute() --> is an overridden method. When ever Job interface is implemented its execute() of method should be overridden. Note that any component you want to schedule should implement Job interface.

JobExecutionContext --> is passed as an parameter to the execute() method. this provides the job instance which provides the job instance with information about its run-time environment. From this we will get the job detail information and also some important information regarding its triggers etc.,

Now we will see the code which will start the scheduler:

package com.MyQuartz.simple;

import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdSchedulerFactory;

/**
*
* @author dhanago
*/
public class StartScheduler {

public void startScheduler()
throws SchedulerException {
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
JobDetail jobDetail = new JobDetail(
"MyJob", scheduler.DEFAULT_GROUP, HelloJob.class);
SimpleTrigger simpleTrigger = new SimpleTrigger(
"MyTrigger", scheduler.DEFAULT_GROUP, new Date(),
null, SimpleTrigger.REPEAT_INDEFINITELY, 60L * 1000L);
scheduler.scheduleJob(jobDetail, simpleTrigger);
}

public static void main(String args[]) {

StartScheduler startScheduler = new StartScheduler();
try {
startScheduler.startScheduler();
}
catch (SchedulerException ex) {
Logger.getLogger(StartScheduler.class.getName()).
log(Level.SEVERE, null, ex);
}
}
}

Here,

StdSchedulerFactory(): A Class StdSchedulerFactory is a class and it is implementation of SchedulerFactory interface. Here it just using for create an instance of SchedulerFactory instance.

Scheduler: Scheduler interface is the main interface (API) to this functionality. It provides some simple operations like scheduling jobs, unscheduling jobs, starting/stopping/pausing the scheduler.

start(): This method is used to starts the Scheduler's threads that fire Triggers. At the first time when we create the Scheduler it is in "stand-by" mode, and will not fire triggers. The scheduler can also be send back into stand-by mode by invoking the standby() method.

JobDetail(String name, String group, Class jobclass): The JobDetail object is created at the time the Job is added to scheduler. It contains various property settings like job name, group name and job class name. It can be used to store state information for a given instance of job class.

SimpleTrigger(String name, String group, Date startTime, Date endTime, int repeatCount, long repeatInterval): Trigger objects are used to firing the execution of jobs. When you want to schedule the job, instantiate the trigger and set the properties to provide the scheduling.

DEFAULT_GROUP: It is a constant, specified that Job and Trigger instances are belongs to which group..

REPEAT_INDEFINITELY: It is a constant used to indicate the 'repeat count' of the trigger is indefinite.

scheduleJob(JobDetail jobDetail, SimpleTrigger simpleTrigger): This method is used to add the JobDetail to the Scheduler, and associate the Trigger with it.

OutPut:


init:
deps-jar:
compile-single:
run-single:
log4j:WARN No appenders could be found for logger (org.quartz.simpl.SimpleThreadPool).
log4j:WARN Please initialize the log4j system properly.
Hello World -- Executed on : Mon Apr 14 22:52:25 IST 2008
Hello World -- Executed on : Mon Apr 14 22:53:25 IST 2008
Hello World -- Executed on : Mon Apr 14 22:54:25 IST 2008
Hello World -- Executed on : Mon Apr 14 22:55:25 IST 2008

Monday, April 7, 2008

Quartz Job Scheduler -- Part 1 (Setting up development project in Netbeans 6.1 beta)

Setting up development project in Netbeans 6.1 beta

Step 1 :Run Netbeans IDE and create a New Java project opening the new project creation wizard like below.
Step 2: Click on the Next button and enter the project name. Here i am giving the name as "MyQuartz". Click on finish. (see the below figure)
Step 3: Download Quartz from the location --> http://www.opensymphony.com/quartz/download.action . Once downloaded extract the archive to a location.
Step 4: The below table explains the files inside the extracted archive.

Files/Directory Purpose
quartz-all-.jar Quartz library includes the core Quartz components and all optional packages. If you are using this library then no other quartz-*.jars need to include.
quartz-.jar core Quartz library.
quartz-jboss-.jar optional JBoss Quartz extensions such as
the Quartz startup MBean, QuartzService.
quartz-oracle-.jar optional Oracle specific Quartz extensions such as
the OracleDelegate
quartz-weblogic-.jar optional WebLogic specific Quartz extensions such
as the WebLogicDelegate
build.xml an "ANT" build file, for building Quartz.
docs root directory of all documentation
docs/wikidocs the main documentation for Quartz. Start with the "index.html"
docs/dbTables sql scripts for creating Quartz database tables in a variety of different databases.
src/java/org/quartz the main package of the Quartz project, containing the 'public' (client-side) API for the scheduler
src/java/org/quartz/core a package containing the 'private' (server-side)
components of Quartz.
src/java/org/quartz/simpl this package contains simple implementations of
Quartz support modules (JobStores, ThreadPools,
Loggers, etc.) that have no dependencies on external (third-party) products.
src/java/org/quartz/impl this package contains implementations of Quartz
support modules (JobStores, ThreadPools, Loggers, etc.) that may have dependencies on external (third-party) products - but may be more robust.
src/java/org/quartz/utils this package contains some utility/helper components used through-out the main Quartz components.
src/examples/org/quartz this directory contains some examples usage of Quartz.
webapp this directory contains a simple web-app for managing
Quartz schedulers.
lib this directory contains all third-party libraries that are needed to use all of the features of Quartz.
Step 5: Open Add JAR/Folder wizard in netbeans like shown below.

Step 6: Add "quartz-all-1.6.0.jar" and all other jars found inside "lib" folder. See the below figure to see the added jars to the project.

Step 7: Now the Development Environment is ready.

Thursday, March 20, 2008

Collection of Jars in One place

From the below URL we can find the collection of Java related jars in one place.

http://www.java2s.com/Code/Jar/CatalogJar.htm

Highlights of NetBeans 6.1

Highlights of NetBeans 6.1 include:

* JavaScript support such as semantic highlighting, code completion, type analysis, quick fixes, semantic checks and refactoring;

* Performance enhancements including faster startup and code completion;

* Spring framework support with features such as configuration file support, code completion and hyperlinks to speed navigation;

* New MySQL support in the Database Explorer to make it easier to create, launch and view MySQL databases;

* Significant enhancements to the Ruby/JRuby support, including a new Ruby platform manager, support for the latest version of Rails and new hints and quick fixes in the editor;

* Beta support for the ClearCase version control system - made available as a plugin from the Update Center.

download from --> http://dlc.sun.com.edgesuite.net/netbeans/6.1/beta/

Monday, December 3, 2007

Spring - Part I

Here is the simple example to start up with spring,

To write a simple spring application we need one interface, one implementation of that interface and a test client to test the implementation. Apart form that we also need a configuration XML file.

One interface --> Hello.java
One implementation --> HelloImpl.java
One Test Client --> HelloClient.java
One Spring XML File --> Hello.xml (Should be in the classpath).

Now let us see the interface Hello.java.


package com.javawave.spring.cli;

/**
* @author dhanago
*/
public interface Hello
{
/**
* This method will return the salutation for the name passed as input
* param to it.
*
* @param name
* @return
*/
public String sayHello( String name );
}


The above interface has only one method to say hello. This method has to be implemented in the implementation class "HelloImpl.java"


package com.javawave.spring.cli;

/**
* @author dhanago
*/
public class HelloImpl implements Hello
{

private String greet;

/**
* zero-arg constructor
*/
public HelloImpl()
{

}

/**
* @param greet
*/
public HelloImpl( String greet )
{
this.greet = greet;
}

/*
* (non-Javadoc)
*
* @see com.javawave.spring.cli.Hello#sayHello(java.lang.String)
*/
public String sayHello( String name )
{

return this.greet + name;
}

/**
* @param greet the greet to set
*/
public void setGreet( String greet )
{
this.greet = greet;
}

}

The Impl class has a property called greet. This also has a setter method "setGreet" to set the value for this property.

Now let us see the spring xml. This XML file will be used for creating the objects in spring framework. This XML is also called wiring xml. Through this XML we will set the greet property of the HelloImpl class.

Hello.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="hello"
class="com.javawave.spring.cli.HelloImpl">
<property name="greet">
<value>Good Morning!...</value>
</property>
</bean>
</beans>

Here in the XML you can see the tag called bean which will map to the bean what you are using in the application. It has an attribute called "id" and a attribute called "class". The "class" attribute maps to the HelloImpl.java in our case. The property tag inside the bean tag maps to the property inside the bean class. Here in our case it is the "greet" property. The value for the property is given in the value element inside the property element. This is the value passed to the bean's property "greet" . This is how spring does the dependency injection (DI). Here what you are doing is injecting dependency through setter method. This is also called Setter Injection.

Now we will see the client application "HelloClient.java" to test the "HelloImpl.java".

/**
*
*/
package com.javawave.spring.cli;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

/**
* @author dhanago
*/
public class HelloClient
{

/**
* @param args
*/
public static void main( String[] args )
{
try
{
System.out.println( "Inside main of HelloClient.." );
Resource resource = new ClassPathResource(
"com/javawave/spring/cli/Hello.xml" );
BeanFactory factory = new XmlBeanFactory( resource );
Hello hello = (Hello) factory.getBean( "hello" );
String result = hello.sayHello( "Man" );
System.out.println( result );
}
catch (Exception e)
{
System.out.println( "Exception/Error:" + e.toString() );
}
}
}

This client application uses ClassPathResource to load the resource. In our case Hello.xml and it creates the factory via XmlBeanFactory. factory class has getBean method which will return a object. Here we get Hello object. So from that we can call sayHello method as shown in the above code and get the result.

The Jars used for this application is:
spring.jar
commons-logging.jar

The Output is shown below:

Inside main of HelloClient..
Good Morning!...Man
Dec 3, 2007 1:59:01 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [com/javawave/spring/cli/Hello.xml]

Friday, November 30, 2007

Comparing two Value Objects in Java

In Java comparing two value object is not straight forward. Here we will see how we can compare two value objects in Java.

For that first we will create a value object called "MyValueObject". This value object contains two properties. 1) firstName 2) lastName. Both the properties are of type string.

In the same class we also have a overridden method which does the comparison for us. This method "public boolean equals(Object obj)" takes the properties and compare them individually. if the properties values are all equal then it returns true or it will return false. By doing this our test class will just call the equals method on the object to make sure if the objects are equal or not.

Code is listed below.

/*
*/
package com.blogspot.javawave;

/**
*
* @author dhanago
*/
public class MyValueObject
{

private String firstName;
private String lastName;

/**
* This constructor is used to set the two properties values in the class.
*
* @param firstName
* @param lastName
*/
public MyValueObject(String firstName,
String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}

@Override
public boolean equals(Object obj)
{
boolean isEqual = false;
if (this.getClass() == obj.getClass())
{
MyValueObject myValueObject = (MyValueObject) obj;
if ((myValueObject.firstName).equals(this.firstName) &&
(myValueObject.lastName).equals(this.lastName))
{
isEqual = true;
}
}

return isEqual;
}
}

Test class is given below:

/*
*/
package com.blogspot.javawave;

/**
*This class is used to test compare the value object.
*
* @author dhanago
*/
public class TestCompareValueObject
{

/**
* This is the main method used to test compare the value object.
* @param arg
*/
public static void main(String[] arg)
{
MyValueObject obj1 = new MyValueObject("Muthu", "Kumar");
MyValueObject obj2 = new MyValueObject("Muthu", "Kumar");

if (obj1.equals(obj2))
{
System.out.println("Both the objects are equal");
}
else
{
System.out.println("Both the objects are not equal");
}
}
}

This one of the way we can easily compare the value objects in Java

Saturday, October 13, 2007

Java Excel API

Where to get the jexcelapi?


Get the API download form --> http://jexcelapi.sourceforge.net/

What is jexcelapi ?

A Java API to read, write, and modify Excel spreadsheets.

Now java developers can read Excel spreadsheets, modify them with a convenient and

simple API, and write the changes to any output stream (e.g. disk, HTTP, database, or

any socket).


Because it is Java, the API can be invoked from within a servlet, thus giving access to

Excel spreadsheets over internet and intranet web applications.


Features of jexcelapi

Reads data from Excel 95, 97, 2000, XP, and 2003 workbooks
Reads and writes formulas (Excel 97 and later only)
Generates spreadsheets in Excel 2000 format Supports font, number and date formatting Supports shading, bordering, and coloring of cells Modifies existing worksheets Is internationalized, enabling processing in almost any locale, country, language, or character encoding (formulas are currently only supported in English, French, Spanish, and German, but more can be added if translated) Supports copying of charts Supports insertion and copying of images into spreadsheets Supports logging with Jakarta Commons Logging, log4j, JDK 1.4 Logger, etc ...and much more.

Technical notes ==> http://www.andykhan.com/jexcelapi/technotes.html

JExcelApi JavaDoc ==> http://jexcelapi.sourceforge.net/resources/javadocs/index.html



Pre-Requirements:
  • Should be knowing basic concepts of Java.
  • Should know how to set class path to use third party Api's.


Now we will see how to read a spread sheet using this API:


First of all we will create a spread sheet like the one below and store it in our local folder.

I am saving this file in "D:testmyFile.xls"



To read the spread sheet content using jxl Api, first we have to create an object called
Workbook. Once you create the Workbook then you will get access to individual sheets.
Note that these sheets are Zero indexed.
So you have to use some thing like workbook.getSheet(0);

Once you get the sheet then you can easily get the cells and their content as string.
If you want it is also possible to get the data with out changing the type as it is.

See the sample code below (SpreadsheetReader.java).

package com.jxl.dhanago;

import java.io.File;
import java.io.IOException;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

/**
* This Java program is used to read the spread sheet and print it in
* console output.
*
* @author dhanago
*/
public class SpreadsheetReader
{

/**
* This method is used to read a spread sheet and print it in console.
*
* @param xlsPath
*/
public void readSpreadSheet( String xlsPath )
{
try
{
/*
* To read the spread sheet , first we have to create a workbook
* object like one shown below.
*/
Workbook workbook = Workbook.getWorkbook( new File( xlsPath ) );
/*
* then get the sheet index 0. Note the index starts with 0.
*/
Sheet sheet = workbook.getSheet( 0 );
/*
* get the cell form the sheet object like below.
*/
Cell cell00 = sheet.getCell( 0, 0 );
Cell cell01 = sheet.getCell( 0, 1 );
Cell cell02 = sheet.getCell( 0, 2 );

/*
* now we will display the cell values as string in console output.
*/
System.out.println( "Cell00 value: " + cell00.getContents() );
System.out.println( "Cell01 value: " + cell01.getContents() );
System.out.println( "Cell02 value: " + cell02.getContents() );
// free up memory
workbook.close();
}
catch (BiffException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}

/**
* This is the main executable method used to test the spread sheet
* reader.
*
* @param args
*/
public static void main( String[] args )
{
SpreadsheetReader readSpreadsheet = new SpreadsheetReader();
String xlsPath = "D:\test\myFile.xls";
readSpreadsheet.readSpreadSheet( xlsPath );
}
}

OutPut for the above code:

Cell00 value: Name
Cell01 value: Muthukumar Dhanagopal
Cell02 value: Krish

The above code displays the cell values as string. How to get the same
data type and display them with out converting them to string. Is that
possible using this API?

Yes, it is possible.
Here is the code which does the same for you.
It checks the cell type for LABEL, NUMBER or DATE and then gets the value from
the cell type cast the value to that particular data type and displays it on the console.

package com.jxl.dhanago;

import java.io.File;
import java.io.IOException;

import jxl.Cell;
import jxl.CellType;
import jxl.DateCell;
import jxl.LabelCell;
import jxl.NumberCell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

/**
* This java program is used to get and display the xls data according to
* the type.
*
* @author dhanago
*/
public class ReadXLWithExactDataType
{

/**
* This method is used to display the xls data with exact type.
*
* @param xlsPath
*/
public void readDataWithType( String xlsPath )
{
try
{
/*
* To read the spread sheet , first we have to create a workbook
* object like one shown below.
*/
Workbook workbook = Workbook.getWorkbook( new File( xlsPath ) );
/*
* then get the sheet index 0. Note the index starts with 0.
*/
Sheet sheet = workbook.getSheet( 0 );
/*
* get the cell form the sheet object like below.
*/
Cell cell00 = sheet.getCell( 0, 0 );

if (cell00.getType() == CellType.LABEL)
{
System.out.println( "Type LABEL" );
LabelCell labelCell = (LabelCell) cell00;
System.out.println( "Label Cell: " + labelCell.getString() );
}
else if (cell00.getType() == CellType.NUMBER)
{
System.out.println( "Type NUMBER" );
NumberCell numberCell = (NumberCell) cell00;
System.out.println( "Number Cell: " + numberCell.getValue() );
}
else if (cell00.getType() == CellType.DATE)
{
System.out.println( "Type DATE" );
DateCell dateCell = (DateCell) cell00;
System.out.println( "Date Cell: " + dateCell.getDate() );
}
else
{
System.out.println( "Type not supported." );
}

/*
* now we will display the cell values as string in console output.
*/
System.out.println( "Cell00 value: " + cell00.getContents() );
// free up memory
workbook.close();
}
catch (BiffException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}

/**
* This is the main executable method used to test the spread sheet
* reader.
*
* @param args
*/
public static void main( String[] args )
{
ReadXLWithExactDataType readXL = new ReadXLWithExactDataType();
String xlsPath = "D:\test\myFile.xls";
readXL.readDataWithType( xlsPath );
}

}

The Output for the above code is:
Type LABEL
Label Cell: Name
Cell00 value: Name


Wednesday, October 10, 2007

Rule Engine - Drools

What is a Rule Engine?

Artificial Intelligence (A.I.) is a very broad research area that focuses on "Making computers think like people" and includes disciplines such as Neural Networks, Genetic Algorithms, Decision Trees, Frame Systems and Expert Systems. Knowledge representation is the area of A.I. concerned with how knowledge is represented and manipulated. Expert Systems use Knowledge representation to facilitate the codification of knowledge into a knowledge base which can be used for reasoning - i.e. we can process data with this knowledge base to infer conclusions. Expert Systems are also known as Knowledge-based Systems and Knowledge-based Expert Systems and are considered 'applied artificial intelligence'. The process of developing with an Expert System is Knowledge Engineering. EMYCIN was one of the first "shells" for an Expert System, which was created from the MYCIN medical diagnosis Expert System. Where-as early Expert Systems had their logic hard coded, "shells" separated the logic from the system, providing an easy to use environment for user input. Drools is a Rule Engine that uses the Rule Based approached to implement an Expert System and is more correctly classified as a Production Rule System.

The term "Production Rule" originates from formal grammar - where it is described as "an abstract structure that describes a formal language precisely, i.e., a set of rules that mathematically delineates a (usually infinite) set of finite-length strings over a (usually finite) alphabet" (wikipedia).

For more information visit the following URL
https://hudson.jboss.org/hudson/job/drools/lastSuccessfulBuild/artifact/trunk/target/docs/html/ch02.html



JBoss server in Eclipse

Defining JBoss server in Eclipse:

Step 1 : Open Eclipse WTP all in one pack in a new work space.

Step 2 : Change the perspective to J2EE Perspective if it is not currently in J2EE Perspective.

Step 3 : Once the Perspective is changed to J2EE, you can see a tab called Servers in the bottom right panel along with Problems, Tasks, Properties.

Step 4 : If the Servers tab is not found. Go to Eclipse menu : Windows > Show view and click on Servers, so that Server tab will be displayed.

Step 5 : Go to Servers tab window and right click the mouse. You will get a pop up menu called "New".

Step 6 : Clicking on the New menu you will get one more pop up called "Server". Click on it.

Step 7 : Now you will get Define New Server Wizard.

Step 8 : In the wizard there are options to define many servers. One among them is JBoss. Click on JBoss and Expand the tree.

Step 9 : Select JBoss v 4.0 and click next.

Step 10 : Now give the JDK directory and JBoss home directory. Click Next.

Step 11 : Now the wizard will show you the default Address, port, etc., Leave it as it is and click on Next.

Step 12 : Click on finish.

Step 13 : Now you can see the JBoss server listed in the Servers window and the status is Sopped.

Step 14 : JBoss server is now defined in Eclipse now and its ready to use from with in Eclipse IDE.

diggthis