Thursday 31 July 2008

working with finances in java

When writing a Java application that is dealing with finances, it is very wise to use BigDecimal class instead of float or double.

This is Sun’s official advice:

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/datatypes.html


BigDecimal class provides methods and properties for hendling numbers in very precise manner.

Let’s see how to use this class:

First of all, create BigDecimal object. For example:

BigDecimal result = new BigDecimal(0.00);


And let’s say we have two values to substract or multiply:

1234.123456789776 and 0.3888377362


In order to do this , java.math.BigDecimal has



BigDecimal add(BigDecimal augend) method for substracting numbers.

or

BigDecimal multiply(BigDecimal multiplicand) method for multiplying numbers


These, offcourse, are not the only method in this class. There are also other methods for mathematical operations. This was just taken for example…

Code:

result = (new BigDecimal(1234.123456789776)).add(new BigDecimal(0.3888377362));


To display the result, you can use the BigDecimal class's toString() method:

System.out.println(result.toString());


and the result would be:

1234.512294525975900694181319749986869283020496368408203125

Or you can display result using, for example BigDecimal class's doublevalue() method:

System.out.println(Double.toString(result.doubleValue()));

Which gives result:

1234.512294525976


Great thing about this class is ability to complitely control how some number needs to be rounded. In order to do this, we can use BigDecimal class's setScale() method.

In order to use it, you just need to specify how many decimal places you would like your number to have, and the logic of rounding it.


There are a lot ways to round it:


ROUND_CEILING
ROUND_DOWN
ROUND_FLOOR
ROUND_HALF_DOWN
ROUND_HALF_EVEN
ROUND_HALF_UP


and many more…

For example, if we want to round our result to 2 decimal places, and to round it with ROUND_HALF_UP method, call:

result = result.setScale(2,BigDecimal.ROUND_HALF_UP);


and then, the result will be:

1234.51

for

System.out.println(result.toString());

and for

System.out.println(Double.toString(result.doubleValue()));

I never used this class before, untill today, when I noticed some wrong results while working on some software that needed very presice results…

BigDecimal class solved my problems…

Friday 25 July 2008

Quick tip 3: How to get List index in oracle forms builder

As i can see, many people have this problem. They have a hard time to get index of an item selected in some list.
As I can tell, there isn’t a function like GET_LIST_INDEX() or something like that.
I had this problem myself few times before, and then I wrote this PL/SQL function:

FUNCTION getListIndex (LIST IN VARCHAR2, VAL IN VARCHAR2) RETURN INTEGER IS
BEGIN
IF To_Number(Get_List_Element_Count(LIST))>0 THEN
FOR i IN 1..To_Number(Get_List_Element_Count(LIST)) LOOP
IF Get_List_Element_Value(LIST,i) = VAL THEN
Return i;
END IF;
END LOOP;
ELSE
RETURN -1;
END IF;
END;


And to find out which index you selected by clicking on the list, call
getListIndex(‘blockX.listX , :blockX.listX);
This will return selected index, and -1 if the list is empty…
For example, to delete something from some list you just cdouble-clicked, call:

-- on WHEN-MOUSE-DOUBLECLICK trigger:
...
DELETE_LIST_ELEMENT('block3.list4',getListIndex('block3.list4',:block3.list4));
...

Some of the SAX Parser issues I came up to...

1) SAX Parser issue No 1 : Sax won’t release the file

When I need to parse XML files in JAVA projects, I use SAX parser.
I like using SAX. It’s quite easy.
Of course, there’s nothing like parsing in PHP ( at least for me ) but SAX can also be interesting…
In one of my projects , I had this situation:
I had a thread that needed to parse N .xml documents , and in case of SaxException or IOException my thread needed to delete or move the current file to some new location.
I was using SAX parser.
It looks really easy thing to do, and it is! well, if you know and do some extra things…
Probably everyone who had this kind of situation very soon noticed that SAX parser won’t delete or move this file!
Why is that so?
Well , I don’t know if this is bug,or it just could have been done better, but it seems that XMLReader used when creating parser does not “release” that document when Exception occurs!
I cannot believe this is the way SAX works, but seems like it is!
What we need to do in a case of Exception? We need to somehow explicitly close this file.
And how can this be done?

I recommend you not to use

void parse(String systemId) method when parsing.

Use

void parse(InputSource input) instead!

This way, you can always explicitly close this InputSource when you need to “release” parsing document when Exception occurs.

Here is the example:

Let’s make some class called XMLDocumentParser that implements ContentHandler:

