Monday, August 4, 2008

Using openoffice with Java

I am back again . Few days before I was working on Openoffice and how we can take the help of its rich libraries to manipulate Microsoft Office and OpenOffice files i.e. Word, Excel, PowerPoint etc.

So here is my experience and its results. You have to download openoffice from the link defined below

http://download.openoffice.org/index.html

and also you have to download openoffice sdk from the following link

http://download.openoffice.org/2.4.0/sdk.html

you need the following libraries from the installed openoffice path. The files we needed are described as follows with their location

a) officebean.jar (%OpenOfficeHome%/program/classes)
b) unoloader.jar (%OpenOfficeHome%/program/classes)
c) juh.jar (%OpenOfficeHome%/program/classes)
d) jurt.jar (%OpenOfficeHome%/program/classes)
e) query.jar (%OpenOfficeHome%/program/classes)
f) report.jar (%OpenOfficeHome%/program/classes)
g) ridl.jar (%OpenOfficeHome%/program/classes)
h) unoil.jar (%OpenOfficeHome%/program/classes)

I am trying to explain by manipulating spreadsheet with openoffice api.

public class OpenOfficeTest {

private void useConnection() throws Exception{

try {

// get the remote office component context
xRemoteContext = com.sun.star.comp.helper.Bootstrap.bootstrap();

System.out.println("Connected to a running office ...");


xRemoteServiceManager = xRemoteContext.getServiceManager();

}


catch( Exception e) {


e.printStackTrace();

System.exit(1);
}

try {

// get the Desktop, we need its XComponentLoader interface to load a new document

Object desktop = xRemoteServiceManager.createInstanceWithContext(
"com.sun.star.frame.Desktop", xRemoteContext);

// query the XComponentLoader interface from the desktop

XComponentLoader xComponentLoader = (XComponentLoader)UnoRuntime.queryInterface(

XComponentLoader.class, desktop);

// create empty array of PropertyValue structs, needed for loadComponentFromURL
PropertyValue[] loadProps = new PropertyValue[0];

// load new calc file
XComponent xSpreadsheetComponent = xComponentLoader.loadComponentFromURL(
"private:factory/scalc", "_blank", 0, loadProps);

// query its XSpreadsheetDocument interface, we want to use getSheets()
XSpreadsheetDocument xSpreadsheetDocument = (XSpreadsheetDocument)UnoRuntime.queryInterface(
XSpreadsheetDocument.class, xSpreadsheetComponent);

// use getSheets to get spreadsheets container
XSpreadsheets xSpreadsheets = xSpreadsheetDocument.getSheets();

//insert new sheet at position 0 and get it by name, then query its XSpreadsheet interface
xSpreadsheets.insertNewByName("Book.xls", (short)0);
Object sheet = xSpreadsheets.getByName("Book.xls");
XSpreadsheet xSpreadsheet = (XSpreadsheet)UnoRuntime.queryInterface(
XSpreadsheet.class, sheet);

// use XSpreadsheet interface to get the cell A1 at position 0,0 and enter 21 as value
XCell xCell = xSpreadsheet.getCellByPosition(0, 0);
xCell.setValue(21);

// enter another value into the cell A2 at position 0,1
xCell = xSpreadsheet.getCellByPosition(0, 1);
xCell.setValue(21);

// sum up the two cells
xCell = xSpreadsheet.getCellByPosition(0, 2);

xCell.setFormula("=sum(A1:A2)");


// we want to access the cell property CellStyle, so query the cell's XPropertySet interface
XPropertySet xCellProps = (XPropertySet)UnoRuntime.queryInterface(
XPropertySet.class, xCell);

// assign the cell style "Result" to our formula, which is available out of the box
xCellProps.setPropertyValue("CellStyle", "Result");

// we want to make our new sheet the current sheet, so we need to ask the model
// for the controller: first query the XModel interface from our spreadsheet component
XModel xSpreadsheetModel = (XModel)UnoRuntime.queryInterface(
XModel.class, xSpreadsheetComponent);

// then get the current controller from the model
XController xSpreadsheetController = xSpreadsheetModel.getCurrentController();

// get the XSpreadsheetView interface from the controller, we want to call its method
// setActiveSheet
XSpreadsheetView xSpreadsheetView = (XSpreadsheetView)UnoRuntime.queryInterface(
XSpreadsheetView.class, xSpreadsheetController);

// make our newly inserted sheet the active sheet using setActiveSheet
xSpreadsheetView.setActiveSheet(xSpreadsheet);
}
catch( com.sun.star.lang.DisposedException e ) { //works from Patch 1
xRemoteContext = null;
throw e;
}
}

public static void main(String[] args) {
try{
OpenOfficeTest test = new OpenOfficeTest ();
test.useConnection();
}catch(Exception e){

}
}

I will post some more examples regarding OpenOffice API to manipulate Microsoft Office product

Cheers


PDF Forms by using iText

Hi All,

We have one situation. we want to read pdf forms. I am posting how we can read and manipulate pdf form with iText, an open source library.

I am sure it will help you all to avoid using commercial products like JPadel etc.

Find the example as follows and enjoy the usage of iText


PdfReader reader = new PdfReader("C:/MyForm.pdf");

AcroFields form = reader.getAcroFields();

HashMap fields = form.getFields();

String key;

for (Iterator i = fields.keySet().iterator(); i.hasNext(); ) {

key = (String) i.next();

System.out.print(key + ": ");

switch(form.getFieldType(key)) {


case AcroFields.FIELD_TYPE_CHECKBOX:
System.out.println("Checkbox");
break;
case AcroFields.FIELD_TYPE_COMBO:
System.out.println("Combobox");
break;
case AcroFields.FIELD_TYPE_LIST:
System.out.println("List");
break;
case AcroFields.FIELD_TYPE_NONE:

System.out.println("None");
break;

case AcroFields.FIELD_TYPE_PUSHBUTTON:
System.out.println("Pushbutton");
break;

case AcroFields.FIELD_TYPE_RADIOBUTTON:
System.out.println("Radiobutton");
break;

case AcroFields.FIELD_TYPE_SIGNATURE:
System.out.println("Signature");
break;

case AcroFields.FIELD_TYPE_TEXT:
System.out.println("Text");
System.out.println(" Value : "+form.getField(key));
break;

default:
System.out.println("?");
}

}

cheers and enjoy iText

Java Reflection -- Myths and Reality

I thought to share my experience with you all people about java Reflection. People have many issues about using reflection some people consider that Reflection creates the performance overhead, some feel that we need more code to write to achieve the desired result by using reflection etc etc. These are some myths which are around the development community.

Today I thought to explain the reality apart from myths and 1000 people benchmark testing applications. So lets start exploring Reflection...

question is what is the Reflection : it is an API and the best way to reference and object class without any compilation error because in all other methods we have to import the class physically at compile time.

The reflection class may be Unknown at compile time or Dynamically loaded at runtime

Reflection allows programs to interrogate an object at runtime without knowing the object's class.

there are four myths about Reflection around the world and that are :

1) Reflection is only useful for JavaBeans technology based components
2) Reflection is too complex for use in general purpose applications
3) Reflection reduces performance of applications
4) Reflection cannot be used with 100% pure Java certification standard

