Wednesday, September 26, 2012

generate report from java


package com.test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;

import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.EngineConstants;
import org.eclipse.birt.report.engine.api.HTMLRenderContext;
import org.eclipse.birt.report.engine.api.HTMLRenderOption;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;
import org.eclipse.birt.report.engine.api.ReportEngine;

public class BirtTest {

     public static void main(String[] args) {
          //Variables used to control BIRT Engine instance
          EngineConfig conf = null;
          ReportEngine eng = null;
          IReportRunnable design = null;
          IRunAndRenderTask task = null;
          HTMLRenderContext renderContext = null;
          HashMap contextMap = null;
          HTMLRenderOption options = null;
          //Now, setup the BIRT engine configuration. The Engine Home is hardcoded
          //here, this is probably better set in an environment variable or in
          //a configuration file. No other options need to be set
          conf = new EngineConfig();
          conf.setEngineHome("C:/eclipse-birt/eclipse/birt-runtime-4_2_0/ReportEngine");
       
          //Create new Report engine based off of the configuration
          eng = new ReportEngine( conf );
       
          //With our new engine, lets try to open the report design
          try
          {
               design = eng.openReportDesign("C:/sanker/birt/birt-test/new_report.rptdesign");
          }
          catch (Exception e)
          {
               System.err.println("An error occured during the opening of the report file!");
               e.printStackTrace();
               System.exit(-1);
          }
       
          //With the file open, create the Run and Render task to run the report
          task = eng.createRunAndRenderTask(design);
       
          //Set Render context to handle url and image locataions, and apply to the
          //task
          renderContext = new HTMLRenderContext();
          renderContext.setImageDirectory("image");
          contextMap = new HashMap();
          contextMap.put( EngineConstants.APPCONTEXT_HTML_RENDER_CONTEXT, renderContext );
          task.setAppContext( contextMap );
          ResultSet rs = getResultSet(); // a function that executes the query and returns resultset
          task.setParameterValue("myResultSet", rs);
          //This will set the output file location, the format to rener to, and
          //apply to the task
          options = new HTMLRenderOption();
          options.setOutputFileName("C:/sanker/birt/output/output.html");
          options.setOutputFormat("html");
          task.setRenderOption(options);
       
          try
          {
               task.run();
          }
          catch (Exception e)
          {
               e.printStackTrace();
          }
       
          eng.destroy();
     }
   