public class XmlDocumentParser implements ContentHandler

and let’s make some method doParse() that returns some wanted object that represents parsed document data:

If we make it like this:


public class XmlDocumentParser implements ContentHandler
{

private String XML_FILE; // holds the name of the document
WantedObject wantedobject; // object that holds xml data

public WantedObject doParse() throws IOException, SAXException
{
XMLReader parser =new SAXParser();
parser.setContentHandler(this);
parser.parse(XML_FILE);
return wantedobject;
}

}

we won’t be able to control it when Exception occurs.

But, if we use void parse(InputSource input) instead:
public WantedObject doParse() throws IOException, SAXException
{
stream = new BufferedInputStream(new FileInputStream(XML_FILE));
XMLReader parser = new SAXParser();
parser.setContentHandler(this);
parser.parse(new InputSource(stream));
return wantedobject;
}



and somewhere in the caller-method, catch Exception, close the stream and do what ever you want with the file:

// caller-method:
...
XmlDocumentParser xmldocumentparser=null;
WantedObject wantedobject=null;
...
// start parsing:
xmldocumentparser = new XmlDocumentParser(“c:\\example.xml”); // set XML_FILE
wantedobject = xmldocumentparser.doParse();
catch (SAXException ex)
{
if(xmldocumentparser.stream != null)
xmlporukaparser.strim.close();
// delete document or move it , or something else…
}




2) SAX Parser issue No 2 : Problem with large text inside tags


I came up to this problem when parsing xml files with large text inside tags.
When a tag values is a small text or a number, SAX will parse your document without a problem, but when a tag value is some large text, then the SAX will return only a part of that text. The last part of that text.
Why is this so?
Do not ever assume and expect that a SAX parser will return entire String it finds inside some tag. SAX parser ( and a great number of other parsers) will return several chunks of that value, and it is your job to put that pieces together…

Lets see how this works:
In sax, in order to read tag values, among other methods, we need to implement characters() method.


StringBuffer sb=new StringBuffer();
Person person= new Person();


public void characters(char[] arg0, int arg1, int arg2) throws SAXException
{
sb.append(arg0,arg1,arg2);
String s = sb.toString().trim();
if(!s.equals(""))
{
if( currTag.equalsIgnoreCase("name") )
man.setName(s);
.
.
.
// do all the things you want…

}
}


So, do not use just some string:

String s = new String(arg0, arg1, arg2);

and assume that’s all there is inside current tag.

Use StringBuffer instead and append every chunk to it…

and, ofcourse, do

sb.setLength(0);

on start of startElement() and EndElement() methods.


There is also another way of solving this problem:



This is the way of saying to parser “Do not parse what’s in it, just read it all at once…”. This is used when some other xml is inside some tag, for example…

Monday 21 July 2008

Izašao je Eclipse 3.4 - Ganymede

25.Juna 2008 najveći Jupiterov satelit zatresao je planetu Zemlju.
Rečenica kao iz knjiga nau
čne fantastike zapravo znači nešto sasvim drugačije.
Nova verzija Eclipse-a, nazvana po najvećem Jupiterovom satelitu ugledala je svijetlost dana Juna ove godine.

Ganymede nam dolazi kao skup od 23, dok neki od tvoraca u svojim blogovima pišu 24, zasebna projekta. Koga interesuje da sazna više o kojim se projektima radi, može pogledati na sajtu http://www.eclipse.org/ganymede/learn.php
Šta reći o Ganymede-u i Eclipe-u inače? Lično, veliki sam fan Eclipse-a i radujem se svakom izlasku nove verzije.
U njemu mi je jako lijepo za raditi. Brz je, ima dosta lijepih opcija koje ubrzavaju rad , lako se nalaze i instaliraju plug-in-ovi, i nekako, čini mi se da programeri koji prave eclipse vrlo lijepo prenose svoja isustva koje opcije bi trebale postojati u nekom IDE-u i na kojem bi se mjestu trebale nalaziti.
Smatram ga SKORO savršenim IDE-om, ali skoro!
U pitanju su par stvari koje su učinile da ga u razvoju koristim samo kada pravim java binove za Oracle Forms Builder jer jako lako mogu podesiti compiler complience level na 1.4 verziju jave ( više o kreiranju java binova za oracle forms builder koristeći Eclipse ovdje). S druge strane, sa nestrpljenjem sam čekao da ove stvari budu popravljene pa da Eclipse takođe mogu uzeti u obzir pri razvoju velikih projekata. Ostaje da vidimo da li je put do toga cilja dug i trnovit ili je sa ganymedeom već riješen…

