Wednesday, September 29, 2010

Internationalization in Java - when is a number not a number?

The Java product I work on is internationalized and localized - well it turns out for the most part. I updated the code some time back to allow the user to type in numbers in their locale so a German speaking user can type 600,25 (notice the comma instead of a decimal point) and we should consider that to be 600.25 in English.

Two problems arose, the masked entry field I wrote handled this just fine allowing user to type in numbers using their locale settings but the code in others areas converted the typed text to a Double using Double.valueOf(text) and it would fail by tossing and exception. I switched the code to NumberFormat.getInstance().parse(text), adjusted to catch the proper exception and everything now works. This code area allows users to enter custom property values.


One thing I found out, NumberFormat returns a Number. That might be a Double or a Long. If you parse 85 you get a Long. If you parse 85.43 you get a Double. You can ask the Number for its doubleValue if you always want the double. I was getting a typecast error on occasion until I figured this out. If you send in an empty string you get a parse error. You may want to check for that before you parse to assign a default value of Double.MAX_VALUE to indicate empty or 0 if you want empty strings to equal a zero value.

Second problem came from the advanced search area where we allow users to search for previously entered data. We used the same masked entry control but never converted the output to a number. The server takes the search statement as a string so there seemed to be no need. Of course there is a need. The code looks a bit silly but I take the text, convert to a number and convert back to text so it will be in English format to send to the server.
String numOne = numberFieldOne.getText();

// We convert to a number then back to text for i18n reasons
// All numbers set to server in English format, this forces that rule
try
{
   numOne = NumberFormat.getInstance().parse(numOne).toString();
}
catch (ParseException e)
{
   numOne = numberFieldOne.getText();
}

Everything is up and running again. The company has a big push toward international expansion so it was critical that we solved these issues. I must say Eclipse pop-up help on methods is very handy. I viewed the pop-up for Integer.valueOf and it suggested using NumberFormat instead. I love it when you are handed the answer without needing to do a web search right from the IDE.

Converting existing code to i18n can be painful, making it i18n from the start and keeping it that way can be a big help. I will add this discovery to my i18n toolbox. Seems pretty rare for users to type in floating point values but it does happen and you need to account for it.

Monday, September 27, 2010

Why does Java paint different under different Mac browsers?

I understand there are differences between Java on a PC vs. Mac vs. Linux. We have code in place to check for each. Even some code for OS subsets such as some special code for Win7 and Vista vs. older Windows flavors. They added fancy pants painting to the combobox in Vista so my custom control paint needed to reflect those changes.

What gets me is I can run our applet on my PC under Chrome, Firefox, IE, Safari or Opera and it looks the same. All the colors match, buttons look identical, my custom controls paint exactly the same. I can see no differences.

Today I get a few bugs about things not painting correctly on the Mac. No big deal, I grab the development team's laptop, update the OS, update Java and install latest versions of Safari, Firefox, Opera and Chrome. Run Chrome as my testbed and fix the items reported by QA. Just an hour or so of pretty easy work. Then I decided to run the software to see if I spotted any new issues and I found some with toolbar button painting. I resolved those under Chrome then ran it in Safari. Background is a lot darker over the main toolbar but buttons are readable. Then I run it under Firefox and when you have a toggle button on the toolbar you can not tell which button is toggled. It gets a special outline and color in Chrome, Safari and Opera just not Firefox.

Safari on Mac
Firefox on Mac

The three right most green buttons are a toggle group, only one will be selected. They are fit to screen, fit to width and fit to height. On Safari you can clearly tell you are in fit to screen mode. Under Firefox you have no idea.

According to the Java console window that pops up as I run Java in each browser I am running JDK 1.6 update 20 in each one. I am not using any special paint code for this button, just using standard JToggleButton. I did not touch code in this area for my other bug fixes. I run an older version of our applet and it still looks bad in Firefox. Why does the JToggleButton paint differently in a JToolBar between browsers? Why is the browser controlling the background color of the toolbar in some cases? This is not how WORA is supposed to work. Of course I know WORA does not work between OS vendors or versions but I did not expect the browser to mess me up.

My other Mac bug was about things painting outside the custom control. On the PC in Java if you set a clip region outside the control you are currently painting it still gets auto clipped to your control. It was a simple fix, I just did an intersection between the current clip and the rectangle I was about to paint thus if it was out of bounds on the Mac I did not paint where I should not be painting. No Mac check, worked fine on PC with the intersection check. I did add a comment as to why the clipping is there and really it is the most legal way to handle things but it was the Mac that forced the work back on the developer, not saying the Mac was wrong, just the PC Java was friendlier.