     static ResultSet getResultSet() {
    ResultSet rs = null;
    try {
Connection con = getConnection();
Statement stmt = con.createStatement();
stmt.execute("select id, name from A");
rs = stmt.getResultSet();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
    return rs;
     }
   
     static Connection getConnection() {
    try {
Class.forName("oracle.jdbc.driver.OracleDriver");
return DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","sanker","password");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
    return null;
     }
}


/*******************************************************/
package com.test;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.eclipse.birt.report.engine.api.script.IReportContext;
import org.eclipse.birt.report.engine.api.script.IUpdatableDataSetRow;
import org.eclipse.birt.report.engine.api.script.ScriptException;
import org.eclipse.birt.report.engine.api.script.eventadapter.ScriptedDataSetEventAdapter;
import org.eclipse.birt.report.engine.api.script.instance.IDataSetInstance;

public class MyScriptedSetAdapter extends ScriptedDataSetEventAdapter {

ResultSet resultSet;

@Override
public boolean fetch(IDataSetInstance dataSet, IUpdatableDataSetRow row)
throws ScriptException {
try {
if(resultSet.isAfterLast())
return false;// to indicate that there are no more rows left to process
row.setColumnValue("ID", resultSet.getInt(1));
row.setColumnValue("NAME", resultSet.getString(2));
resultSet.next();
return true; // to indicate that more rows to follow
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}

@Override
public void open(IDataSetInstance dataSet) throws ScriptException {
super.open(dataSet);
try {
if(resultSet != null)
resultSet.next();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

@Override
public void beforeOpen(IDataSetInstance dataSet, IReportContext reportContext) throws ScriptException {
super.beforeOpen(dataSet, reportContext);
//retrieve the parameter myResultSet set from the java class in Step 1
System.out.println("myResultSet="+reportContext.getParameterValue("myResultSet"));
resultSet = (ResultSet)reportContext.getParameterValue("myResultSet");
}
}

Saturday, March 3, 2012

Find missing number in a list in java


Problem :- 

         Assume that there is a list of numbers that has numbers from 1 to n. Out of the list, one number is missing. Find the missing number from the list.

Solution :-

       The solution (written in java) with least time complexity is to use BitSet and set bit in the bitset for each corresponding number in the list. The first bit that is not set will be the missing number in the list.

void findMissingNum(int[] ar) {
if(ar != null) {
BitSet bs = new BitSet(ar.length);
for(int no : ar) {
bs.set(no);
}
System.out.println("Missing number=" + bs.nextClearBit(1));
}
}

Saturday, August 1, 2009

AOP - Simple Example

Aspect Oriented Programming (AOP) promotes separation of cross-cutting concerns like logging, transaction management, security, etc from the components in a software system. The components may be performing these system services apart from the core logic they are entrusted with. These concerns tend to cut across multiple components in a system, hence called cross-cutting concerns of a system. These concerns introduce levels of complexity to your code as -
  • systemwide duplicated code for implementing these system concerns, necessitating multiple code changes if any of the concerns change
  • components are burdened with more code than that which deals with their core functionality
AOP modularizes these services and applies them declaratively to the required components in the system. Hence, components become more specific and cohesive. It covers the core application with layers of functionality without the application even knowing it exists.

Let us get a feel of AOP through a simple example.
A class People who sings praiseworthy songs about a class King. Let us see how it works without AOP.



Here, each time the King goes to a War, it must stop and tell his People to Praise him before he can start fighting the War. Similary, after the War, the King must remember to tell the People again to Praise him about his achievements.

Let us now introduce the concept of Aspect here and also, a configuration file praise.xml.


The functionality of the Aspect is defined in the bean referred to by the ref attribute. The aspect is made up of pointcuts and advice. Here, we declare a pointcut which is triggered by the execution of a startWar() method. Advices are provided in 2 forms here - before to call singBefore() method of People before the pointcut and after to call singAfter() method of People after the pointcut.

This simplifies the code in class King as follows:




reference: spring in action

Sunday, July 26, 2009

Simple usage of Spring

Let us look into the concept of Dependency Injection through a small example:-

Here we are trying to print out a string "Hello World" using Spring's techniques. The interface HelloService defines the contract for the service class:-

package com.hello;
public interface HelloService {
void sayHello();
}

HelloServiceImpl implements the above interface as follows:

package com.hello;
public class HelloServiceImpl implements HelloService {
private String hello;
public HelloServiceImpl() {}
public HelloServiceImpl(String hello) {
this.hello = hello;
}
public void sayHello() {
System.out.println(hello);
}
public void setHello(String hello) {
this.hello = hello;
}
}

The property "hello" in this class can be set either through the constructor or the setter method. Now, let us write the Spring Configuration file, named here as hello.xml







Here, the bean named "helloService" of class "HelloServiceImpl" has a property "hello", which is injected with a value of "Hello World" using the setter injection. In effect, this does the following:-

HelloServiceImpl helloService = new HelloServiceImpl();
helloService.setHello("Hello World");

If we were opting for constructor injection, then the tag in the xml file would have to be replaced with -




In effect, this does the following:-

HelloServiceImpl helloService = new HelloServiceImpl("Hello World");


Now, let us write a main class for this entire application, HelloMain.java -

package com.hello;
//add imports and handle exceptions as and when necessary
public class HelloMain {
public static void main (String[] args) {
BeanFactory factory = new XmlBeanFactory(
new FileSystemResource("hello.xml"));

HelloService helloService = (HelloService) factory.getBean("helloService");

helloService.sayHello();
}
}

Here, the BeanFactory is the Spring container. The configuration file "hello.xml" is loaded, "getBean()" retrieves a reference to the bean with id "helloService" and this reference is used to print "Hello World" to the screen.

This example depicts Dependency Injection or Inversion of Control in Spring clearly. Typically, in almost all applications, each object would be responsible for obtaining its own references to the objects it collaborates with, which leads to highly-coupled and hard-to-test code. But here, objects are given their dependencies at creation time by the xml file (in the above example) or dependencies are injected into objects, hence enabling loose-coupling. Here, the interface helps the class to remain loose-coupled at all times.




reference :- Spring in Action

Friday, July 24, 2009

Spring - What is it?

Java was in the process of maturing during the year of 1996. Many rich and dynamic web applications were being developed. But, people started to realize the shortcomings of Java Applets. This paved the way for the invention of Java Beans - a software component model for Java. They were primarily used for building user interface widgets and seemed too simple to be able to do any "real" work. Later in the year if 1998, Enterprise Java Beans (EJB) extended the normal beans to the server side, even though losing its simplicity. Its complexity reduced its popularity and easiness. This is where Aspect Oriented Programming (AOP) and Dependency Injection (DI) found spot to flourish. These methodologies furnish the POJOs (Plain Old Java Object) with a mirror image of an EJB using a declarative programming model, but completly avoiding all the complexities. Better late than never !!!

Leading the development based on lightweight POJOs is the Spring Framework.

Spring is an open source framework, created by Rod Johnson benefitting from its features such as simplicity, testability and loose coupling. Basically, it is a lightweight dependency injection and aspect-oriented container and framework. Breaking it down into simpler terms:-

  • Lightweight -> in size (distributable JAR less than 2.5MB) and overhead of processing
  • Dependency Injection -> loose coupling by means of objects not creating or looking up for dependent objects on their own, instead giving their dependencies during instantiation without being asked by them
  • Aspect-oriented -> separating business logic from system services (logging, security, transaction management) where objects deal with only things they are supposed to do
  • Container -> contains and controls the lifecycle and configuration of application objects
  • Framework -> configures and composes complex applications from simpler components with the help from an XML configuration file
Let us have a peep into the Spring Modules:-
  • Core -> provides the fundamental functionality of Spring, onbased on the BeanFactory
  • ApplicationContext -> builds on top of core and makes Spring a framework, adding support for internationalization messages, application life-cycle events, email, JNDI access, remoting, scheduling, validation, etc.
  • AOP -> decoupling application-wide concerns from objects to which they are applied
  • JDBC abstraction (DAO) -> abstracts away the boilerplate code of JDBC keeping the database code clean and simple, also building meaningful exceptions over the normal SQL Exceptions
  • ORM -> supports various ORM frameworks like Hibernate, JPA, JDO, iBatis, etc in addition to JDBC
  • JMX -> helps expose application's beans as Java Management Extensions beans supporting monitoring and reconfiguring a running application
  • JCA (Java EE Connector API) -> integrates Java applications with various information systems like databases and mainframes, all scattered in disparate servers and platforms
  • MVC Framework -> separates user interface from application logic, also supporting existing MVCs in market like Struts, JSF, etc
  • Portlet MVC -> aggregating several bits of functionality on a single web page providing a view into several applications at once
  • Web -> support classes for MVC applications
  • Remoting -> access applications over the network, expose objects' functionality as remote objects, all considering the objects as simple POJOs
  • JMS -> guarantees message delivery throught JMS message queues and topics and helps create message-driven POJOs capable of consuming asynchronous messages

Thursday, July 9, 2009

EasyMock IllegalStateException: missing behavior definition for last method call

When you encounter this error, please check whether you tried to use the mock object before invoking EasyMock.replay() method. I did that encountered the IllegalStateException and spent quite some time until I figured out the reason.

I had written the following expect() ;

EasyMock.expect(testObj.getTestMethod()).andReturn("testValue");

the culprit was the following statement which I had put before the expect().

System.out.println("testObj="+testObj.getTestMethod());

Hope it helps someone!

JUnit with EasyMock

Ever wondered how could you test your classes without waiting for your colleague to complete his classes.. I think EasyMock is one of the answers..

EasyMock helps to create mock objects by passing an interface as argument. It is very helpful when you have complex web application that involves lot of custom objects and you want to test a particular class which is dependent on ten other classes.

It has 2 simple steps to follow.

1. Create mock objects
2. Set the expected values in mock object so that the methods of the object return the same values

It is very easy to use. (Steps below:-)

1. Add easymock libraries
2. Create JUnit test case
3. Create mock objects using EasyMock.createStrictMock(MyInterface.class)
4. Set expected values using EasyMock.expect(myObj.myMethod()).andReturn("ReturnvaluefromMyMethod").
This statement means that when myMethod() is invoked, return the value "ReturnvaluefromMyMethod". In essence, whichever method you are planning to invoke later, set the values expected to be returned from the method.
5. call EasyMock.replay(myObj);

Our mock objects are ready to use.

Tips:-
1. Do not call any methods of the mock object until you call replay(). Otherwise it will throw an IllegalStateException at that point.

2. If your interface contains getter/setter methods, instruct the getter() [not the setter()] with the expected return values. In general, we are used to invoke the setter method with the value to be set and use the getter methods to retrieve the value.


Hope it helps!