Sunday, December 26, 2010

Lost In China on New York Times by Matt Gross

With school finally finishing another term, I began to have a few time to spare to catch upon my readings.  I would like to share this interesting article that I stumbled across on New York Times. 
http://travel.nytimes.com/2010/12/26/travel/26chongqing.html?pagewanted=1

Chengdu is a place on my travel list.  Even though I have roots in China, when I was young, my familiarities with China's geography was limited to big cities like Beijing and Shanghai.  Yunan being a province next to my country and being crossed the border town of Shwe Li into Kung Ming, that was the farthest I have been in China.  I learned about Chengdu through my college friends who boasted Chengdu as having the best cuisines ever.  And I would like to be there to test their statements.

Wednesday, December 8, 2010

Using Richfaces Editor

This time, I want to write about Richfaces's <rich:edtor>. The good thing about it is that it's based on TinyMCE's WYSIWYG editor like the ones on blogspot.com, which allows formatted text. Now, I needed to use it because I want to have this functionality where users can enter formatted text and the exact formatting will get displayed, just like with this blogging. Richfaces has a good example here

The main thing here is :

<rich:editor configuration="#{editorBean.currentConfiguration}"
id="editor" width="400" height="300" validator="#{editorBean.validate}"
viewMode="#{editorBean.viewMode}" value="#{editorBean.value}" useSeamText="#{editorBean.useSeamText}">
<a4j:support event="onchange" reRender="result" ajaxSingle="true"
requestDelay="1000"
onsubmit="if (!#{rich:element('form:editorvalue')} && !#{editorBean.useSeamText}) return false;" />
rich:editor>
In my project, I don't need to use a lot of those attributes. What I used was configuration, value and viewMode. I also definitely don't want to use ajax support because doing so will reRender the editor everytime. I need to use advanced setting since I want to allow users to do formatting but I need to limit the format options. It turns out that if you use the default advanced setting, it'll give you 3 format bars. I need to change that as well. The following code describes how I achieved those settings. As you see, it's not complicated at all.
<rich:editor theme="advanced" configuration="rich.editor" value="#{note.instruction}" width="1000" height="200">
     
<f:param name="theme_advanced_buttons1"
              value="bold,italic,underline, cut,copy,paste,pasteword,link,unlink,bullist, numlist" /
>
        <f:param name="theme_advanced_buttons2" value="" />
        <f:param name="theme_advanced_buttons3" value="" />
        <f:param name="theme_advanced_toolbar_location" value="top" />
         <f:param name="theme_advanced_toolbar_align" value="center" >
</rich:editor>
My current format options are limited to a few formatting. If you want to add more, you can add it.  The list of button controls are documented here 





The data are saved in the database with all the formatted tags.  If you display using regular <h:outputText>, it will display all the formatted tags since that's how it's being stored.  In order to display formatted text, you will need to set "noEscpate" attribute of <h:outputText> to "true"

Saturday, November 20, 2010

Unmanaged Entity Converter Part II

As you all know, seam's entity converter works only for persisted objects. If you have transient objects, then you will need to write a custom converter like here.

The thing about the above converter is that you need an abstract entity class, which will need to be extended by the entities that you are managing for. The solution used a Hash Map that takes in a key-value pair. The value is the object and the key of the object is implemented by the abstract entity manager.

One of my coworkers used slightly different approach, which I think is neater and did not require each entity to extend the abstract entity class. What he did was instead of creating the key, he used the hashCode value of the object. Each object is unique and so are their hash values. Therefore, we can safely use the hash values as our key. The detailed code is shown here.


Now, after we upgraded to JBoss 5 and Seam 2.2.1, the way we called the converter from the code is not working anymore. We originally used <f:converter converterId="nameOfConverterId">. But we keep getting "Value Not Valid" error as thrown by JSF. After two weeks of trying to figure out what is the cause, a slight change in the way we call converter solved the problem. Instead of using JSF tag, you can use the converter attribute of the component. For example, if you are using <h:selectManyCheckBox>, you can write like this :<h:selectManyCheckBox value="#{myValue}" converter="#{converterName}">. Make sure you reference the converter name using EL expression, otherwise it won't work.

Hopefully this post will save you a lot of time if you are having similar issues.



Wednesday, November 17, 2010

If you are an undergraduate or graduate Computer Science student, it's very possible that you will have to take an Operating System class as part of your curriculum. Most of the time, the class will have labs or coding projects. I'm not so sure of this, but I can say with a 99.9% confidence that almost all OS classes in the State uses Tanenbaum's book. I am not sure why it is so. I haven't read many Operating System books, so I can't make comparisons. But his book is one of the highly favored one. And also I notice that most professors who teach OS have experiences dated back to 1970s. From my experience with two different OS professors, both of them have experience dated back to those days with punch cards.

From my experience, most students hate OS class. But I think it is one of the important classes that every person in computer science or engineering discipline should learn about. The fact is that most of us enjoy coding and learning all sorts of programming languages. But we do not like to learn OS.

The thing that makes it hard us to enjoy OS is that there's no direct practicability, and it is very theoretical. And it's a lot of materials to digest. Professors will assign you to write a program that mimics those scheduling algorithms. But say, if you really want to see how it is done in your Windows XP or Unix, you need lower level programming. It is not as straight forward as C or Java.

If you are trying too hard to fit what you learned into the programming aspect, I'd suggest that you take a step back and try to understand as it is without complicating it. Of course, you will need some background knowledge in order to understand it. And if you have trouble understanding it, try to read through materials again and again. I find that Tenanbeum's textbook is pretty good at explaining. I'd compare that reading his textbook is pretty similar to reading an anatomy book. It's pretty self-explanatory, but a lot of materials to be memorized.

So, don't worry if you can't seem to get it through. Most CS students have to go through that once in their life and you are not alone.

Sunday, October 31, 2010

<s:convertEntity> for non managed entities

For those of you who uses <h:selectOneRadio> with entities or enums in Seam, you will definitely need to use <s:covertEntity> or <s:convertEnum>. It will assign an entity or enum converter to the current component. It is essentially useful in drop downs and radio button selections.

However, in order to use the s:convertEntity or s:convertEnum, you have to be Seam Management Persistent Context. In other words, the value that is being used in your h:selectOneRadio or h:selectOneMenu has to be a persisted entity. It WILL NOT WORK OTHERWISE.

For some reasons that you need to use a transient entity, then you will need to write a custom converter for handling those unmanaged entities. The given link from Seam will help you understand how to write a custom converter for those transient entities . http://seamframework.org/31463.lace

Tuesday, September 28, 2010

Specific error messages mystery solved.

At the beginning of this month, I wrote about a problem I faced after upgrading JBoss 4 to JBoss 5. I have a class that validates information. When user clicked a button, it first calls that validator method, which in turns return a true or false value. If validation passes, the user can proceed, otherwise, the user cannot process and the page is re-rendered with error messages. The problem I faced was that all the messages are appearing at the global level instead of specific component.

In the code, I used <rich:message for="componentId" /> for error messages.

After contacting JBoss support and a few test cases, I solved the problem. The problem was that when the validation failed, I return the page by writing return "page1.xhtml" in my code. If I changed that line of code to return "", the error messages are rendered at the right location.

Thursday, September 9, 2010