Nego, da krenemo od početka
... Da vidimo koji projekti čine ganymede:

Dakle, radi se o veoma lijepom spisku stvari koje trebaju programerima. Projekti su , očigledno pažljivo odabrani, ali ne bi marilo da se spisak proširio za još nekoliko korisnih stvari potrebnih pri radu...
A ako pričamo o onim sitnim stvarima, detaljima koji nam čine da nam neki IDE bude omiljeni, Ganymed ih je pun. Počevši sa brzinom samog IDE-a, lakim podešavanjem compiler compliance level-a, sa jednostavnim wizardom za kreiranje .jar fajlova, sa funkcijama koje su na , po meni , dobrim mjestima, kao npr. stavke padajućeg menija za generisanje koda ili dugme za kreiranje nove klase,paketa ili slično, odličan debuger , velika radna površina u odnosu na npr. neke druge IDE-e , jednostavni update bilo koje komponenete IDE-a, plug-in-ovi za skoro sve, izuzetno je prilagodljiv željama korisnika…
Posebno bih pohvalio novi sistem update-a koji će sam za vas odabrati i downloadovati sve dependencies-e, i novi način pregleda stabla klasa nazvan Breadcrumbs .

Međutim, sta je sa onim
“Ali…”
Šta je to zbog čega je ovaj IDE SKORO savršen, a ne savršen ( po meni )? Zašto i pored toga što obožavam pisati kod u eclipse-u ( u njemu mi čak ljepše i vizuelno izgleda nego u drugim IDE-ima) njega ne koristim pri pisanju većih projekata, već samo pojedinih modula istih...?
Koje su to stvari koje bi trebalo popraviti, dopuniti i dodati ?
Prva stvar je ne postojanje aplikativnog servera koji dolazi zajedno sa IDE-om ( u instalaciji ), i koji se bez dodatnih podešavanja i instalacija lako pokreće klikom na dugme u razvojnom okruženju. Naravno, sve se može dodatno instalirati i podesiti, ali ne vidim razlog zašto bi neki programer gubio vrijeme na to, ako postoji drugo, takođe sjajno, razvojno okruženje sa kojim dolazi odličan aplikativni server „in the box”, sa sjajnim alatima za editovanje konfiguracionih XML-ova istog servera.
Druga stvar, koliko god se činila malom i beznačajnom, takođe ima veliku ulogu na mene a to je sam način kreiranja .jar fajla. Ako radimo na nekom projektu koji u sebi sadrži neke eksterne jarove, i od tog projekta exportujemo .jar fajl, Eclipse neće uz njega exportovati i potrebne eksterne jarove , niti će u manifest fajl kreiranog .jar-a dopisati relativnu ili apsolutnu putanju ka eksternim jarovima, već sve ovo moramo ručno raditi. Kažem, mala stvar , ali kada imate posla preko glave, onda očekujete da bar male stvari IDE sam odradi. U ganymede-u je ovo dopunjeno, ali u tom smislu da u jedan .jar fajl integriše sve dodatne .jar fajlove koje vaš projekat koristi.
Po meni, ova stvar je najbolje riješena u NetBeans-u, koji će eksportovati vaš .jar , a u root-u tog foldera kreirati i folder “lib” u koji će smjestiti sve dodatne .jar fajlove importovane u projekat, a manifest fajl će dopuniti putanjom do njih...
Оnо što bih u narednom periodu u ganymed-u volio vidjeti je alat s kojim možemo raditi sa bazom podataka. Pregledati njene objekte, pisati stored procedure i slično... Dakle, nešto što podsjeća na Toad, jer ipak se vrlo često radi sa bazama podataka, i ovakav alat unutar eclipse-a bi zaista bio pravi pogodak!
Ganymede je tek izašao. Sada predstoji malo duži rad u njemu i tek tada možemo dati prave impresije, ali u svakom slučaju hvala Eclipse fondaciji na lijepom iznenađenju...
Do sljedećeg javljanja... Zivjeli!

Friday 18 July 2008

Quick tip 2: Enable TDBGrid to show all columns without scrolling

One of my friends called me and asked me today how to enable TDBGrid in Borland C++ Builder to resize it’s columns on showing data in it.
He had a problem with TDBGrids that need to show some tables or query results with large number of columns.
He needed all of them to be visible without horizontal scrolling.
As I am aware, this function does not exist in TDBGrid, and it has to be made.
If it does exist I’m really not aware of it, and please tell me about it.
So, I wrote him code that I often used and what worked well for me :