We need to test more often on the Mac. It is an important platform. We have clients using it. Stinks that I have to dig down this deep to fix things and now I have a new problem between browsers that I am not sure how to even fix. Has anyone else run into the JToggleButton paint issue?

Wednesday, September 22, 2010

Two Java rotates - one works one does not (sometimes)

Why does this code not always work?
        g2.translate(translate.width, translate.height);
        g2.rotate((myRotate * Math.PI) / 180, 0, 0);
        g2.drawImage(image, 0, 0, null);

This code appears to work in all our test situation

        AffineTransform trans = AffineTransform.getTranslateInstance(translate.width, translate.height);
        trans.rotate((myRotate * Math.PI) / 180);
        g2.transform(trans);
        g2.drawImage(image, 0, 0, null);

This came up as a client issue. I did not write the original code but I was asked to help track down and resolve this rather annoying issue. When I run the old code on my machine it runs just fine. When we run the old code on a VM on another machine it works fine but running it as a servlet under Tomcat and it screws up and does not generate a rotated image. You get an empty rectangle instead.

The problem is now fully fixed but it just seems odd that the AffineTransform works where the standard rotate does not. You don't get any errors / exceptions. You just don't get a rotated image. We are going to run some timing tests between the two calls as we are curious which is faster. Of course faster and broken is broken so we will not switch back to the original code but we want to make sure server performance is not impacted massively with the new code in place. If this was client side processing we would be less worried but you still want things to run as fast as possible.

Tuesday, September 21, 2010

When all else fails upgrade the JRE

Another team was having issues with some image manipulation so they asked me to help out. They had traced it down to some code doing an image rotation. Code was very simple so no obvious problem. The code was happening in the servelet, get a TIFF, convert to PNG, scale it down and rotate it if the rotation flag on original TIFF was set.

Special TIFF (aren't they all?) so we use the 3rd party library from Acordex to load them and same them as a PNG. Everything there was working fine so I took the code out of the servlet and made a stand alone Java project. It worked perfectly. I wrote out the images to a temp directory at various stages.

I then created a JAR file with the test code so we could run it on the VM using same set up as the Tomcat based servlet. JAR did not run because I cheated to pull the 3rd party code from another JAR. Grabbed FatJar for Eclipse and built a new JAR with all the stuff I needed.

Worked like a champ on the machine of the developer I was helping. Put it on the customer identical VM and it did not work. Everything up to the rotate was fine but the rotate produced nothing for an image. Both I and the developer running JDK 1.6 update 21, the customer VM was update 6. Updated the customer VM to update 21 and it ran just fine. Did some searching for known rotate issues but did not find any. Figured the we have a fix for the customer so might as well let it go at that.

Update 6 is pretty old, don't think the custom is going to fight the upgrade. Anything below 19 is pretty suspect due to security issues anyway. I hate to blame the JRE first, always figure it has to be my code at fault especially when I am not doing anything out of the ordinary. Best be is to create a small test program if possible to narrow things down. Glad this one is off the books.

Monday, September 20, 2010

People will always use the tools they know

My son's school sends out a weekly PDF document of activities. I thought it looked a little odd but was not too worried about it. This week it came as a MS publisher file because they said the scanner was broken. From that I deducted the following steps were happening each week:

1) Create the newsletter in MS Publisher
2) Print it
3) Scan it as a PDF
4) Email it

Not everyone can open a publisher file, the PDF format is the way to go as the reader is free. Same reason I sent out our Christmas letter in PDF format. The oddness came from the PDF I got being scanned. I knew it looked grainy but was not sure if that was a look they intended. Some like the whole retro thing.

I sent the principal a note that they can just get a free printer driver allowing you to print from any program directly into a PDF skipping steps 2 and 3 plus giving you a much nicer looking final product for the email. He just responded that he downloaded the program and it worked like a champ so they will start doing things that way from now on.

Happy to be able to help the school out as they do so much for my kid and all the children that attend.

It always amazes me to what extremes people will go with the tools they have. Not every fix involves a download of something either. Just knowing a different formula in Excel can save hours of manual labor.

I photoshopped a picture for my son's birthday cake. They said bring in the picture, I asked can I bring in a CD or a USB key. I was told they can only scan images so I had to bring in a hard copy picture. I have a feeling that is not really how it has to work but I gave up and printed the picture and gave them that. The cake came out fine, a printed image slapped on icing is going to look fuzzy anyway but I have a feeling there is a way to pull this off without a scanner. Silly image ends up as a JPG in there somewhere why not just start out with that as the source?