Seam User Transaction

I have to use Seam's user transaction for one of my stateful bean. I needed user managed transactions because I was doing batch processing. I was using Bean Managed Transactions.

On the view, there are two major process; one is a command button which calls a method and the other one is a <rich:dataTable> which has one entity per line, and h:selectOneBooleanCheckBox for each entity attributes. The idea is that I'm providing user with a list of books, and users can select if a book is Spanish, Chinese or Italian by selecting the appropriate check boxes. Since I'm using ajax, I put <a4j:support> inside <h:selectOneBooleanCheckBox>, which is supposed to automatically update the value in the database. But it didn't happen. The boolean value never gets updated.


After trying a few hours, I finally took out the transactionManagement annotation from the bean and made it a regular stateful bean. Then all those boolean values get updated. I think since my stateful bean is responsible for committing transactions, that's why I can't expect the container to automatically commit the boolean values in the entities.

Wednesday, September 8, 2010

We updated our JBoss from 4 to 5, and our Seam got updated to 2.2.1. There was some modification in the source code in order to comply with JBoss 5 and Seam. The big problem right now is the deprecation of FaceMessages, which is replaced with StatusMessages.

StatusMessages' addToControl() method didn't work. It works when a message is added to a global <h:messages>. But if I want to customize a particular input of a form with <rich:message>, it doesn't work. Instead, it displayed all the messages at the global level.

I think what is happening is that, there was something changed with the updated Seam, that makes searching of components in a form always returning null, which consequently causes all messages to be display at the global level.

Granted, my current form is huge and complicated. There're some other parts where there is only <h:form> and simple code, where displaying message in particular place worked. So, I think it's a matter of trying to rearrange my JSF view code to keep up with the changes or there is some bugs.

Monday, September 6, 2010

Two books that made my day



I know I have stopped writing about my work with Java or other programming topics. Since I finished my summer class, I have been pretty relaxed and enjoying my last few weeks of my holidays before my fall semester starts again. There was an immediate project at work that I had to work on, which exposed me to non-AJAX web development. But it was not interesting enough for me to write about it. So, instead I'll focus on two books that I read this past week: Love In The Time Of Cholera and The Red Pyramid.

I always admire good writings. A good writer can make a boring story interesting and better. Classic example is Jane Austen. All of her books are basically about romance between a rich guy and a poor girl, which is made more complicated by their different social classes. They always have happy endings. But I can never get tired of reading Jane Austen's novels. Love In the time of Cholera is another classic love story, but it is amazing because of the writing. I'm not sure who should I give credit to for such a beautiful writing: the translator or the writer himself, since its original version is actually released in Spanish.

Another book I read was called The Red Pyramid. It was a more modern story, writing is mediocre but it was the story that attracts me. I am always interested in ancient mythologies, especially Eyptian ones. My childhood dream has been to visit Egypt one day and I still hope to do so. But I actually didn't know much about Egyptian god and goddesses. That fact didn't occur to me till I read The Red Pyramid. It is similar to Percy Jackson's series in that both main characters are semi-deities. It is not a surprise especially because The Red Pyramid was written by the same author as Percy Jackson's.

I'm glad that I'm catching up on my readings, especially since I used to read a lot as a kid and teenager. I believed that reading was what actually made me who I am. Since I started my undergraduate, I kinda stopped reading. I read but it was more like textbooks. I'm happy that I've began this habit again.

Monday, August 30, 2010

Cutie pets


I have never really been a cat person. But everything changed when my roommate brought in two kitties 4 months ago. In fact, it was only one kitten in the beginning. Then, fearing that her kitten might get lonely, my roommate took in another kitten.

I was uncomfortable about having two kitties in my house. Well..I didn't know certain qualities of cats. The best thing about them is that they take care of themselves. I was amazed when the kitties used the litter box without training. I think that alone is a great plus.

Lately, I noticed the presence of other living creatures in the house and how it affects me. Our first kitten, Mie Mie is about 5 months now and our second addition, Snowball(because she was white) should be about 4 months. I noticed that I came to attach to them. Every time I come home, I know that they will be there behind the doors, waiting for me to come back. Even though I do not play with them that much(as you know cats are known to be lazy), I came to acknowledge their presence.

I would like to try to have a pet dog some time in my life.

Wednesday, August 25, 2010

The girl with the dragon tattoo

I read The Girl with the Dragon Tattoo...in one day. I did not really know the story before I started reading it. I just knew that it was solving the mystery of a missing person, and there was some financial corruption involved. So I thought it was some sort of conspiracy stories. However, I was wrong and I felt like I wasted my time staying up late till 4am to finish up the novel.

I like conspiracy stories. I liked Bourne Ultimatum series(I never read the books, just watched the movies). So, I think I held a very high expectation of the Dragon Tattoo given that it was a best seller in Europe and then in America. As I was reading it, I felt like the story was one that have been repeatedly told by many other novelists; rape, sex and missing person. Of 'coz that was not all to it. There was some corruption in the finance sector of Sweden, but to me, that part of the story wasn't intelligently plotted.

I kept in my mind that I was reading a translated version. Sometimes, a good story is dependent upon choice of words, metaphors and so on. Since this is a translation, I cannot comment on the narrative ability of the author. I can only tell that the story plot is one too familiar kind and I was totally disappointed that I even gave up the idea of reading its sequels. However, I watched the trailer of the Swedish movie adaptation and I found it to be interesting. I am not too keen on the idea of making an American version. More over, I do not like the girl who was chosen to play the main protagonist. I think Swedish actress Noomi Rapace did a very good job in the movie.

Wednesday, August 18, 2010

rich:tabPanel and selectedTab

rich:tabPanel is one of the richfaces components that we use very frequently in the project. One reason is that it allows us to do all processing on one page instead of multiple pages. It has its own drawbacks, but I think it's totally subjective to each individual and the type of applications.

Among the few properties of rich:tabPanel the 'name' and 'selectedTab' attributes are useful. Each tab can be given a name that you can references from other places and the 'name' attribute is just what you need. If you want to control which tab is active, then you will need to use 'selectedTab'. The process is simple, you can have a variable at the POJO or bean which can be an integer or string type. You can have that variable outjected by using @Out annotation. On the jsf page, all you need is selectedTab="#{varname}".

Now, I just mentioned that you can use both Integer and String type for the variable and it will work. Now there're times that an Integer type variable will cause some problems. For example, I gave each tab a dynamic names, which I did it by using object.hashCode() method. Each object is unique and therefore, the hashcode() will be unique. This will save you a lot of energy from brainstorming the names of the tabs if you have 10+ tabs. But when you use Integer variable for the selectedTab name, the page will crash everytime you try to do some processing. It is crashing at the Apply Phase because after you request an action, it'll try to restore the view and restore all the state variables and at that point, for some reasons, it cannot restore the selectedTab Integer variable. The workaround is to use String variable in this situation.

Friday, July 16, 2010

Hibernate error : Cannot instantiate abstract class or interface:

If you ever saw this error message "Cannot instantiate abstract class or interface: " in retrieving a list of objects, there could be one of the two reasons.

Assuming you have an object model where there's an abstract parent entity which is inherited by a list of children entities and each entity is mapped to a table, then