What I found from hard core developers around the world and by reading many articles and books and also from my own experiences the answers of each and every questions is as follows

for point 1) Reflection is only useful for JavaBeans technology based components

The first answer is NO because people have wrong understanding of Reflection as they believe that it can be only used with JavaBeans technology based components as some other pure object oriented languages are also using Reflection such as Smalltalk and Eiffel.

Rather it has more benitis like Reflection helps to keep software robust and make application more Flexible, Extensible and Pluggable.

for point 2) Reflection is too complex for use in general purpose applications

The first answer for this point is also NO. According to me Reflection makes the code simpler and helps us in removing useless nested if/else statements. The skills required to use Reflection can easily be mastered. Reflection can significantly reduce the footprint of an application and imporve reusability.

for point 3) Reflection reduces performance of applications

heheh again the abrupt answer is NO and the statement is False, Reflection can actually increase the performance of code according to my experience and my experience is also proven by eclipse RCP engine as it is using Reflection heavily. Lets see how it can improve the performance. the main factor which can contribute to increase the performance are :

a) By Reducing and removing expensive conditional code
b) By Simplifying source code and design
c) and also can greatly expand the capabilities of the application

for point 4) Reflection cannot be used with 100% pure Java certification standard

According to the experts the answer should be NO for this point also as this statement is also proven false. There are only few restrictions :
"the program must limit invocations to classes that are part of the program or part of the JRE"