Not that I have never done the same sort of thing, taken way too many steps to do a simple process when someone that is an expert in that area could have trimmed it down to two mouse clicks. I bet I did a lot wrong during my photoshop session with the picture. Happens when you don't do something very often but as so as I have to repeat a process the first thing I think is "Computers are meant to handle repeating tasks, I will figure out a way to bend a computer to my will" and I usually do. Sometimes you give up totally, other times you give up and then one day read something on the internet that reminds you of how stupid your process is and you fix it.

Monday, September 13, 2010

Android - too early or too late?

I really want an Android phone so I can write some Java code for it. Is it too early or too late to do that? Tech moves so fast you hate to get stuck with a $500 device that is outdated in a few weeks.

Too early - they keep updating the OS. 2.2 is out now, talks of 3.0 and a "new way of doing things" on the way. Will all 2.1 and earlier phones be left out in the dark? I think the talk of fragmentation is a bit overboard but I still worry. I can get a PC and update the OS pretty much at will. Seems like you are partially held hostage by your phone vendor. When will Samsung release 2.2 for the Galaxy S series? Will they fix the WiFi vs. 3G issues? How long before they abandon this phone series totally?

Just when I am about to pull the trigger I start to do some research on the Galaxy series and see it has various WiFi issues. It will stay connected if plugged in but not if on battery. Wants to hit 3G when you have WiFi. Look I am pretty cost thrifty. I would not even get 3G service, I want the phone to be a phone, do texting, play some games and let me write some code for it but I don't want to pay for 3G. I am around a WiFi network 95% of the time. I would buy the phone outright and not do a service place which I hope means I will not get hassled at purchase time.

My wife has a Blackberry without a data service plan, she uses the calendar part of it for everything and the keyboard for texting. There are times a little 3G access would do her some good, she calls me and has me look up stuff on the internet a few times a month, but is it worth an extra $30 a month to avoid that? Everything in life is just another $10 here and $30 there so you have to draw the line. Guess that is why I don't play WoW, adding another monthly expense and the fear of addiction keep me at bay.

Too late - lots have already bought them. Are my programming ideas too late to the party to be worth anything? Coding for a mobile device seems to be the wave of the future though. Having that programming experience has to pay off. Probably better to get on board now rather than totally miss the boat.

I have downloaded the Android SDK and Eclipse plug-in more than once and have installed it on my main machine at home and a laptop I use from time to time. I know I can start coding against the emulator but that thrill may run dry quickly if I can't run it on a real phone. I would not want to write something and release it in the wild without testing it on actual hardware. If I am to get into the game I need to buy the equipment. It is a $500 investment in my future. I could sit down and write code to see what I think of the SDK and then when my first game is done I will have to buy a phone right?

Second worry is the wife will play with the phone and want one too. They have a special going now if you rent to own one you get one free. We are doing a "no plan" deal now to save money, the only way to get a "free" one is to go onto a 2 year plan. Would I get back that difference by being on a plan? I wont if they force you to a 3G data plan. There is no doubt she uses more features of the phone than I do and I bet she would prefer this over her Blackberry. Not looking to spend $1,000 outright to get two with no plan.

I have an iTouch at home. It gets a lot of use for quick and easy web lookups. Instant on is wonderful, being able to use it nearly anywhere in the house is perfect. We keep it by the bed at night so we can check on the weather when we wake up so we know how to dress the kids for school. I was watching football updates on it yesterday. My son uses it for homework, easier than a laptop when you are sprawled out on the floor. The Android would add to that experience as it appears to be a very similar device. Not that we fight over time on the iTouch.

For now I am going to follow the Galaxy forms to see if Samsung fixes the issues with the 2.2 update or some other patch if it is a firmware or driver issue. I need to sit down and write some code in the emulator too and get myself all pumped up for owning one.

Friday, September 10, 2010

Win7 Taskbar - I like it but they forgot things

To speed up my C# development process I pinned the EXE of our project to the Taskbar of Win7. How does this help? When I press the (>) run button or hit F5 in the IDE it does another build process to make sure all the stuff it needs is in place. Waste of time when all I did was make simple code changes I want to test and am pretty darn sure there is no debugging involved. I can always attach to the process if I want to debug anyway.

So I pin it, easy to do, but it has the ugly generic icon. I could go and change the icon in the code to solve that but we have a deal with our UX team, no icon before its time. If it is ugly and generic or it is a standard [?] image then everyone knows UX has not designed and approved an image. Company rule, I just follow it.