1) First make sure that records are consistent. That is, when you try to retrieve a record, hibernate is retrieving a list of parent objects and according to the data model design, each parent object must have subsequent child object. So, for each row in a parent table, there should be a matching record in the sub-table. For some reasons, if the record is missing the sub-table, when hibernate returns the data, it will throw the exception since it cannot instantiate the abstract parent class.

2) It is possible that your data are intact, but the problem is the changes of the data model in the code base. In our class, we removed one subclass but we forget to migrate the data and remove the sub-table that is being mapped to the subclass. Hence, when hibernate retrieves a list of parent objects, it is seeing the right data but since our data model are not consistent, it's throwing an exception.

Thursday, July 8, 2010

Merging landscape and portrait PDFs into one.

In one of my previous posts, I wrote about the problems with merging different pdfs into one pdf package. I followed the sample code posted here to have different pdfs merged into one.

However, there's one problem with that code. The code is fine if you combined pdfs of the same size. But as in my case where I have pdfs of both portrait and landscape, landscape pdfs are cut off. Originally I thought the way to solve this problem is rotating those landscape pdfs and then merge. However, rotating pdf works only when you output the merged pdf using a PdfStamper. The code uses PdfWriter which takes a Document object to write the pdf contents.

After several hours of googling the solution, I realized that, the solution is not by rotating the pdf, but buy changing pdf size. When document.newPage() is called it's generating a blank page and contents are being written to the new page in the following lines of code. The default page size is portrait size, so if we change the page size and copied over the content, the new PDF would be copied without being chopped off. Only one line of code is needed to solve the problem, which is
document.setPageSize(pdfReader.getPageSize(currentPageNumber))

Here pdfReader must be pointing the current pdf that is being copied over. Another important thing to note is that setPageSize() method has to be put before document.newPage(). If you put it after, then the changed page size will be effective only for the next page, not the current one.

Monday, July 5, 2010

Dynamic including of a page inside <rich:modalPanel>

I've used <rich:modalPanel> inside a dataTable successfully in the past. I did it in two ways. For simple <rich:modalPanel> i.e a modal panel that requires no actions except for just displaying information, I just put <rich:modalpanel> inside the dataTable. This is not really a good solution since, one modal panel is associated to multiple instances of object. And I have conversation time out experience when I tried to open up the modal panel and close it multiple times quickly.

The other way to use modal panel is to send parameters to the modal panel. This is useful especially if you have a form inside a modal panel which you want to do processing. In this scenario, modal panel is declared outside the data table. Every time, the panel is open, an object reference can be passed to a variable in the backing bean so that we know which object we want to associate the currently active panel with. Obviously, this requires more steps on the programmer side.

Honestly, I do not have a good experience working with modal panel. In theory, modal panel sounds a good solution for many user interfaces, but I still find that <rich:modalPanel> to be lacking in some features that I would want. Also, it doesn't allow nested forms inside the panel.

So, my last annoying experience with <rich:modalPanel> is when I want to include a page inside a modal panel. And the page is dyanmic, i.e, given the object information, I would like to include a certain page. So, I have <a4j:include sr="#{object1.name}.xhtml" inside the modal panel. It turns out that I cannot do that and every time I tried to access the page, object1.name returns an emtpy string. I think what is happening is that <rich:modalPanel> is being rendered on the page load. It's not dynamic rendering. Therefore, the object value is not there and it's not returning the appropriate page. I need to do a little bit more debugging regarding my assumptions. But when I can add a static page to be included in the modal panel, it worked just fine..

Wednesday, June 30, 2010

How to prepopulate an email message with subject and body

Today I learned about how to populate an email message on client-side.

I think most people know about how to create an email link in html. It can be easily done by using
<a href="somebody@mail.com>Mail Somebody</a>
But what if you want to partially pre-populate the subject title and message body?

After googling for the answer, I found out that you can easily get the job done by using
<a href="mailto:somebody@mail.com?subject=Hello There&body=Line 1%0ALine 2%0ALine 3>Mail Somebody</a>

Since I'm calling the method from jsf tag, instead of using <a href>, I can use h:outputLink since h:outputLink produces html links. Also I've read people complaining about the html link not working if you put space in the subject or body. You can simply solve the issue by putting '%20' instead of space.

Click Mail to try out.

If you also want to know how to include cc and bcc recipients, here's a great page:
http://www.pageresource.com/html/mail2.htm

The complaint I have regarding this is that I cannot use other jsf tag to get the same performance. I would like to use a menu item (for consistency) instead of a link. I tried it in many different ways and it is just not feasible. Also, please note that you will need to have an email client(i.e Outlook Express etc. ) set up for this to work.

Monday, June 21, 2010

Android's Very Basic

So after learning some Android basics using Note Pad tutorial, I decided to write a simple program on my own. Note Pad was a great tutorial, but I always feel that the best way to master a programming language by trials and errors. So, I began to write a simple Hello World program (Yep, hello world again..) which greets according to the name users type in. So, if you type in Paras, it will display "Hello, Paras".

So, for my program, I need a button, a text field input and a text output. I've always been confused about layout for Android. I know that for each layout, you are supposed to write an xml file and put it under /layout folder in the project. The file strings.xml under /values folder hold all the key value pairs. So, for example, if I want to put a button that says "Say Hello", I put button in the .xml file under /layout folder. The button name will have to be specified in strings.xml. I know this is a very confusing way of doing GUI. However, thanks you a blog post I found using Google, I found DroidDraw(http://www.droiddraw.org/). It's beta version, but it is useful. You can generate layout xml codes using DroidDraw. However, you will still need to modify strings.xml file on your own.

If you have learned a little bit of Java Swing, you will find Android very similar to it. They used same concepts such as Action Events.

Instead of posting the whole code, I'll just state the important ones. When you launched your android application, you will have to do set up and this is done inside onCreate() method. onCreate() methods is from Activity package which has to be extended in every Android application. Each application can have one or more activities. For example, launching the application is one activity and pressing a button can be another activity but doesn't have to be.

Then you can set your layout by writing
setContentView(R.layout.main);

R.layout is the default for all application and main is the name of your layout file. In my case, my layout file is named main.xml.

Next thing is you want to say hello, when user click the button. So, like Swing, Android uses event listeners. We have button objects and event listeners are set to those button objects. We need to get a reference to our button object first. To do this, we say
button = (Button)findViewById(R.id.sayHelloButtonId);

The layout file, main.xml has a button tag and the tag will have an id reference. We're using that id to find our button object. So, the last steps is displaying hello,


button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sayHello();
}
});

Sunday, June 20, 2010

Android won't be able to catch up Apple OS

I downloaded the Note Pad tutorial that is provided on android website. I'm on tutorial #2 and it is about how to add and delete a note.

After my first helloWorld program and Note Pad 1 tutorial, I feel very frustrated about the way Android programming works. You need a bunch of xml files for positioning, creating activities and providing values on the objects.

So, at the end of the 2nd tutorial, I was running and testing the application. I realized that there's a piece of code that stateed about deletion of a note. I was very confused because I did not see Delete Note on my apps. I tried many different ways but the Delete button is no where to be found. And then, I tried to read the code carefully and noticed that Delete Note button is added when a Conext Menu is created. Honestly, I'm a bit confused about what a Context Menu is since I didn't read all the fundamentals line by line. Then I realized that I didn't try pressing too long on an existing note. And I tried it and the Delete note appears!