Now I will explain you that why we have to use Reflection :). Reflection solves the problems withing object-oriented design :

• Flexibility
• Extensibility
• Pluggability


Reflection solves the problems caused by ...

• The static nature of the class hierarchy
• The complexities of strong typing


Reflection also can benefits the Design Patterns and can decouple the object further and by doing this can simplify and reduce maintenance.

The best Design Pattern used with the Reflection are the Observer
and Command.

This topic and discussion is not meant to write the Reflection apis :) and explaining the Reflection in detail. for that purpose we can write one more post in forum :D hehe to get the number one position :D hehehe...

The main purpose for this post was to remove some myths which is spread in the community and again re-spreading by the other people who never used the reflection.

Cheers and enjoy using reflection

Saturday, August 2, 2008

creating jBPM workflow programmatically

Hello readers of my blog. The purpose of this blog is to provide the best and creative ways of using the workflow engines. I am working on jBPM for the last 2 to 3 years. All examples and work available is creating the workflow by using jBPM graph designer plug-in.

We have some issues that we want to create the workflow on the fly based upon some specific criteria. When I started to look for the examples which could solve my problems, I found there is no such example present on the web so far. Now I wish to publish my work on jBPM workflow. I hope it will give the readers and developers better look and they can get the deep knowledge of jBPM APIs.

Now I will write step by step how to create workflow by using jBPM API.

Step 1: Create ProcessDefinition

ProcessDefinition processDefinition = new ProcessDefinition("process");

Step2: Create StartState
StartState startState = new StartState("start-state");

Step3: Add StartState to processDefinition

processDefinition .addNode(startState);

the flexiblity in this way of creating the workflow is we can easily add all nodes at any time to the processDefinition. When we have to create the transitions which will define the flow of the processes.

Step4: Creating Nodes (you can create the Nodes based upon some rules i.e TaskNode etc)

Node node = new Node("nodeName");

Step 5: Now Create the Events, Actions and Delegation. Delegation is more important as it defines the actionHandler associated with this Action which defines the Events.

Event event = new Event(Event.EVENTTYPE_NODE_ENTER);

Delegation delegation =
new Delegation("package.ActionHander");

Action action = new Action(delegation);

event.addAction(action);

node.addEvent(event);


Add this created Node to the processDefinition as described in Step3

Now we can create as many nodes and associate them with processDefinition. When we got any logic that we want to create parallel process or want to combine parallel processing to single processing we need Fork and Join.

In jBPM Fork and Join can be created by using the following code

Fork fork = new Fork("forkName");

and

Join join = new Join("joinName");

The most important in jBPM workflow is the transition. Workflow creater should know the importance of the transition and know how to control and properly use Transitions. Fork can have single arriving transition and multiple leaving transition while Join can have multiple arriving transition and only one leaving transition.

Step 6: Creating Transition

Transition transiton = new Transition();

transiton.setName(transitionName);

transiton.setFrom(previousNode);

transiton.setTo(nextNode);

Step 7: Associating the transition to the originating node

originatingNode.addLeavingTransition(transiton);

Step 8:
Creating the EndState. This state will instruct the jBPM engine that this workflow will end at this point.

EndState endState = new EndState("end-state");

Adding the endState to the processDefinition as described in Step3.

Step8:
Deploying the processDefinition to the jBPM database

JbpmConfiguration configuration = JbpmConfiguration.getInstance();

JbpmContext context = configuration.createJbpmContext();

context.getGraphSession().saveProcessDefinition("processDefinition ");

context.close();

Step 9: The most important thing is to do properly setpup jbpm-config.xml file

add transaction attribute to the service tag of jbpm-context. otherwise processDefinition cannot be deployed properly.

name option is "tx" and factory value is "org.jbpm.tx.TxServiceFactory"


Step 10: Enjoy jBPM and explore the beauty of jBPM programmatically.

Hopefully I am able to explain the world about workflow with jBPM.

Cheers

Anees-ur-Rehman
Chief Solution Architect

Infopro Solutions Sdn Bhd
ph: 0060-17-6960742