I made a function called AdjustGrid() which will iterate through all columns and set their width to some equal value. This way, we can always see all the columns in some DBGrid , almost regardless to it’s size.
Let’s look at the example I made. Button1 just shows the data in the DBGrid, without adjusting any size ( default ).


and when we click on Button2, we get:


…And – it helped him… ;-) ! He even told me he will buy me a beer! ( psss: he never does! ;-) )
…and why am I writing about this trivial thing?
Because I remembered than that many people asked me the same thing before. I hope this will helpful to some of you how are looking for something like this…

Quick tip 1: Session save path Unwriteable (tested with joomla 1.0.x)

One of the problems people often come up to while installing joomla is Session save path Unwriteable error.

In this quick tip you’ll learn how to solve this problem.

Of course , the first thing you need to do is to contact technical support and a webmaster of your server, and to see if he can ( wants to ) help.

If this doesn’t work, install joomla regardless to this error , and in a folder containing configuration.php create new folder , for example temp_folder.
Set it’s CHMOD so it is allowed to write in it.
From configuration.php copy the value of $mosConfig_absolute_path entry ( without quotes ) , and then add a new line to this file:

session_save_path('');

and between quotes in bracets write copied value + /temp_folder

for example, if in configuration.php says:

$mosConfig_absolute_path = '/home/virtual/site76/fst/var/www/html';

Then, we will add a line:

session_save_path(‘/home/virtual/site76/fst/var/www/html/temp_folder’);

save changes. Now try to login to joomla.
Good luck!

Tuesday 15 July 2008

How to bring back old component palette look to BDS 2006

I am very big fan of Borland C++ Builder ! I just love it!
I’m not just big fan of BCB, but big fan of Borland ( Code Gear )!
But there are just few things I just cannot understand:
- Why new versions of BCB don’t look like BCB 6 and BCB 5?
- Why doesn’t component palette look like palette in these old versions?
- Why doesn’t IDE look the same as BCB 6 IDE or BCB 5 IDE?
- And why was IDE build in .NET (if I have been well informed) ? It’s so slooooow now!

Well, to be honest, I do know the answers to some of these questions, but it all seemed better, nicer and faster in BCB 6 and 5. And everything had original Borland look that I liked…

If you (like myself) would like your BDS 2006 to look like BCB 6 as more as possible, I can help you with one thing: to get your component palette to look like the one in BCB 6.

Few days ago I downloaded and installed DDevExtensions 1.5
You can download it from http://andy.jgknet.de/dspeedup/index.php?page=DDevExtensions
The installation is quite simple. As a matter of fact, it could not be easier than it is…

There is an installer ( .exe ) provided. Just run it, and follow the wizard. In a few seconds you’ll have your DDevExtensions installed.
New ( old ) palette is not going to be shown by default. In order to activate it, go to Tools -> DDevExtensions options,


and under “old palette” just select “Active”.


The old palette look is not the only thing you’ll get. I like “Search component” too.
Just start tipping the name of component you need, and it will find it for you…



I didn’t test DDevExtensions yet, but it looks promising and I’ll sure give it a try!

Sunday 13 July 2008

Creating and using Java beans in Oracle Forms builder

Probably anyone who uses Oracle Forms Builder, at some point found himself with a certain problem that is very hard to fix using Oracle Forms Builder only, although it gives prety much everything you need to build a database application.
On the other hand , large number of those who managed to solve the problem weren’t even aware of a fact that they were able to solve that ’large’ and unusual problem by using Java beans, which can be used in Oracle Forms Builder.
Not to mention that many developers don’t even know about this functionality of Forms Builder that enables us to use Java code in our Oracle Forms application, and those who do know about it don’t know HOW to do it!
What I now plan to do is to show you how you can create and use some simple java bean in your Oracle Forms application.
These examples are far from usefull and complex but it will help you understand how to make a java bean and then you can create very usefull and complexe modules using almost complete power of Java...
I use Oracle 10g , and Developer suite 10g , and that means that we must use 1.4 version of java while building our bean.
Let’s open Eclipse and create new Java Project. Let’s call it „MyBean“ , and let’s create one Java class called „FirstBean“. For now, we have something like this:


The easiest way of creating a java bean that we can use in oracle forms builder, is to extend Vbean class. Vbean is located in frmall.jar. You can find it in %ORACLE_HOME%\forms\java on windows. ( for example, I have it on location C:\oracle\DevSuite\forms\java )
In order to use it, open project -> properties in eclipse , and under „java build path“ click on the Libraries tab , and then select frmall.jar by clicking on the „Add external jars“ button.