At the same time, I realized that that might be how the copy function works on android. When I got the phone first time, I was upset because I had to manually enter numbers to copy contacts. But that's how copy works too, you have to press on a text field for a long time for a context menu option to show up. Why can't they program in a simple and more straight forward way. Most users are not tech savvy and they will need to cater to those people. With the way that they are going, I don't think Android will be able to catch up with the popularity of IPhone OS anytime soon...

Sunday, June 13, 2010

My Experience With My First Android App

So, I've been wanting to join this mobile app business and finally started to learn to develop my first helloworld android apps. At this point, I'm not fully there yet because I ran into problems using android SDK. But I'm almost there..

As with most mobile app, you need an emulator to test your android app. I'm still a little big vague about this keystore thing that android apps require. But I'm sure I'll figure out once I try to release my app. For now, I'm good with using emulator.

Originally, I was trying to develop the app with Eclipse by installing ADT plugin. I successfully downloaded it. However, as the tutorial stated, if I go to Eclipse-> Preference, Android should be there. But it wasn't. I tried researching it and some suggested that I needed Aptana plug-in. I installed it and it still didn't work. Meanwhile, the new plug-in(Aptana) was messing with my Eclipse configuration. Since I needed Eclipse to be in the current state(i.e. I don't want to re-install and re-configure for my project), I decided to give up on the idea of using an IDE for development. So, I've been using command line tools for the first app.

Another problem that I ran into was trying to install my app onto the emulator. The tutorial said I needed to use adb command. But, when I first used it, it gave me no device found error. I had the emulator running and even when I typed in adb devices command, it's showing me empty device list. It's not showing no device so it is detecting but not connecting to my emulator. After some search and a few commands tries, I had to kill adb server and restart it and it worked.

I'll continue my tests and tries and I'm really excited to see my first android app on the emulator.

Saturday, June 12, 2010

Adding path variable in Mac OS

Every day is a learning experience for me. I learn from work. I learn from my activities. So, today I learned how to set a PATH variable in Mac.

I know how to set a PATH variable in windows. That was easy. I'm finding it hard to get a solution that will solve my problem. Because Mac is based on Unix and there're so many different version of Unix out there, the answers that I found are not applicable to me. However, thanks to tech_recipes.com, I was managed to change my path variable.

So, I have to use export command. The format is
export PATH=
and then I can add any path I want at the end of that. So for example, I can do like
export PATH=/user/bin
to set my path variable to /user/bin. This is only for one path. If I want multiple paths, then I have to separate it with a colon. Also, notice that you cannot have any space except between the key words export and PATH.

To see what is your system's current PATH variable, you can type env command. However, if there're existing PATH and if you type in export PATH=/user/bin, the original path will be overwritten. So, you will want to append the path at the end of the existing path. The way to do is that to use $PATH variable. For example, you can do
export PATH=$PATH:/user/bin
. That will add /user/bin to the path variable on top of the original paths.

Wednesday, June 9, 2010

Entity Manager Vs. Entity Manager Factory

For those who are confused between entityManager and entitymanager factory, here is a short and simple explanation. An entity manager is an instance inside a persistence context that manages entities. An entity manager factory is an interface that is used to obtain the application managed entity manager. An entity manager factory can create entity manager(s).

There are two types of entity managers : container managed entity managers and application managed entity managers. If you use container managed entity managers, you don't have to worry about a lot of things. The containers that you use(for example I use Seam) will take care of everything. The application managed entity manager is the other way round. There'll be certain situations in which you might want to control you entity manager instead of having a container take care of it.

Monday, June 7, 2010

Calling Seam managed entity manager from a servlet

I've been spending a majority of my time for the past week trying to figure out what seemed like an unsolvable problem. Again, as usual, this is related to the PDF applications.

So, we have the following process flow in our system :
1) Users print the application, which is partially filled with data collected from the system.
2) Then, users can fill in more information (as government applications ask for very minute details of information).
3) Then, users can click 'Save' button provided on the form so that those additional filled data are being stored as fdf file on our server.

Now, users want to download those data files within a given date range. My original work flow didn't involve any database interaction. But now, I have to store data regarding each fdf file so that those data can be used in the download process. However, it requires a database interaction and we use Seam managed persistence context for persisting data in the database.

When the 'Save' button is clicked, before a fdf file is created on the database, it has to create a row in the table so that we know which day fdf file is created and other information. I'm stuck at this step since I can't get the existing entity manager in our application scope from a custom servlet call inside a pdf file.

I've been trying and today I made slight progress. I managed to obtain an entitymanager object from a servlet call. However, I still need to figure out how to do additional processing by using that entitymanager. I'll post the code if I succeed to do what I need to do.

Saturday, June 5, 2010

Batch PDF processing

The weather has become uncontrollably hot in New York City. My AC in the room is not cool enough and I got a free portable AC. I'm not sure how people will go through this summer given the fact that we had an extremely cold winter and our body temperature has been so adjusted to the cold weather.

I am working on my project on a Saturday, and closing the tickets. Sometimes, I wish people to be less demanding or technology to be more advanced so that I don't need to solve problems like the following.

We have different applications in pdf format. We allow them to print those different pdfs in packages, that is they can select two different pdfs to be printed at once, and it will be returned as a single pdf file. Working with pdf applications is not easy. I won't be where I'm at with PDF processing without help from websites like planetPDF.com. Now, the problem is when they print out those PDFs, since not all PDFs come in the same format, when combined together, some landscaped-style PDFs are cut off. And they don't want that to happen.

Right now, I absolutely have no idea how to deal with this issue. For one, they can print out PDFs one by one, and those batch printing is just an option to better save time...

Monday, May 31, 2010

Customizing h:selectOneRadio

So, the other day, one of the users request to make changes to the way a particular dropdown is displayed. I used h:selectOneRadio for the radio buttons and for the dropdown options, I used the s:selectItem that has an arrayList of enums for values. The requested change was to customize those dropdown options so that some options are bolded whereas the rest are displayed normally.

It sounded as a decent request and didn't seem hard. However, I'm finding that it's hard to customize a dropdown choices that uses h:selectOneRadio. I can't just randomly customize s:selectItem, and f:selectItems is also very similar to s:selectItem. The only thing that is left to try is f:selectItem. I thought I could use f:selectItem because it doesn't take an arraylist like others. However, f:selectItem doesn't have 'style' option.

Therefore, I couldn't customize the dropdown list as I wanted. I'm wondering if there's a way out there that will make this customization feasible at all.

Wednesday, May 26, 2010

Platform Vs. Framework

It seemed to me that I'm not the only one who has confusion about differences between framework and platform. Based on my past experience, I understand what platform is in general. We run Operation Systems on Windows platform, Linux platform and so on. By definition, a platform creates an environment that software codes can run. Based on that definition, J2EE is a platform.

On the other hand, framework is a collection of APIs and libraries that guide how software should be run. Programmers can modify the established framework to enhance and modify. However, the underlying architecture of those application will essentially be the same. Seam is a framework, which is run on a J2EE platform.

Monday, May 24, 2010

Web applications and browsers