Next step, Windows has always allowed you to assign any icon you like to a program. A lot of programs, MS Office comes to mind, have a number of icons included in their main EXE. I try all sorts of clicking on the taskbar to try and get to a properties so I can change the icon. No luck. Hit Google and search the web and find out you need to navigate to the following directory (with your user name of course):

C:\Users\kpeck\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar

Then you can right click on the shortcut and adjust the properties there. Dang MS, why the heck is this such a pain in the behind? I like the other changes to the Taskbar but this is about as old school as you can get. Hate to explain to my mom how to change an icon on a very visible part of the user interface.

Next I had to go find a suitable icon so I found one of Bender from Futurama. Sure I went from a generic icon to one that has no association to my application and spent 15 minutes doing it. What else do you expect from a programmer? Sometimes you just have to stop and figure out a solution to a problem even if the end result is close to pointless. My guess is the info will come in handy in the future, this sort of knowledge almost always does.

Tuesday, September 7, 2010

Why Java beats C++ and C# when you really want to be productive

I have programmed in a lot of languages over time and the one I always come back to when I want quick productivity, notice I did not necessarily say quick run time, is Java. Why would that be?

First off you can just start typing your ideas and get the program running quickly. In C++ every time you write a few lines of code you have to think about writing the anti-lines too. Create it and clean it up. C# is a dead tie with Java here usually. The one are that gets a little annoying is being in the Dialog editor, clicking on a control, click on "OnClick" event and having it pop you back into editor to write the code. There are a lot of times I know I want "OnClick" events for 5 buttons on a dialog, I don't want it switching to the editor over and over. I want to stay on the Dialog until all 5 stubs are in place then I will do my code editing.

I have done a lot of code reviews. When we reviewed C++ code you could take a single CPP file and find all sorts of issues - potential memory leaks - unnecessary string conversions - etc. Reviewing Java code means looking and how multiple objects interact. Basically the language eliminates the chances of making a lot of stupid mistakes. It cleans up memory usage, there is only one String class. This allowed us to look at the architecture instead of just the syntax. I was not doing C# when I was doing C++ vs. Java code reviews but I have a feeling it would be very similar to Java.

If I need to do a simple dialog box to say open a file, read in settings and allow a user to change settings and save them back I use C# / WinForms. The only reason for this is WinForms makes it so easy to lay out a dialog box. Not that Java is super hard but you have to think about what layouts to use, how to lay them out in relationship to each other and write all the code to create the controls and panels. I do it all day long but that does not mean I enjoy it. WinForms is a clear winner in this area for me most of the time. There are odd anchoring situations that WinForms can just not handle where a GridBagLayout of MigLayout in Java are coded with ease.

When you get into C# / WPF you are basically back in the Java world. Sure there is an editor but it is not the most friendly thing in the world. Add to this you are looking in two files, XAML and CS, to keep it all tied together and you lose a little bit to Java side as a programmer. I know the XAML split makes it much easier if you have a designer and developer working in tandem. In the end it is probably the correct way to split the presentation from the code and data.

C++ has a Dialog editor of course but it stinks when you need to resize and move controls about. Then you have to deal with MFC on the back side which is really a terrible thin wrapper over the Win32 API and it is not object oriented. MFC has a very limited set of controls and they are hard to customize adding to your pain. When I was doing a lot of dialog work with a team in London I would do all the prototypes in C# and after many meetings getting the look hammered out I would convert it to C++ / MFC. This seems to be a great approach as WinForms allowed nearly instant tweaks so I could send a prototype back to them in the middle of the conference call which would have taken too much coding effort to pull off in MFC.

The one huge issue that hits home once a project starts to grow in size is compile time speed. In Java using Eclipse the program is basically always built. You know all the compile time errors instantly and when you hit run it just runs. Even the web project I work on, which takes an extra step to build jars and deploy them to Apache Tomcat, is an ANT script I wrote that takes an average of 8 seconds to build 4 jar files totaling 6.4 meg. That allows me to update code, JAR it and test it in seconds. We have multiple projects that share the same common Java code. I keep them all loaded in Eclipse so I instantly know if any code changes I make in the common areas break other projects.

The C++ project takes 45 minutes to build. We have build errors nightly on that project as people build and test small parts of code but don't build and test the whole thing. Who has time to do that more than once a day? Plus if there is shared code you have to build multiple projects to know if you broke other areas. That pretty much never happens.