I mentioned before that we must use 1.4 compiler compliance level , so select it from drop down list, under „Java compiler“.


Click apply .
I will make a bean that we can use to:
- Get our own IP address
- Switch letters case of some string to upper case
- and to show input dialog for a user to enter some string and retrieve that string.
These examples are more than trivial , but they will help you understand a logic of building java beans that you can use in oracle forms builder.
You will soon see that we communicate with java beans by setting and getting some custom properties. all this is done by the use of the getPropery and setPropety methods defined in the Iview interface. Each property is created and stored within the oracle.forms.properties.ID class.
Let’s make 5 of it:


We will use I_TEXT to set an input dialog text, IP to retrieve ip address , SET_STRING to set a string for which we change letters case , SHOW_INPUT to say a java bean that we want to show input dialog, and UPPER_CASE to say a java bean that we want to retrieve (upper cased) string that we sent earlier.
So, the only two things we need to set before getting the result from java bean are I_TEXT ( text to be shown on input dialog) and SET_STRING ( the string that is about to be upper cased ).
In order to set it, we must use setter setProperty() :


and later when we call SET_CUSTOM_PROPERTY in PL/SQL we will send it’s value.
example:
If we have a BEAN_AREA in oracle forms called BLOCK4.BEAN_AREA11 , and want to set I_TEXT ( input dialog text ) to be : „Please insert a value:“ , we would call
Set_Custom_Property('BLOCK4.BEAN_AREA11',1, 'I_TEXT', ’Please insert a value:’);
The other three ID classes are used to get a value ( remember? : IP , upper case string, and input dialog entry )

and with PL/SQL’s function GET_CUSTOM_PROPERTY we are able to get these properties.

example:
If we have a BEAN_AREA in oracle forms called BLOCK4.BEAN_AREA11 , and want to get and show user’s entry from the input dialog into the :BLOCK4.TEXT_ITEM10 , we would get it by calling:
:BLOCK4.TEXT_ITEM10:=GET_CUSTOM_PROPERTY('BLOCK4.BEAN_AREA11',1,'SHOW_INPUT');
Here is the entire FirstBean.java file.
When we are finished writting a java bean, let’s export it as a .jar file named „mybean.jar“.
In eclipse, right click on MyBean project, and select „Export“. Follow the wizzard .


Copy the .jar file you exported into %ORACLE_HOME%\forms\java folder ( in the same folder where frmall.jar is located ).
Update %ORACLE_HOME%\forms\server\formsweb.cfg with „mybean.jar“ entry:


in the registry editor update FORMS_BUILDER_CLASSPATH variable :


Start OC4J instance ( START -> Oracle developer suite -> Forms Developer -> Srart OC4J instance ) .
Start Forms builder.
and on the canvas drop BEAN_AREA. Set it’s Implementation Class property to
me.tcom.darko.bean.FirstBean


and start using it.
Here is the following code for our three functionalities:
to retrieve IP address:
:BLOCK4.TEXT_ITEM10:=GET_CUSTOM_PROPERTY('BLOCK4.BEAN_AREA11',1,'IP');
(notice: we are not setting anything in order to get this result )
to change letters case of some string to upper case:
Set_Custom_Property('BLOCK4.BEAN_AREA11',1, 'SET_STRING',:BLOCK4.TEXT_ITEM14);
:BLOCK4.TEXT_ITEM10:=GET_CUSTOM_PROPERTY('BLOCK4.BEAN_AREA11',1,'UPPER_CASE');
(notice: in order to get upper cased string, we need to set it first )

and to show input dialog to user , and retrieve user’s entry:
Set_Custom_Property('BLOCK4.BEAN_AREA11',1, 'I_TEXT',:BLOCK4.TEXT_ITEM6);
:BLOCK4.TEXT_ITEM10:=GET_CUSTOM_PROPERTY('BLOCK4.BEAN_AREA11',1,'SHOW_INPUT');
( notice: again, we need to set I_TEXT first in order to show input dialog )

Here
is complete code ( mybean.jar , FirstBean.java and MYBEAN_FORM.fmb ).

Java beans in oracle forms builder can really be powerful. For many things that you cannot do in Forms builder there is JAVA.
For example you can make java swing application, integrate it into java bean and call it from within oracle forms and many more…
Also, you can register events in oracle forms builder of that swing application and use it , and many more, but some other time about that…