As a developer of web-based application, I sometimes wish that there were a new type of browser out there. One that will be a hybrid between a standalone application and the true browser type. Not that I don't like what we have right now. I think the development of browsers have come very far(considering the fact that it started out in 1980s and the first browser came out in 1991) and what we have nowadays is very fitting to our needs. But there're some areas where the idea of a browser is not suitable to use. This is coming from my first hand experience of developing web applications.

The idea of a browser is to share and retrieve information in a big network. Most web pages in 1990s were passive in data representations. As we entered into the new century, the idea of internet was changed and browsers became more sophisticated. They supported a variety of functions, plug-ins and multimedia. As we are on the end of two decades since our first browser, we've reached the dawn of cloud-computing, in which browsers play a significant roles.

Now, the question is if current browsers capable of supporting cloud-computing? Granted, there're a lot of web applications out there such as our online banking systems and social networking site that requires the use of browsers. But the idea of browsers as applications is somewhat inconsistent and inappropriate. Therefore, developing of web applications is somewhat different and sometimes complicated.

I don't have a specific list in my mind of what the new application browser should be. But I like the idea of one of Mozilla's add-ons called Prism. It completely removed the annoying buttons such as the back button and therefore, made the web applications more like standalone applications. However, Prism is not very popular and people are still scared to replace Firefox, IE and Chrome with something like Prism. Hopefully, there'll be something out there that will be sophisticated enough to start browser revolution.

Friday, May 21, 2010

Pac-Man turned 30th!

I'm not really a Pac-Man fan. I like Tetris more than Pac-Man, probably because the highest level I ever achieved on Pac-Man is the second level. And I didn't have enough interest to push my effort further.

Anyway, yesterday, Pac-Man turned 30th. Normally I should neither be happy or sad. However, Pac-Man meant something else to me these days. The professor from my algorithm class uses Pac-Man as an analogy to solve the dynamic solution problem. It is not directly applicable, but Pac-Man was an illustrative likeness. So, when someone mentioned Pac-Man, instead of remembering it as a game, I remember it as the starting point to solve dynamic programming problems. ("Chopped the big solution one by one to obtain the smaller piece and find the best one"). Happy Birthday, Pac-Man!

Tuesday, May 4, 2010

Facebook : What went wrong?

Facebook is in decline. Everyday, I hear more people are talking about closing and deleting their accounts. What started out as a project by some college students that targeted to bring students from U.S. institutions together had expanded globally. There are reportedly about 400 million Facebook users worldwide.

Facebook teaches us that to do something that will gain attention, you should target the right audience. Young people are more technology oriented, and especially, college students are the best group to be aimed at because of their intellectual level, social structure and networking ability. Facebook was a success with college students. When Facebook started, there were other social networking sites such as Friendsters and MySpace. However, Facebook quickly surpassed the popularity of those other networking sites because of the environment and perspective that it created at that time. If you wanted to create a Facebook account, you needed to have a valid college/university email address. That gave users a sense of privilege that they are belonging to a limited group of people who share more or less same background. On top of limiting the users who could use Facebook, it also added one more restriction by allowing different privacy settings. During that time, Friendster did not allow users to have control over the display of the information. A lot of Friendster’s users are starting to get tired of their information being display openly. Facebook seemed to jump in the game at the right time. There are other features that contributed to the success of Facebook such as tagging. Facebook API allows the development of applications which can be played in groups by you and people in your friends list, and that also created the sense of belonging and community.

It is a very good social networking platform until a year or so ago. I think the main problem with the decline in the popularity of Facebook is the surge in users; as a consequence the privacy settings are less efficient. And also the role of the business comes to play in the picture. When you develop something because you want to, it is a totally different perspective from doing something to create monetary value. I cannot say that Mark Zuckerberg held no intention of making profit out of this whole venture. But at least, his initial effort seemed to be selfless.

Information is a very valuable asset in today’s world. People are willing to pay for information, and I think Facebook has an advantage of in the possession of the information of the users around the world. If you think current privacy setting in Facebook is good enough, you are wrong. If you want to totally limit the access of your information, there are so many steps involved. Some people will be smart enough to realize the shortcomings of Facebook, and I’m waiting for the day when Facebook will become obsolete.

Sunday, May 2, 2010

Easy way to rename files in Java is not that easy!

I know there's a method called renameTo() in File class. I tried using it. All the posts I found online suggested that all I need is a File object to the new file and call renameTo() method.

I tried all the possible combination and it didn't rename my file. I saw the all my file objects are given the right paths by printing out the file names. The only possible thing I can think of is the permission issues. So I even tried copying the files over to the Shared folder and still failed.

So, I ended up writing a method that copied over the content of the original file into the new file which has the new file name. After that, the old file gets deleted. And it worked and that was a prove that the permission wasn't the issue. I know it's a not-so-sophisticated approach. But it worked and I needed something that will work. Hopefully I will be able to use renameTo() without any problems one day.

Thursday, April 29, 2010

Things happening in my life

It has been quite some times since my last post. I was on a trip to Europe and got back just a week ago. I've been trying to catch up with school and work. It's been almost the end of the semester. Time flies!.

I have a couple of things about Java I want to write. But I'll keep it for later post since I want this post to be less technical. So, this post will be about random things that came to my mind.

The volcanic eruption in Iceland happened just a few days before I took my flight back home. I was in Rome that time and the flights did not affect me. But my parents were flying from Rome to Amsterdam and their flight was canceled. I had to make phone calls and change the trip plan and reservations. I couldn't imagine what would I do if there's no internet. Had same thing happened to us ten years before, we would have been totally lost as of what to do. But nowadays, with internet and our communication system, changing flight was easy and they didn't have to spend time at the airport at all.

Tomorrow, we're having a conference at NYU. It's annual event of High school girls in NYC about Computer Science and Engineering. It was co-organized by NYU's Women in Computing and Princeton's GWISE. This is a great opportunities for those high school girls to be involved in since there were presentations, discussions and talks about Computer Science and Engineering. Topics such as what you can you do as an engineer or computer scientist, how can you apply for scholarships and what types of background you should have. Here's the link if you are interested : http://cims.nyu.edu/~wincweb/HS/

Thursday, March 25, 2010

Strange behavior with a4j:form & s:fileUpload

Last time, I wrote about how you can use s:fileUpload for uploading files. It seemed straightforward and easy. But when I started implementing the whole code, I couldn't proceed.

I have a page where users can upload files and also can change properties of the file. A file can belong to Folder A, Folder B or Folder C. So, I needed to specify the files properties so that I can retrieve appropriate one. So, I had an a4j:form tag with enctype set to handle s:fileupload and other components(two drop downs and one button). But I was having trouble uploading the files. It was just not uploading.

So, in the end, I ended up taking other components out from the form and have a separate a4j:form. And that works. I don't have explanation for such behaviors. All I can say is that if you put too many components and s:fileUpload into an a4j:form with enctype set to handle s:fileUpload, it just might not work for you.

Tuesday, March 16, 2010

Upload Files with JSF, JAVA & Seam

About 4-5 years ago, I learned in Java about how to make a File dialog box appears. I haven't used it about file dialog boxes in my projects. So, I was excited when I had the idea to allow users to upload simple PDFs file without them having to ask me to do it. I know it is going to be a bit extensive work for me on top of what I have to accomplish before the next deployment. But I'm sure that procrastination is the habit of almost all the programmers.