The C# project, which is barely functional as we are just getting it off the ground, takes 5 minutes to build. I really feel the wasted time. In Java I stay in my constant coding cycle all day long. I rarely mess with the C++ code. For the C# cycle you get bored waiting on the compile so you check out a blog or other websites while you wait then you forget to check back to see it is done building. Finally you get to test your code if you can remember what you were even trying to fix 10 minutes later. This project is being written in a modular manner with various DLLs and a single EXE tied together using MEF. This adds to the compile time as files due to HD access for all the file copies that are going on. I am sure this could be sped up. Stand alone smaller applications I have worked on in the past seemed to build a lot faster, nearly Java speed.

It can be a wash at the start of a project when you are writing large amounts of code between compiles but let's say you are trying to tweak a small area of fix a little bug where the debugger is just not giving enough info. I ran into this when dealing with the 3rd party license issue with C#. Add two lines of code, build, run, try again. I have done that plenty in Java but it became quickly painful and very unproductive feeling in C#.

Java wins for being the most productive over the life of a product. Plus it runs on multiple platforms and I can use it write stand alone applications or Web apps. It is not the most friendly for building the initial UI or Dialogs but it is very flexible in this area and all your dialogs are resizable for (almost) free allowing for easier internationalization.

C# / WinForms wins for small dialog based products. Quick to layout and quick to build and test. Best used for standalone apps. Harder to internationalize as the localization folks need to touch every dialog. Limited to one OS.

I feel like I have the most control over the look and feel in C# / WPF as you can get very fancy with very little programming effort. Every control is custom draw because even list box elements can be a panel with anything in it you want and data binding is very easy. Can be used for both stand alone and Web apps although you switch to Silverlight with it owns set of special limitations to go that route. I have a feeling all the flexibility will cause things to run slower as the application grows. There is always a penalty to be paid for eye candy.

Expertly written C++ can be the winner for stand alone applications if you want pure speed and want to be able to use every ounce of the OS you are running against. You can talk to every device hanging off your system or network. There are times that needs to happen but those times are getting rarer. You can use QT for cross platform. I don't think many would choose C++ for Web apps. You do pay the price at development time, harder to find and fix bugs, longer compile times and older tools across the board to help you out. Great language for a lot of uses, always handy to know how to read it.

So there you have it, I like Java the best right now. C# / WPF might grow on me if we can get in there and optimize the compile time and delve into all the flexibility with a designer by my side . C# / WinForms seems to have its uses but is not the direction MS is going at this time. C++ still has many uses but is not where I would start to write smaller utilities or to write a fancy pants UI.

Thursday, September 2, 2010

It's Alive

Finally have the DotImage code working so that QA can actually see an image from the nightly build. What a pain. The Atalasoft team was very helpful and between their suggestions and some tweaking on my end we finally have it working today. Took nearly a full week of tinkering which is not very productive and hopefully someone will not accidentally make a change that screws it all up in the future.

On a totally different topic: I don't often buy things just for myself but I just wanted to get the Starsky and Hutch Gran Turino and the original Batmobile from the 60's TV series in 1/18th scale for my computer desk collection. I found them on-line for a reasonable price and they arrived today.

The Gran Turino has the slap on police light on the top, proper paint and rims. I know I bought the glue it together yourself model kit as a kid. They never had the real car as a kit I could find. As close as I got was a Chevy Nova, probably was a Gran Turino out there but I did not know enough to tell the difference at the time. Sure I got it at Alco in Salina. I painted the stripe, I bet it looked like crap, and I remember I painted it across the trunk instead of over the roof. The next week when the show was on I had noticed what a screwup I was and I had to repaint my stupid model. Bet it made it look twice as bad as I just painted right on top of a lousy paint job with a second lousy coat. I know I used masking tape for the job and I am sure I pulled off some paint in the process but I had my Starsky and Hutch car.

The Batmobile is a model I always wanted as a kid and saw at the overpriced hobby store in the mall in Salina every time we went in there. I still have this car in 1/64th scale as a hot wheels car and have always loved it. Just verified it is in the hotwheels case right here in the computer room closet. Cheesy as they come but man I wanted that car in a larger scale. It was my goal to ask Grandma Peck to buy this for me if she ever came to town but it was out of the proper asking for a gift price range. The one there was a 1/24th scale and sat in a special display case. Don't know the price, it was probably around $40.

Every car I have has a story and I just needed to add these stories to my collection. Trevor and Spencer thought they were pretty cool. They also have the Duke's of Hazzard, KITT and the Trans Am from Smokey and the Bandit at the same store, maybe another day.