So, I'm going to use Seam's s:fileUpload to allow users to upload a file. s:fileUpload comes with a browse button which allows you to browse through the files in your local disk. The first step for me was to learn how to use that fileUpload tag.

In order to use s:fileUpload, it is mandatory that it's inside either a4j:form or h:form which has enctype="multipart/form-data". In my case, it's like this :

a4j:form id="uploadTA" enctype="multipart/form-data"

Then in the backing bean or POJO, I need to specify either an inputstream or byte array to hold the file's data. The way Seam passes the file information is inside data attribute of s:fileupload. So, it'll be like :

s:fileupload data="#{fileUpload.file}" accept="application/pdf"

fileUpload is my backing POJO and file is a byte[] array. I can't use an injection and outjection attribute for my byte[] array. You will need to use getters and setters otherwise you will get an exception.

If you are up to this part, then all you are left with was how to save the file data on the server hard disk. s:fileUpload only allows you to hold the file's data into a byte array. If you want to have a file, then you need to do a little more work. You will need a button that will call an action method to do the work. So, I have the following on my jsf page :

h:commandbutton action="#{fileUpload.upload()}" value="Upload"

The upload() method looks like this :

public void upload() throws IOException{
if(file.length != 0){
//you can specify the name you want and the path inside File() object's constructor
OutputStream out = new FileOutputStream(new File("file.pdf"));
out.write(file);
out.close();
log.info("Successfully created file");

}else{
log.info("file size is either null or 0");
}
}

Wednesday, March 10, 2010

AJAX & Seam's Conversation Time Out

I've been struggling so much with Seam's conversation time out error that I began to abhor to use anything that is AJAX. Maybe my problem does not entirely lie on AJAX. Maybe it can also be caused by the fact that I used the properties of AJAX a lot on my web design without realizing the side effects.

One should have a strict control of AJAX events if one wants to incorporate AJAX functionality into the web pages. That is, you should clearly planned and set out about how the updates and re-rendering should happen. If you did not, what could possibly happen is that multiple ajax events can simultaneously happen and create a deadlock situation for conversations if you use Seam and AJAX together. I have a big web page with a lot of events and AJAX functions. Now, it's hard for me to trace back what is causing the problem. One way to solve it is to rewrite the whole page, piece by piece, by putting strict control over AJAX events. But at this point in my project, it'll be too much to handle.

A piece of advice that I want to give to those who plan on or have been using AJAX supports is that make sure you use eventQueues attribute of AJAX to organize your AJAX calls. This does not solve the problems at times, but it definitely helps. Also manually re-render the portion of the page instead of using auto re-render offered by . If you have a small page, using 's auto re-render property might be harmless, but it can cause you big problems if you use it a lot on a complicated page.

Friday, February 26, 2010

Modal Panel & z-index value

I've been using modal panel without understanding what a z-index is. It's a CSS property that I didn't have to worry about until recently. Apparently, a z-index value in a component can affect the way components are displayed. The definition of a z-index from w3school is :

the z-index property specifies the stack order of an element.

An element with greater stack order is always in front of an element with a lower stack order


So, if you have two named mp1 and mp2, each of which has a z-index value of 2000 and 1000 respectively (those are arbitrary numbers that I picked), when you called those two modal panels, mp1 will always display on top of mp2. You will be scratching your head as I was, if your mp2 is smaller than mp1, and trying to figure out why mp2 wasn't showing up. The reason is because of your z-index value. In using I don't think you need to specify z-index value explicitly. If you didn't specify any value for z-index and called mp2 from mp1, it'll still display properly.

Showing a process bar panel inside a rich:modalPanel

So, I have been complaining about RichFaces AJAX a lot. The more I get to use most of its features, the more I find that AJAX is not as "agile" as we think. There is one components of AJAX that I really dislike of. It's .

is good if you have something like a warning to display. But if you want to do more such as adding a form onto the , it can give you a hard time. I am not going into length about how it caused me troubles. I'm going to talk in this post about how I called a modal panel inside another modal panel.

So, I have this first modal panel (let's call it panelA) which contains a select one radiobox and a commandButton. So, it's a very basic form where users can make a choice and click the commandButton and in the background, all the events are happening. After the method is called, the page is refreshed with new information. So, the method() in my commandButton is not a very lengthy one. But, depending on the connection, it can take slow and often cause timeout to the users. So, I want to add an indicator that shows that there's something processing in the background and during the processing period, I don't want to let users do any type of additional processing.

Since calling modal panel is mainly done by using javascripts, I tried using onclick and oncomplete attributes of the commandButton. But for some reasons, it didn't work. So, here's what I did in the end :

So, with the help of and , I managed to call another modal panel from inside a modal panel.

If you have a page with multiple method calls which can take long time, I would suggest you to follow the techniques mentioned in here.
http://community.jboss.org/wiki/RichFacesPleaseWaitBox

Wednesday, February 24, 2010

RichFaces AJAX & Problems

AJAX is a technology that has been advancing far more rapidly than any others. Most of the web applications these days make use of AJAX.

AJAX is Javascript based. So, a programmer has control over a page without really having to know too much in details about Javascript. It has made AJAX a popular choice for those who want to make use of Javascript but hate to learn it.

Using AJAX together with dynamic HTML make your web pages more stylish, appealing & sleek. Because you can update the view according to users' choices, it is much easier to do the customization of the pages.

Recent development in AJAX technologies has incorporated other features and hence made AJAX based framework a better choice in creating web-based applications where MVC structure is used.

I use RichFaces which is a framework that combines JSF & AJAX. Even though RichFaces provides us with all of the advantages that I aforementioned, AJAX is not necessarily the best solution sometimes. Why? I can list a few complaints here.

It is true that AJAX makes customization a lot easier. But it has a price on the side of performance. If you make a lot of AJAX calls which update the pages, depending on the way you interact with the page, it can cause troubles. In my cases, I have experienced lost of data because of multiple re-rendering of one page. In fact, troubles with RichFaces are big ones. If you do not prevent from multiple methods being called simultaneously, you are likely to run into the conversation timeout error. So, when you design your application, you need to make sure that a second method is not called unless the first one finishes.

RichFaces is good but let's face it. It's still built on top of Javascripts. So, if you want to change something in depth, you still need to learn about Javascripts. If you look at a lot of RichFaces tags, you can still see that their attributes still make use of a lot of Javascripts.

I'm not saying that you should totally avoid using RichFaces AJAX. Just be aware that there're some pretty serious downsides to it once you start using it a lot.

Tuesday, February 23, 2010

Why people are addicted to Facebook

I attended a talk about two weeks ago by a prominent professor at Columbia University. The talk was about Freedom in Cloud Computing. I decided to attend the event because I thought I might learn something valuable from the talk. Cloud computing has been a part of our lives more or less. Even though it hasn't taken its full form, it'll in a very near future. It's passed the early stages of development and entered the mid-renaissance stage. But the talk wasn't really about cloud computing. It was about the destruction of our privacy by incorporating cloud computing to our daily lives. The professor who gave the talk was one of the important figures from the group of Software Freedom Law Center. Obviously, he hates facebook and twitters. He thinks those applications have been exploiting our privacy by monitoring the usage logs which contain some personal and confidential data. His method of preventing such privacy invasions is by creating the so-called mini portable servers, which can be controlled by only us, not the giant application developer such as Google or Facebook. In theory, it sounded easy and feasible. But in practice, I personally think that it will take quite some time.

I have a couple of friends who use Facebook a lot. I don't like Facebook and I don't like Google. But I am a Google client because of the Google chat which is the only way I can connect with my family.(Other messaging clients are not allowed in my country). I have nothing against Google so far. But Facebook got me annoyed about some privacy issues and hence I deactivated mine. And I haven't had a single regret yet. But I am constantly amazed by the ways in which people are addicted to Facebook and in which people can so easily reveal about one's self and one's innermost feelings and secrets. And I started asking myself why is it that people can share thoughts on sites like Facebook & Twitters, but not in person. Sharing thoughts on Facebook is like distributing your diary book to your classmates. Granted you can control those privacy settings but how much can you really control?

I do have a couple of explanations for why people prefer Facebook and emails over phone calls.

First, it's very convenient. People are self-centered. If you want to talk to a friend, you can call that friend at your free time. But the friend might not spare some time for you. Technologies like social networking sites solve that problem. If you have to talk to a friend for 5 minutes to share a piece of information, you can do that in less time on Facebook. Of 'coz it'll take longer time for them to respond, but on average, you are reaching out to more than one friend.

Second, there's an extra medium between you and the others. You have some type of controls over that medium. If anything goes wrong, you can control it to a certain extent. It gives a person a sense of control and reassurance, because no direct attack is there. Even if it's there, there's at least something you can do about it.

Last, you don't need to wait for something to happen. You can just leave a comment, post a thought on Facebook and just leave it there. Surprising, the amount of attention that you get from others on Facebook is higher than the amount of attention you get from talking to someone in person.

I don't like Facebook. I primarily had the account so that I could keep in touch with some friends. But I realized that I could try to do it in some other ways as well. If I have to have pictures or update my profiles constantly to get my friend's attentions, then I'm sure that I need better friends.

Wednesday, February 17, 2010

Simple Calculator Using Swing Part III

This is a continuation of a simple calculator program that makes use of swing. Just for recap, I covered a few topics such as how to add buttons to a panel, how to order the layout & how to add action listeners. This post will briefly explain of the logic of each action listener corresponding to each button in my calculator.

In my calculator, there're numbers 0 to 9 and other signs buttons. In this post, I will like to focus on how I develop my code regarding those arithmetic operation.

Each arithmetic operation consists of two operands, one operator and one result. Since we have only one text box, we definitely one temporary variable to store the number because the text box can hold only one number at one time. So, let's break down our process of adding numbers. It'll be like this :
1) Enter first number
2) Choose the type of operation
3) Enter second number
4) Choose = sign to get the result

As I mentioned, we need a temporary variable to store the first number, and we need to write a method to perform the arithmetic operation. So, after we enter the first number and choose an operation type, we need to clear out the first number so that when you enter a second number, the text box will start from scratch.

So, the code will look like this :
The above code is for addition. So, for other arithmetic operation, it'll be similar.
Now, what happens when you hit =. It's supposed to grab two numbers and return a result. And here's what the code looks like.
Of course, the whole project will consists of a bunch of if-else statement to capture the right button action. And note, since we're using a text box here, you can enter the numbers. However, you can't using any keys other than number keys to perform operation. Additional steps are required if we want to capture users' input from keyboards and that'll be one of my future topics.

Thursday, February 11, 2010

Hibernate & MySQL : Pitfall

As you know, I work with EJBs, Seam & Hibernate. I have nothing against them. In fact, I think the use of those technologies together with MVC architecture has many advantage in terms of development. First, we programmers do not have to worry about low level architecture. The use of Hibernate in object mapping to database actually eases out a lot of troubles of writing database calls. So, we can focus more on code development and efficiency. Or you can argue that programmers are generally lazy and always trying to find a way to make life easier. But sometimes, it can backfire.

Hibernate does a lot of things for us. As long as we know some hibernate annotations and a little bit hibernate sql, we can write an application with Java at business logic layer and any relevant database at back end. But here's one important thing before you develop your data model and start implementing. If you decide to use MySQL as your back-end database, MySQL doesn't allow you to join more than 61 tables at once.

Depending on what type of data model you have, it might affect you. For examples, we had object hierarchy data model with one root and multiple children. Since we rely Hibernate on querying the data from MySQL, Hibernate generates those queries automatically. If you have one parent with more than 61 child tables, hibernate will generate a query that joins all those child tables. You might be wondering how you can have a data model that has one parent and more than 61 child tables. Well.. you just can.. So, one way to avoid is not to use MySQL at all or try to have a better data model.

Thursday, February 4, 2010

Fundamental of Algorithms

I've started school again. So, between work and classes, I'm a bit busy. I'll occasionally write about some interesting problems/stories that I encounter at school. I am starting Master program in Information System at NYU. This semester, I'm taking Fundamental of Algorithms class.

Quite honestly, I was a bit worried of that class. I personally don't think I am a hardcore CS person. I love writing programs, solving problems and finding solutions. But I never really take interest in theoretical CS. Algorithms was a required class but I think I would have taken it had it not been required either. I am planning to make the best of my graduate studies(partly because it's a very very expensive investment) by taking as many classes that interests me, as I can.
My heart sank more after looking at the course website. It seemed like a really hard classes. Homework seemed to be like unsolvable puzzles because the professor mentioned that we're not required to solve it entirely.

But after two classes, I find myself enjoying the class. Yes, it's hard but it's totally worth it. I'm not sure which grade I will end up getting in the end. But I hope it is a good learning experience. And all I can now is try my best to learn and solve the problems.

Tuesday, January 26, 2010

Simple Calculator Using Swing Part II

I talked about some GUI components that you can use in my previous post. In this post, I will explain to you how to use those GUI components.

Buttons and Text Fields are useless unless they do something, right? Some actions are triggered if you click a button. So far what we have is just display. You can run the code and will see that nothing happens when you click a button. So, now, I am going to implement an action method. Here's the code snippet : (You can click on the code to see it bigger)

You just call addActionListner() of JButton. addActionListner() take an ActionListener object. As you see it, we're passing our class SimpleCalculator to addActionListener(). ActionListener is an abstract class that has the method actionPerformed(). An abstract class has methods that haven't been implemented. So, whatever class that uses abstract class have to implement those methods in the abstract class. In ActionListener abstract class, there's an actionPerformed method. So we're going to write the code for actionPerformed method in our class. Also, you need to make sure that you declare :

public class Calculator implements ActionListener

and here's our actionPerformed() method.


The logic here is simple. Now, when you click the number buttons, you should be able to those in the text field.

Saturday, January 23, 2010

Simple Calculator using Java Swing Part 1

I wrote about Java Swing and its components in my previous post. Now, it's time to move on to the next steps which is learning how to make use of those components and create an application. Of 'course, I didn't talk about all the components that come in the package. But we will encounter some new ones in a few. I personally think that you learn the most when you have a concrete example or project that is useful and applicable to the real world. Therefore, I decided to write a program called A Simple Calculator. This will be a long post. So, I'll try my best to highlight the most important notes. I also want to extend this project to a few posts. So, in this post, I'll talk about the layout of a swing application. The following is a screen shot of my simple calculator.


It's a simple calculator : it has a couple of JButtons and one JTextField. (You can use JLabel in the place of JTextField). What is not obvious here is that I used GridLayout and BorderLayout for the layout of the buttons.

By default, JPanel comes with a FlowLayout(It will be discussed in later posts). You can change default layout of a JPanel when you create a new JPanel by specifying in the constructors or you can explicitly call setLayout() method of JPanel. For this program, I used a mixture of BorderLayout and GridLayout. I used two GridLayouts because I wanted all numbers on the left side and all the signs on the right side.



So, we have the mainPanel which is holding all the different panels with different layouts. The mainPanel's layout is BorderLayout as I want to put the text field and the buttons on top of each other. And there's another buttonsPanel which holds two smaller panels : numbersPanel & signsPanel. The reason is that that two different button panels are different in terms of number and arrangement. buttonsPanel has also a BorderLayout because BorderLayout allows the two panels to be placed on left and right sides. And each smaller button panel has GridLayout which is self-explanatory.

You need to add the following 3 lines of code in the end to put everything on the panel.

buttonsPanel.add(numberPanel, BorderLayout.WEST);
buttonsPanel.add(signsPanel, BorderLayout.EAST);

mainPanel.add(buttonsPanel, BorderLayout.CENTER);

You will see that I created JButton and add an actionListener to it. I'll talk about it in my next post.

Monday, January 11, 2010

Hibernate : Deleted Entity Passed to Persist

I use Hibernate and Seam in my project. In using advanced technologies which were not taught in the classrooms, I had to learn about Hibernate mappings, Seam POJOs, EJBs and Java Persistance through books, Googles and other forums. Often, we ran into problems that we didn't know how to solve. Times like that we turned to Internet to find solutions. I ran into a problem last week that I was so dreaded of a few months ago. We thought we fixed the problem but apparently it came back and haunted us. Somehow, I googled for a solution and someone posted an idea on a blog that helped me solve my problem. So, I'm writing this post sharing what I learned and hoping that some one will actually find my post helpful.

This error that I was dreaded of was "Deleted Entity Passed to Persist" error. This is not the type or name of the error. It is what Java revealed in the logs and it can't proceed because of the "Deleted Entity Passed to Persist". In the past, we noticed that it happened when we tried to remove an entity from database by using entityManager.remove(entityname). For those of you who have worked with EJB will know what entityManager is. Basically it's trying to delete a row of data from database and it's doing so by calling an API.

Let's say I have an entity called Person and a second entity called Credit Card. A person can have one or more credit cards. So, we created a one-to-many relationship between Person and Credit Card. Person has become a table in the database and Credit Card has become another table in the database. Credit Card table has a foreign key column called Person_Id which stores the Id of the person from Person table. We created two way relationship.

class Person{
@OneToMany
private List creditCards = new ArrayList();

//getter & setters etc.

}

class CreditCard{
@ManyToOne
private Person person;
}

We put one relationship in Person entity and another relationship in CreditCard entity. (Note: the above code is NOT complete, you will need to ask other annotations for it to work properly). By doing so, you will see two way relationship, i.e, if you look from Person entity, you will see it's connected to Credit Card entity and if you look from CreditCard entity, you will see it's connected to Person entity. Now if you want to delete a credit card record from the Credit Card table, you need to first take out the relationships between the Person and that Credit Card.

We used to set the Person Id to 'null' and then call the remove() method from the EntityManager. But doing so gives the above error.

I finally found out the solution that nullifying a column doesn't take out the relationship in this matter. Since this is two way relationship, we need to take out that credit card from the arrayList in the Person table. So instead of doing entityManager.remove(creditCard), we have to do this :

person.getCreditCards().remove(c); // c is a credit card
entityManger.remove(c);

This is also a proper way of removing entities. You should get no "deleted entity passed to persist" error by adding an additional line of code.

Friday, January 8, 2010

Reality Vs. Customer Satisfaction

In enterprise IT world, there's always a debate between what's the right way to do things and what the clients want. What might please our clients might not always be the best solution. As I've been wadding towards my third year milestone of job experience, I've encountered so many situations where what our clients specified a requirement, we implemented it and later on they wanted to change it again. I used to think that as a service provider, I should always provide customers what they want. But sometimes, a firm objection (as long as you have a solid reason) is needed to avoid regular updating and changing of the code.

I'm writing this post in relating to an event that happened a few days ago, which is related to what I was talking above. In my project, we need to capture our client's information such as name, dob and etc. We also need to capture the marital status of each of our client. The old implementation was such that any clients under 16 will not be asked of their marital status. This specification has been requested by our analyst who left. For me, I don't think 16 is not a realist number for this situation. There're a couple instances where 14, 15 years old can be a parent. But he was the analyst and I thought he would have known better.

Now after one year since when the system has gone live, they started complaining about the age restraint. They started questioning why we chose 16 to be the limit. Honestly, I had no idea. So, after a few brainstorming, 13 was chosen to be the decision point. And we told our client that this will be the final decision and no further changes should be made about it. For me, I really didn't think 13 was the right solution. There is always something else.

So guess what? The other day they found out there's a 12 year old parent. It's a sick world. But it's the reality. My coworker did some search on Google about the youngest parent in history and 5 was the youngest one. (If you want detailed information , you can view here. ) Now the question is do we put 5 as the decision point instead of 13. Or do we take out the age restraint at all? Anyone under 5 could never be a parent. But you will never know in this bizarre and strange world. When it came down to user satisfaction, how far can we go?

Wednesday, January 6, 2010

JFrame



The last post was creating a very simple hello world swing application using JFrame, JPanel and JLabel. In this post, I would like to post a bit more about JFrame.

JFrame is one of the three top-level container classes that come with Swing. The rule of thumb is that each Swing application has AT LEAST ONE top-level container. The above figure is a JFrame and in this application, we have one top level container, which is a JFrame. In our JFrame, we have a menu bar(y'all know what a menu bar is) and a content pane(the yellow background). In a containment hierarchy, this is what the above figure looks like
JFrame
|
------- Content Pane
|
------- Menu Bar

Content pane can be customized and new components can be added to our original Swing application. In my previous example, I added a label to the content pane. We can call content pane directly from JFrame by the method frame.getContentPane(). But we used a slightly different approach last time. We created a JPanel component and then added it to JFrame. In my last post, I explained that content pane existed inside JPanel. It was my mistake to misuse the word since I'm using contentpane as a variable name.

What I really meant was that I was trying to create a customized content pane. when we call frame.getContentPane(), we actually get a container object, not a JComponent object. ( I will talk more about JComponent in my next post). Since I wanted to make use of JComponent features, I needed to either type cast or create my own content pane. In this case, I created a JPanel and added to JFrame, making my contentPane JPanel a content pane.

As I mentioned above, JFrame is one of the top-level containers. In Swing, there are two other top-level containters : JDialog & JApplet. Each standalone Swing application has JFrame as root container and each applet application has JApplet has root container. If we have an application that has a dialogue box, then there will be two top-level containers in this case, which are JFrame & JDialog.