Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

2018-02-05

The "Java is dying" tale

And there was it again... - somebody (in a Java group - strange enough) told that Java is dying. Uff! - I hear this for years now - and it gets annoying to hear or read this again and again (of course of the people who don't like - or simply don't know Java).

Nevertheless, Java ranks within top 3 programming languages on whatever index you look!
But probably you should also consider, where you live, because there are statistics over countries which shows that most important language depends on country - e.g. here:
https://blog.hackerrank.com/which-country-would-win-in.../ (Java is there first for Poland, Python for Hong Kong for example).


Oh - this article (even if older) already talks about the Java is dying tale: https://jaxenter.com/java-slippery-slope-downward-trend...


What makes Java still a very important language and still very attracting for newbies, is the wide field of usage - from desktop over web and not finished at mobile development. Especially when searching for a first language to learn which can be used to do it all.

Another fact is, that there are many open jobs (at least here in Austria) for Java Developers at the moment - so knowing Java currently helps if you need a new job...

Related posts: The programming language discussion, Java vs .net/C#, Choosing a programming language, The programming language, Popular Java myths.

The programming language discussion

And there it is again - the programming language discussion - Not a single developer forum or group that does not have it at least once every month.

Don't get my wrong, there are many good programming languages out there many are worth to be learned. Although I learned many through the years, I know very well that one cannot be expert in a lot of languages. You can only be an expert in that what you use often. 

Sometimes I need to look into old VB Classic code and after a while I am back into it - but not coding in the same speed as back then when I used it on a daily basis just because of the fact, that I don't remember well all the libraries and their functions I wrote back then.

When the programming language discussion comes up, the arguments are about what is the "best" programming language or what is the most "widely used" language. But I consider this being secondary priorities.

Learning a programming language is an investment!

You need to consider, what are your needs and learn what will bring the best return on investment for you!

I found the following strategy being very useful:
Have one primary programming language - or at maximum two - that you know very well and basically can be used to solve all your programming needs (batch tool, server daemon, desktop application, web application and mobile application in best case). Then have 2 or 3 programming languages that you can use for particular needs in special cases where your primary language is not so good at.

Choose wisely the programming languages you learn!

Related posts: Choosing a programming language, The programming language, The IDE and the libraries, The "Java is dying" tale.

2015-07-23

Java vs .net/C#

Visual Basic Classic was my primary programming language for many years. A pretty amount of years ago when Microsoft announced the end-of-life of Visual Basic Classic (one of the last statements regarding VB6 see http://msdn.microsoft.com/en-us/vstudio/ms788708.aspx) I took a first look at .net and C# as it seemed to be the most logical next step. I was deeply disappointed by the first versions of .net and C# (it was v1.1 if I remember correctly - it was so full of bugs and terrible slow). The next shock for me was the absence of any migration path for the existing VB classic projects. So switching to .net would have been a total restart. I really wondered about that step of Microsoft because pretty every software vendor knows that a hard cut in backward compatibility of software comes with the danger that customers start taking a broader look around to competitors.

Due to the fact that I already had switched from Windows to Linux at home at that time, I thought by myself, that this would be the opportunity to learn a completely new langauge which is platform agnostic and enables me to write applications that run on both environments. Using a computer I can't program (the Linux box at home) was a horrible situation for me.

About a year later, after several evaluation phases and another attempt with C# to give it a second chance, I decided to go for Java with two core advantages (apart from the language specific reasons):
  1. Develop once and run the binary anywhere - on Windows, Linux or even Mac.
    Yes, I know the critics, that Java or other attempts following the "write once, run anywhere" paradigm do not deliver this promise (see comments on Wikipedia to cross-plattform development for example). Now, years later and after a few applications developed (commandline, server, Swing rich clients) my experience is very good. Of course if your development machine runs Windows and you use Windows API exits or use com4j, J-Interop or JACOB to interact with a Windows-only COM component then you will have problems running it on Linux or Mac. For example: I have developed a Swing application that worked flawlessly on Mac even although I did not have any possibility to test it (I do not have a Mac). I was used to get problems with windows only applications just trying them on a new version of Windows! Of course I also had some compatibility issues e.g. when stripping invalid characters from filenames (different characters are allowed and not allowed on the two systems) or checking if a file is still accessed (there is no windows-like file locking on Linux) - but these are differences in architecture of the operating systems and that can be handled. You can develop for many platforms also using C++ for example but then you need at least one instance of each operating system at your fingertips to do the compiling work.
     
  2. Reduce dependencies
    You already run a risk choosing a programming language. You have a learning curve and invest into know-how, library development and maybe also buy some external components - not to speak about the related tools you learn to master (IDE, packaging, deployment, ...). But this is mainly your own risk. The even bigger risk is for the customer using your application when it is not plattform agnostic. I have seen companies trying to migrate a few servers to Linux and were stuck because of software running on Windows only. You don't know which operating system survive for the longer time. With a platform agnostic solution you just don't care. It's a matter of flexibility.
I can see further advantages, like choice of IDE or missing licensing issues (Visual Studio license usually provided by the employer and when you leave you have to find a new sponsor).

Having now the choice between several IDEs I first used Eclipse (free) and moved to NetBeans later on (also free). The book, which was most helpful for me in learning Java (Javainsel) was and is very good (sorry folks, it's german).

The biggest advantage of Java - being platform independent - also is the biggest obstacle in a (still) Windows centric (business) world: To ensure plattform independency (as I explained above) means, that you should only use and do stuff that is available everywhere - or you need to implement to different solutions. The resulting problem is: How to deal with the Windows specific stuff?

My solution to this problem is in the first place to not use OS specific exists or use calls to Windows-only stuff. For applications that need to integrate with Windows stuff I try to keep the OS dependent part small (e.g. a VBScript) and let it communicate with the Java program via commandline, over the net or by saving files to watched folders. For example: To get the active window title under Windows the Windows API is a possible way to go while on Linux there is a commandline tool called wmctrl which can do the same. So under Windows you would write a small Windows program that uses Windows API to to get the title of the current window. Probably the easiest way is to write an AutoIt script which has a prepared function for this and let it return the Window information in the same way as the wmctrl program does on stdout. Your program then - depending on the OS it is running (you can find that out during runtime) - calls either the one or the other commandline tool grabbing stdout of the called program. So it is recommended, that you try to reduce the OS dependent parts to a minimum and split your application into components - and the smaller OS specific part finally needs to be developed twice or three times.

It was and is one of the core arguments of those developers on Microsoft (.net and C#) that they are bound to Windows anyway because they deal with so many other Windows-components. Yes, this is partly true and I do still a lot of Windows-specific VB scripting. But I always think in components and so there are several opportunities to write parts in a platform agnostic way. Even if it is not yet totally platform independent - later there is less work when an OS migration is needed. If you look at the trends of the last years, you can see one big related trend: decoupling or "loose coupling" of components (from COM and DCOM to SOAP and REST). Lately I read more and more about "Micro services" which - frankly spoken - is just a form of component oriented design. Anyway, that nowadays makes it possible to have processes on different operating systems written in totally different programming languages talking to each other.

In the meantime I also improved my C# knowledge a little and developed a few smaller things in C# where it did not really made sense to do it in Java. There are a few people dealing with both languages. Interestingly those people criticizing Java most are usually those who don't know Java and have never ever looked into something else but the Windows world.

Although Microsoft had the chance to create a "better" Java by learning from it, they did many things worse in my opinion. Many say that the .net libraries are better organized than the Java ones. I do not know the .net libraries very well yet, but I tend to agree. On the other hand there are a many characteristics where I prefer the Java way, for example:
  • Properties (C#) vs Getter and Setter methods (Java)
  • Delegates (C#) vs Passing interface implementations (Java)
  • sealed methods+readonly variables (C#) vs final - one word that says it all in both cases (Java)
  • Missing checked exceptions in C# - a Microsoft guy once told me that checked exceptions produce just bloated code and therefore something like this does not exist in .net. Well folks, it is about error handling - something, Microsoft may not care a lot about ;-).
  • Ă„hem, want to talk about GUI development? - Windows forms or WPF? - Both seem to be unfinished I did not figure out yet, which of those will remain unsupported sooner. At least silverlight is dead... - I went for Windows forms so far and even for a quite simple GUI I was stuck with the shitty TreeView and a double-click-issue - bug report from 2009 and not fixed yet...
In general Java is easier and simpler (less language constructs - not the libraries) in my opinion, but sometimes there might be more code for the same thing, but who cares? - It is important at the end, that you don't refuse touching again your code from a year ago (not to speak about the code of others ;-) ).

I will continue to do a increase my C# knowhow, but I'll be always more confident when I can open up NetBeans again and working on a component in Java.

See also: The programming language, Choosing a programming language, Popular Java myths.

2012-04-05

Choosing a programming language

Currently - after a very long period I am again into the programming language decision which I was not expecting.

Changing programming language is a big deal and you shouldn't do that every 2 years. When you search the web you will find recommendations to learn many languages and learn a new each 2 or 3 years. I find this totally silly. To get really productive with a programming language, takes at least a year and of course you would like to get the most out of it regarding ROI (return on investment).

When I did evaluate programming languages the last time, it was a 3-step way:
  1. Collecting all options with the result of a hand full remaining for further analysis.
  2. Keep an eye on activity and evolution of the results from step 1.
  3. Detailed analysis of the remaining options and choose.
The time from beginning of step 1 until end of step 3 took about 2 years. During step 1 I already decided on a few parameters, which in my case were:
  • I prefer static typed languages over dynamic ones for several reasons (e.g. less error prone, YMMV).
  • I don't want to code user interface - I have coded GUI since I was an 8 year old boy and I was about 14 when I got GUI designers (those times still using MS DOS) so hand-coding GUI is for me like returning to stone-age and so that is a no-go for me if a GUI designer is missing.
  • I don't like language hopping and because of the very dynamic requirements of my software projects I need a programming language that can be used for quite all realms - so all the domain-specific languages are excluded for my needs.
  • My applications are usually plugin/addon enabled which means that a customer must be able to develop those for special needs on his own - without additional costs. That means, my favor goes to languages that are free (and open source) including the IDE used for development.
  • The language should not be tight to a particular operating system.
My decision - taken back in 2008 after many years of classic Visual Basic development on Windows was: Java together with NetBeans IDE, using Swing GUI for desktop applications (NetBeans itself uses Swing - however, there is another option for building GUI in Java: SWT). A short comparison Swing vs SWT can be found here. Back in those days I have already blogged about my decision, you might want to read back to "The programming language" and "The IDE and the libraries" maybe. The Swing GUI is - by the way - far superior to the .net WinForms or WPF - both do not adapt well to very different text lengths in labels (just to give one example - in Swing this works without additional work in full automatic). Another core advantage of Java in general is: You take the binary and it runs everywhere! - C++ and many other languages at least require the same code to be compiled on each platform. What if I want to develop for the Mac and I don't own one? - I have given Java apps that I have written to a friend for testing on his Mac and it worked - without me ever testing it on the Mac. Of course if you call system programs dealing with the output you may see differences in the behaviour on different operating systems that you have to deal with. The most annoying thing in Java is that you need to ensure that the Java runtime is installed on all the client PCs where you want to use the app. Of course no difference to Microsoft's .net here - although there is less version quirks than for .net...

Now, about 4 years later there is nothing wrong with my decision. My decision is still that. With the rising of alternative operating systems the importance of Java has gained (on the server side Windows definitely already lost for enterprise applications at least) and many server-applications go Java to be platform agnostic. Apart from that the Java world is huge. Microsoft's .net is growing also, but still far from that (regarding size and quality of libraries and community).

The trigger for my latest search for a programming language is that I have a few very small programs (running on the client) to write (they are not "real" applications, just tiny programs for particular small needs). I found Java - and .net or Mono as well just too big for such tiny stuff. In my particular case they are Windows specific needs. A few of those needs I already solved by just writing VBScripts. That was ok for the GUI less needs. Now I have a few little needs for small GUIs. And that again brought me to a brief look around.

And indeed that is the single parameter ("should fit for very tiny requirements also") I did not include in my former decision back in 2008. And good it was I think because finding the programming language that fits for really everything 100% is not realistic. It is even not realistic to think that a programmer nowadays can survive just knowing one language - but: It is important to keep in mind that no one can achieve the same level of expertise in all used languages.

So this post can be seen as an addition to my main pro-Java decision - the programming languages that are helpful in addition to Java.

For Windows development you should know VBScript and on Linux shell scripting or Python or Perl for the small scripting stuff.

But what to choose, if a little GUI is needed?

If you search for a platform independent development platform, you could look at Free Pascal and Lazarus IDE as it creates native code (so just take the executable and run it instead of writing packages or setups that manage plenty of dependencies) and is fast. There is one problem with this approach: On Windows (in my case) using COM components (not to talk about .net) is not well supported and possible only with quirks (not tried myself, I just read about that). That is the reason why this is not an option for me in my current situation. If your application does not need to tightly integrate into the Windows ecosystem Free Pascal gives you multi-platform development (same code, just need to be compiled for/on each platform).

After all, still core technology is C(++) and Code::Blocks is an IDE available for all major platforms (for wxWidgets projects the wxSmith seems to be the most capable GUI builder, you need separately install wxWidgets - at least on Windows). Or anyway you can either use NetBeans using external designers to build the GUI for Linux development. I have developed quite a lot C++, but maaany years ago and today I simply had problems getting Code::Blocks to work seamlessly with wxwidgets (design worked, but compilation finished with configuration errors). What I found on the net related to my errors was from about 2008 partly not matching my environment. I gave up on this but for those succeeding I want to mention this option.

Last but not least I still also see the option to use SharpDevelop with .net for the single reason of time-to-get-started and seemless integration into the Windows ecosystem - and this combination by the way is the only mentioned one that is bound to windows only. If you think of Mono and MonoDevelop then be warned about the differences! Creating platform independent applications with C# is not as seamless as you might think! Using  MonoDevelop on Windows (MonoDevelop can compile against .net or Mono) brings more platform independence but you loose the Windows integration (COM/activex support at minimum level - I find the Java-COM-interop even better; registry access and stuff like that). The very important point here is the Windows integration - it's the one and core argument for this option!

I was about to write a paragraph on speed but didn't want to write that without a single test after more than 3 years of not checking that. Surprisingly a minimum GUI test lead to the following result: Cold start on a virtual Windows 2008r2 machine is 5 seconds for both - .net as well as java. A second start is 1-2 seconds - either for both. I then tried a Java test application with a little more GUI to find out that (warm) start is 4 seconds - not bad either. Surprisingly Java 1.6 update 30 and .net runtime 4.0 seem to bring a similar user experience at least from startup behaviour. Many still say, Java is slow - far missed!

But I may not forget that I need to access activeX/COM components for my small work which makes it more feasible doing it with .net because .net simply integrates better here - as already mentioned. Of course there are options when using java - for example - my favorite com4j (which I tried for several COM components in the past where it worked well). Although I never tried to embed activex controls into a swing component - and that does not seem trivial in Java - see here.

Needless to say that I would prefer Java for 100% of the work if it would be easier to deal with COM components and if it would integrate nicely with the Windows stuff. Java with NetBeans is basically the only combination that I really love to develop with. Everything else lacks in IDE features, is difficult to set up or the community is small and tiny amount of available components.

And of course there is my general tendency to avoid Microsoft technologies whereever I encounter them. The classic Visual Basic was one of the longest continued stuff of Microsoft, even although there were signifficant changes between VB 3.0 and VB 4.0 (with switch to 32 bit). When I look at the last years there were unusable first attempts of .net with first Windows forms and then WPF (see a discussion here), Microsoft pushed a lot of newer GUI styles over the years with Ribbon interfaces or now the Metro GUI where you need to use a new GUI language and software companies continously need to adapt or rewrite parts of the application). Would I have used Java since the late ninetees I would have experienced a completely different continuity. Microsoft managed it very well, to drive developers .net without those getting aware that they are again caught in a one-way-street with a dead end. Just because industry follows Microsoft - at least on the client side - in most areas, I need to accept that I can't stay completely outside the windows specific (VBScript and .net) stuff. I will take care to keep it at a minimum. This means, that for my tiny programs I will most probably go with .net just because of the lack of other options.

For those who like dynamic languages, I want to mention Python. One of it's core advantages in my opinion is that it runs on many platforms but comes along with Windows extensions on Windows. This means: When you need to do Windows stuff you can continue to use Python - of course using the Windows stuff (COM and Windows API for example) means that (at least that part) of your program is then bound to Windows-only use. For platform agnostic programming there are bindings for wxWidgets for Python. However, the IDE's I tried were all poor in features or stability - I tried Eric, SPE and Idle back in 2008 - a short look tells me, that there is still a lack of GUI designers (e.g. Glade for Windows seems near to discontinued) - so I cannot really recommend a particular IDE - you can have a look yourself - here is a list of Python IDE's. Unfortunately deployment for Python programs on Windows is not as easy as for .net or Java.

To round up this post: For building setups for your Windows applications I can recommend the Innosetup application as a good mix of flexibility and ease-of-use. For creating Linux packages see official documentation for creating .deb packages (Debian, Ubuntu, Mint, ...) and here for creating .rpm packages (redhat, Fedora, ...).

Related posts: The programming language, The IDE and the libraries, Install NetBeans on Ubuntu 10.04, Java vs .net/C#.

2010-12-10

The community

In the last months I have been a participant in several communities, forums and the like. And I also have left some. I want to share some experiences:
  1. The community behind a software product (or any other thing) is a crucial factor for success of the product and motivation of the members.
  2. The spirit of the community is important. For the Ubuntu community (to give an example) there is the code of conduct to which most members admit to. It is the philosophy behind the group, a big picture that holds the people together.
  3. Nobody knows everything. With the contribution and help of each single community member the community gets smart.
  4. In good communities, members focus on the matter, not on blaming other persons or other products - their main target is to solve problems. Of course I like that. :-)
  5. In good communities it is easy to get involved and it is easy to be integrated (if you handle the members with respect).
  6. In good communities you are respected and your opinion is valued.
  7. There is a mass contribution effect in larger communities: While a company could hardly finance project teams with more than 30 or so members, in a big community there are many people adding value - even if it is a small contribution for each person, those contributions some up to enormous results.
There are two communities that I am proud to be in - the Ubuntu community and the Java community. I do not only participate in forum posts etc - I am also attending local events. Those events are usually very interesting from the technical point of view and also from the way community members deal with each other.

Don't forget, that no product and no system can be successful without the people behind it! - It's all about the people!

Related posts: The Open Source idea, The Open Source movement, Paying for free and Open Source, User lock down, Going Linux, The future of Java, Popular Ubuntu desktop myths.

2010-11-14

The future of Java

The last months (after Oracle has completed the merger with Sun) were full of insecurity and discussions within the Java developer communities about the future of Java. Many have blogged about their fears. I personally followed the discussions but I felt, the best thing is to wait. People are so fast with their interpretations and guesses how others will behave.

In parallel there were discussions about Apple stopping support for Java on the Mac etc etc.

Even although Oracle already told they are strongly commited to Java, NetBeans and other famous Sun products, discussions were going on.

Finally a few further commitments have come to public:

IBM joins OpenJDK
http://blogs.sun.com/mr/entry/ibm_to_join_openjdk

Oracle and Apple Announce OpenJDK Project for Mac OS X
http://www.apple.com/pr/library/2010/11/12openjdk.html

This means, that big players decided to go the Java and Open Source path. And it is important to unite the forces. Working together is far better than fighting each other.

When I decided to switch away from my Windows-only-development, one major reason was: There are many other operating systems gaining market share, like several flavors of Linux (Ubuntu, Mint, Redhat, Debian etc) and Apple - and I can't say for sure which ones will be there in the long run, but I want to provide security to my customers, that they can benefit from the software for a long time. - Java was a good choice in the past and now we can again be sure that it still is a good choice. The idea of Java - "write once, run everywhere" - has saved me from a lot of work in the past (compiling for different architectures not required, no building of different styled setup procedures etc). There are people mentioning that the write once, run anywhere phrase is not quite true, because not available for really all operating systems and often there have to be exceptions made for dealing with different operating systems. - Well, this is partly true, when it comes particular features, that might be even not available on all operating systems. Fortunately for such cases Java can be coupled with C(++). For availability: Java is available on more operating systems than most other languages (see http://www.java.com/en/download/manual.jsp).

BTW: C(++) is also a language, that is around and will be around for a long time and I hear nobody complaining that it is developing too slow for example. And I really prefer thinking carefully before putting new features into the language. There must be many things considered. It is important to do no harm to the language.

Oh, there is finally also an official podcast from Oracle for Java developers:
http://blogs.sun.com/javaspotlight/
Of course this is biased and the Javaposse (http://javaposse.com/) is still the first address when it comes to Java podcasts.

We have exact plans for the next versions of Java:
http://blogs.oracle.com/javaone/2010/09/plan_b_wins.html
http://openjdk.java.net/projects/jdk7/features/

And we get exactly what we need next for NetBeans (the first-class Java IDE):
http://netbeans.dzone.com/nb-generate-simpler-rest

Related posts: The dawn after sunset, The programming language, Popular Java myths, Java applications on the desktop, The community.

2010-09-26

Install NetBeans on Ubuntu 10.04

Why should one do a description of installing NetBeans on Ubuntu - it's in the repositories and just a few clicks?

The reason is: Installing it through the repositories you will get problems later when trying to upgrade NetBeans with the builtin-update tool. Apart from this I prefer to download the full package from http://netbeans.org/downloads/index.html and deactivating the modules I do not need - at the moment. I always make sure that the sun (or now Oracle) JDK is installed (there were problems in the past with OpenJDK - and although they should be solved I still go with the Sun/Oracle one.

Preparations:
  • You can install the Sun/Oracle JDK through the repositories or do the manual install.
  • To make sure, the correct Java is used, install galternatives (then available through Applications-System Tools-Alternatives Configurator) and then go through each item in the list on the left. There are quite many Java related tools that - after installing the Sun/Oracle JDK now offer that one as second alternative. For all the Java related tools select the new alternative from Sun/Oracle JDK.
  • If you manually installed new JDKs - e.g. after an update has been released, you might have to change the symlink accordingly at /usr/lib/jvm/java-6-sun using the ln command, eg:
    cd /usr/lib/jvm
    sudo ln -s java-6-sun-1.6.0.20 java-6-sun

So here are my steps for the NetBeans installation:
  1. I create a folder under opt for NetBeans:
    sudo mkdir /opt/netbeans
    I don't use the profile folder for installation because this reminds me too much of Windows. In the profile folder there should only go data and I backup this folder more often than other ones. It does not make sense backup the programs all the time.
     
  2. Then I set the permissions for the normal user:
    sudo chgrp theuser /opt/netbeans
    sudo chmod ug+rwx /opt/netbeans
    If you want to have more users work with NetBeans then replace theuser with a group that all the users are member of - however this solution is only if you trust those users regarding updating and activating plugins etc. Otherwise install as a user with sudo permissions and do not set the permissions above to prevent other users from updating.
     
  3. Then I install all NetBeans components (running the installer as normal user) in that folder (/opt/netbeans). There will be usually a subfolder for netbeans (including version in the folder name) and also for Tomcat and Glassfish.
     
  4. I also extract the javadoc downloaded from http://www.oracle.com/technetwork/java/javase/downloads/index.html into /opt/netbeans as jdk-6-docs or so. In former times I put it under the jdk folder but as I upgrade the JDK itself more often than the documentation this always needed additional work to move the doc to the new folder or change links when they got broken after deleting older javadoc.
     
  5. To make the javadoc available in NetBeans launch NetBeans and go to Tools-Java Platforms, switch to the javadoc tab and add the javadoc root folder - in my case /opt/netbeans/jdk-6-docs.
     
  6. When I add external libraries (Tools-Libraries) I also save/extract them previously to another folder - not within my profile (for reasons I mentioned earlier) - of course an option would be /opt/libs or so - I have a completely different separate folder for shared data and libraries that I backup from time to time (less often than profile data).
Related posts: The IDE and the libraries, The programming language.

2010-09-10

Shell scripting your desktop windows

In Java my limits are often what is offered in every OS - and what is inside the JVM.

One thing, I often needed in the past under Windows is to get the title (or other information) of the active window. I was using Windows API to get the information needed. Under Linux/Ubuntu things are different - and more complicated due to different desktop environments, I thought. And how to access those APIs with Java?

Well, it turned out, that I am completely wrong and once again was trapped in my old habits from Windows.

Linux offers commandline tools - not only to get window information - no, also to manipulate windows, move them to different desktop etc. As I could start an application on a different machine and showing the window on my machine, I can either see the machine name in window lists. A commandline program can be easily used from within Java and output can be retrieved easily. Awesome!

It again turns out, that Microsoft Windows is totally poor in commandline tools. However, I could implement a similar small exe that gets me the active window title through API on windows and does console output that can be retrieved by a Java application or can be used in batch files.

If you are a Linux user, have a look at the following commands:
  • wmctrl
  • xprop
  • xwininfo
All these tools can be used even from within shell scripts - awesome!

With xprop -root you get exhaustive information about windows.
Using xprop -root | grep _NET_ACTIVE_WINDOW\(WINDOW\) you get the active window handle. You can then use the address in wmctrl -l | grep theaddress. The only quirks is that in wmctrl the address might have an additional 0 after 0x so you should search for the part after 0x only in the output of wmctrl.

2010-09-09

Dynamic method invocation in Java 6

I often read that people are waiting so much for dynamic method invocation promised for JDK 7 (which now is delayed - see Re-thinking JDK7).

What I wonder is: I already use dynamic class loading and dynamic method invocation in Java 6. Of course, it was a little work, but once done the dynamic class loading and object creation is a one-liner and so is the call to a method:

1:  /*  
2:   * DynTool.java  
3:   */  
4:  package at.mwildam.common;  
5:    
6:  import java.beans.Expression;  
7:  import java.io.File;  
8:  import java.lang.reflect.InvocationTargetException;  
9:  import java.lang.reflect.Method;  
10:  import java.net.MalformedURLException;  
11:  import java.net.URL;  
12:  import java.net.URLClassLoader;  
13:  import java.util.Date;  
14:  import java.util.logging.Level;  
15:  import java.util.logging.Logger;  
16:  import javax.tools.JavaCompiler;  
17:    
18:    
19:  /**  
20:   * Dynamic class loading and method invocation  
21:   * By Martin Wildam (http://www.google.com/profiles/mwildam)  
22:   * @author Martin Wildam  
23:   */  
24:  public class DynTool  
25:  {  
26:    /**  
27:     * Tries to instanciate an object of the given class and returns a pointer to it.  
28:     *   
29:     * Expects the class files in the directory given by the  
30:     * dynClassPath parameter. For each dot (.) in the class path there  
31:     * must be given a subfolder. If there exists a .java file instead of  
32:     * the expected .class file then the method tries to compile the .java file.  
33:     * It tries also a compile if both the .java and the .class file exists but  
34:     * the .class file is out of date (older than the .java file.  
35:     * The addClassPath parameter is only used if the attempt to  
36:     * compile is done.  
37:     *   
38:     * You can also specify a jar file in the dynClassPath parameter if  
39:     * you have a fully compiled and prepared package.  
40:     *  
41:     * Returns null if the object could not be created.  
42:     *   
43:     * Sample: getPluginInstance("/Work/Java/TestGUI/dist/TestGUI.jar", "testgui.TestPluginClass", "/Work/Java/TestGUI/dist/lib")  
44:     *   
45:     * Note: Dynamic class loading and calls evaluated during runtime  
46:     * using reflection is time consuming in general and therefore should be  
47:     * avoided for performance citrical operations (although already better  
48:     * since Java 5).  
49:     *   
50:     * We are returning null here in error case although not recommended  
51:     * because I do agree with Joel Spolsky (http://www.joelonsoftware.com/) on  
52:     * Exceptions at http://www.joelonsoftware.com/items/2003/10/13.html.  
53:     *  
54:     * @param  dynClassPath path to classes root dir where to search for the class to instantiate.  
55:     *     Can also be a .jar file.  
56:     * @param  className Full class name for the plugin class to use.  
57:     * @param  addClassPath is an additional option for classpath to search (;-separated)  
58:     *     which is only used when a compile attempt is done.  
59:     * @return Object or null in error case.  
60:     */  
61:    public static Object getPluginInstance(String dynClassPath, String className, String addClassPath)  
62:    {  
63:      if (!dynClassPath.toLowerCase().endsWith(".jar"))  
64:      {  
65:        String classFile = className.replace(".", "/");  
66:        classFile = dynClassPath + "/" + classFile;  
67:        String javaFile = classFile;  
68:        javaFile += ".java";  
69:        classFile += ".class";  
70:        if (addClassPath.length() != 0) addClassPath = ";" + addClassPath;  
71:    
72:        if ((!existsFile(classFile) && existsFile(javaFile))  
73:            || getFileDate(classFile).before(getFileDate(javaFile)))  
74:        {  
75:          JavaCompiler jc = javax.tools.ToolProvider.getSystemJavaCompiler();  
76:          int r = jc.run(null, null, null, "-classpath", dynClassPath + addClassPath, "-d", dynClassPath, javaFile);  
77:          if (r != 0) return null;  
78:        }  
79:      }  
80:      else  
81:        addFileToClassPath(dynClassPath);  
82:    
83:      try  
84:      {  
85:        if (addClassPath != null && addClassPath.length() > 0)  
86:          addFilesToClassPath(addClassPath);  
87:        URL url = new URL(DynTool.getUrlFromPath(dynClassPath));  
88:        URL[] clsList = new URL[1];  
89:        clsList[0] = url;  
90:        URLClassLoader ucl = new URLClassLoader(clsList);  
91:        Class cls = ucl.loadClass(className);  
92:        return cls.newInstance();  
93:      }  
94:      catch (NoClassDefFoundError ex)  
95:      {  
96:        Logger.getLogger(DynTool.class.getName()).log(Level.SEVERE, null, ex);  
97:        return null;  
98:      }  
99:      catch (ClassNotFoundException ex)  
100:      {  
101:        Logger.getLogger(DynTool.class.getName()).log(Level.SEVERE, null, ex);  
102:        return null;  
103:      }  
104:      catch (InstantiationException ex)  
105:      {  
106:        Logger.getLogger(DynTool.class.getName()).log(Level.SEVERE, null, ex);  
107:        return null;  
108:      }  
109:      catch (IllegalAccessException ex)  
110:      {  
111:        Logger.getLogger(DynTool.class.getName()).log(Level.SEVERE, null, ex);  
112:        return null;  
113:      }  
114:      catch (MalformedURLException ex)  
115:      {  
116:        Logger.getLogger(DynTool.class.getName()).log(Level.SEVERE, null, ex);  
117:        return null;  
118:      }  
119:    }  
120:    
121:    
122:    /**  
123:     * Late binding method call on an already instantiated object.  
124:     *   
125:     * Invokes the requested method of a given object instance where the  
126:     * object class is not specified at compile time.  
127:     *   
128:     * To call a method that does not have a parameter then pass null for the  
129:     * params parameters.  
130:     *   
131:     * What the method returns is routed to the caller of this method as Object  
132:     * so you have to cast the return type to something more specific if needed  
133:     * or just use .tostring. If the called method is declared void then this  
134:     * method returns null.  
135:     *  
136:     * Note: Dynamic class loading and calls evaluated during runtime  
137:     * using reflection is time consuming in general and therefore should be  
138:     * avoided for performance critical operations.  
139:     *   
140:     * We are returning null here in error case although not recommended (because  
141:     * of the earlier mentioned reasons).  
142:     *  
143:     * @param  instance A not well known object for that we hope to be able to  
144:     *     call the requested method.  
145:     * @param  methodName Name of the method to be called  
146:     * @param  params parameter objects to pass to the method (best matching declaration variant is searched)  
147:     * @return Returned object or null if method is declared void or an error occurred.  
148:     */  
149:    public static Object call(Object instance, String methodName, Object... params)  
150:    {  
151:      //Statement stmt = new Statement(obj, methodName, null);  
152:      //stmt.execute();  
153:    
154:      Expression expr = new Expression(instance, methodName, params);  
155:      //expr.execute(); //Not necessary, called automatically on getValue();  
156:      Object result = null;  
157:      try  
158:      {  
159:        result = expr.getValue();  
160:      }  
161:      catch (Exception ex)  
162:      {  
163:        Logger.getLogger(DynTool.class.getName()).log(Level.SEVERE, null, ex);  
164:      }  
165:      return result;  
166:    }  
167:    
168:    
169:    /**  
170:     * Adds a resource given as URL to the classpath.  
171:     *   
172:     * Adds the given url to the classpath dynamically.  
173:     *   
174:     * From antony_miguel at  
175:     * http://forums.sun.com/thread.jspa?threadID=300557&start=0&tstart=0:  
176:     * "  
177:     * I've seen a lot of forum posts about how to modify the  
178:     * classpath at runtime and a lot of answers saying it can't be done.  
179:     * I needed to add JDBC driver JARs at runtime so I figured out the  
180:     * following method.  
181:     *   
182:     * The system classloader (ClassLoader.getSystemClassLoader()) is a subclass  
183:     * of URLClassLoader. It can therefore be casted into a URLClassLoader and  
184:     * used as one.  
185:     *   
186:     * URLClassLoader has a protected method addURL(URL url), which you can use  
187:     * to add files, jars, web addresses - any valid URL in fact.  
188:     *   
189:     * Since the method is protected you need to use reflection to invoke it.  
190:     * "  
191:     *   
192:     * The class path change does not reflect in the system property  
193:     * "" because that property does not get modified any more after application  
194:     * start. So don't check success by checking  
195:     * System.getProperty("java.class.path");.  
196:     *  
197:     * @param  url Url to add to the class path.  
198:     * @return True if operation was successful  
199:     */  
200:    public static boolean addUrlToClassPath(URL url)  
201:    {  
202:      if (url == null)  
203:      {  
204:        Logger.getLogger(DynTool.class.getName()).log(Level.WARNING, "Missing url to add to classpath.");  
205:        return false;  
206:      }  
207:    
208:      boolean b = false;  
209:    
210:      URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();  
211:      Class sysclass = URLClassLoader.class;  
212:      try  
213:      {  
214:    
215:        Class[] methodParams = new Class[1];  
216:        methodParams[0] = URL.class;  
217:        //There could be really different classes in the array.  
218:        @SuppressWarnings("unchecked")  
219:        Method method = sysclass.getDeclaredMethod("addURL", methodParams);  
220:        method.setAccessible(true);  
221:        method.invoke(sysloader, new Object[]  
222:            {  
223:              url  
224:            });  
225:        b = true;  
226:      }  
227:      catch (IllegalAccessException ex)  
228:      {  
229:        Logger.getLogger(DynTool.class.getName()).log(Level.WARNING, null, ex);  
230:      }  
231:      catch (IllegalArgumentException ex)  
232:      {  
233:        Logger.getLogger(DynTool.class.getName()).log(Level.WARNING, null, ex);  
234:      }  
235:      catch (InvocationTargetException ex)  
236:      {  
237:        Logger.getLogger(DynTool.class.getName()).log(Level.WARNING, null, ex);  
238:      }  
239:      catch (NoSuchMethodException ex)  
240:      {  
241:        Logger.getLogger(DynTool.class.getName()).log(Level.WARNING, null, ex);  
242:      }  
243:      catch (SecurityException ex)  
244:      {  
245:        Logger.getLogger(DynTool.class.getName()).log(Level.WARNING, null, ex);  
246:      }  
247:    
248:      return b;  
249:    }  
250:    
251:    
252:    /**  
253:     * Converts a file path to an url link.  
254:     *   
255:     * Returns the url link equivalent to the given path as string.  
256:     *  
257:     * @param  path  
258:     * @return Url string  
259:     */  
260:    public static String getUrlFromPath(String path)  
261:    {  
262:      try  
263:      {  
264:        return new File(path).toURI().toURL().toString();  
265:      }  
266:      catch (MalformedURLException ex)  
267:      {  
268:        return "";  
269:      }  
270:    }  
271:    
272:    
273:    /**  
274:     * Returns a boolean true if a "normal" file with the specified name exists.  
275:     *   
276:     * Note: Returns false for files that are part of the kernel system.  
277:     * So it returns true only for "normal" files.  
278:     *  
279:     * @param  fileFullName FQPN of the file to be searched for  
280:     * @return Boolean  
281:     */  
282:    public static Boolean existsFile(String fileFullName)  
283:    {  
284:      if (fileFullName == null)  
285:        return false;  
286:      else  
287:      {  
288:        File f = new File(fileFullName);  
289:        return f.exists() && f.isFile();  
290:      }  
291:    }  
292:    
293:    
294:    /**  
295:     * Returns the timestamp of the file with the given name if exists otherwise 0.  
296:     *   
297:     * Returns a Date of 0 if the file could not be found otherwise the last  
298:     * file modification date.  
299:     *  
300:     * @param  fileName Name of the file from which to read the date and timestamp  
301:     * @return Date  
302:     */  
303:    public static Date getFileDate(String fileName)  
304:    {  
305:      if (!existsFile(fileName))  
306:        return new Date(0);  
307:      else  
308:      {  
309:        File f = new File(fileName);  
310:        return new Date(f.lastModified());  
311:      }  
312:    }  
313:    
314:    
315:    /**  
316:     * Adds the given file dynamically to the class path.  
317:     *   
318:     * Further details see {@link #addUrlToClassPath(java.net.URL) }.  
319:     *  
320:     * @param  file File object to be added dynamically to the class path.  
321:     * @return True if operation was successful.  
322:     */  
323:    public static boolean addFileToClassPath(File file)  
324:    {  
325:      if (file == null)  
326:      {  
327:        Logger.getLogger(DynTool.class.getName()).log(Level.WARNING, "Missing file to add to classpath.");  
328:        return false;  
329:      }  
330:    
331:      URL url;  
332:      try  
333:      {  
334:        url = file.toURI().toURL();  
335:      }  
336:      catch (MalformedURLException ex)  
337:      {  
338:        Logger.getLogger(DynTool.class.getName()).log(Level.WARNING, null, ex);  
339:        return false;  
340:      }  
341:    
342:      return addUrlToClassPath(url);  
343:    }  
344:    
345:    
346:    /**  
347:     * Adds the given file dynamically to the class path.  
348:     *   
349:     * Further details see {@link #addUrlToClassPath(java.net.URL) }.  
350:     *  
351:     * @param  fileName FQPN of the file object to be added dynamically to the class path.  
352:     * @return True if operation was successful.  
353:     */  
354:    public static boolean addFileToClassPath(String fileName)  
355:    {  
356:      return addFileToClassPath(new File(fileName));  
357:    }  
358:    
359:    
360:    /**  
361:     * Adds files in the given folder dynamically to the class path.  
362:     *   
363:     * You can specify multiple paths separating them by ";".  
364:     * Further details see {@link #addUrlToClassPath(java.net.URL) }.  
365:     * Path must contain only jars and class files (subfolders not included).  
366:     *  
367:     * @param  path FQPN of the path to be added dynamically to the class path  
368:     *     or multiple paths separated by ";".  
369:     * @return Number of jars and class files added.  
370:     */  
371:    public static int addFilesToClassPath(String path)  
372:    {  
373:      if (path == null || path.length() == 0) return 0;  
374:      int n = 0;  
375:    
376:      if (path.contains(";"))  
377:      {  
378:        String[] subPaths = path.split(";");  
379:        for (String subPath : subPaths)  
380:        {  
381:          n = n + addFilesToClassPath(subPath);  
382:        }  
383:      }  
384:      else  
385:      {  
386:        File dir = new File(path);  
387:        File[] contents = dir.listFiles(); //Path Must contain jars and class files only  
388:        for (int i = 0; i < contents.length; i++)  
389:        {  
390:          File file = contents[i];  
391:          if (addFileToClassPath(file))  
392:            n++;  
393:        }  
394:      }  
395:      return n;  
396:    }  
397:    
398:  }  
399:    
400:    

You might prefer looking at this code on pastebin.

Sample usage:
  1. Object obj = getPluginInstance(yourJarFile, yourPluginClassName, additionalLibPath);
  2. Object result = call(obj, "pluginMethod", param1, ...);
    // For no parameters use at least null for param1
I use this currently in two cases:
  • For loading plugins at runtime (in those cases I only need getPluginInstance because I cast the object to a known interface class).
  • To avoid fixed dependencies of common utility libraries (in those cases I only need the call method). What I mean with this? - To explain, a little example: I have a Swing utility class that runs through all elements of a JFrame or JDialog and returns a map with all widget names and values it can extract. This way, saving dialog inputs is a one-liner. However, I support a lot of different external widgets, most are not used in 80% of my projects, so I don't want to introduce the dependencies to all those external components not included in the Swing core. Using the dynamic call offers the support for those widgets when I find them in dialog contents (identified by class name) where they occur. And the appropriate dependencies are only needed in the particular projects where they are needed.
So I don't really understand, why so many people are arguing against Java, that dynamic calls are not possible - where my sample code either automatically compiles a class that is given as .java instead of packed into a compiled .class or .jar file. And if I have both I check the class file if it is older and compile only in that case. So I would say, this is dynamic Java language!

Related posts: Get reliable local IP address in Java, Popular Java myths.

2010-07-16

Java applications on the desktop

When it comes to discussions about programming languages on forums and newsgroups, one argument against Java is that there are quite no Java applications for the desktop.

This is definitely not true. I have looked what Java applications I am using (or used a lot in the past), and here is a list:
And of course, if you are a developer programming in Java, JavaFX, C++, PHP, Python or Scala for example, then you probably use NetBeans or Eclipse - both very popular IDEs (integrated development environments) are written in Java.


There are many, many Java desktop applications out there, look for example at javadesktop.org. You can see the wide area where Java is used on the desktop at geertjans blog here for example or at the NetBeans site here.

One advantage of using Java at the desktop is that you can choose between two core different ways: Swing or SWT. While SWT tries to use the OS specific widgets (to look more like the original OS and be faster), Swing does render everything itself. So SWT is a little bit faster and looks more like OS, but Swing is more flexible (more widgets available) and you can easily use different look and feel / themes (there is also an OS like). In both cases you can develop modern Java desktop applications that look nice and integrated with your OS.

The disadvantage of using Java on the desktop - I will be honest - is startup speed. Once started, SWT and Swing applications behave fast - probably not as a native Gnome application for instance but really - it's fast enough for the user. That startup time is still an issue you will notice mostly, if you write small tools as Java desktop applications. For larger ones it is less annoying because those you don't open and close all the time. If you open the application and tend to keep it open you will have no problem. If you open and close the app frequently then it may become an issue. Same applies for small commandline tools - writing those in Java is maybe not the best option. Anyway, really annoying is only the first start of the first Java application after reboot when the Java runtime is not in the cache yet. NetBeans for example (which is a big Java application) needs 12 seconds on my machine (a year old) when the Java runtime is already in the cache. Freemind is a smaller application and takes only 5 seconds to startup which is acceptable.

If you look also at server-side then ... what should I say .... the world is full of Java applications - too much to cover here (and of course for many websites or web applications you often can't really say from outside what is used behind the scenes).

Related post: Popular Java myths, The future of Java.

2010-07-15

Get reliable local IP address in Java 6

It is strange: I consider myself still being new to Java, but when I search for particular sample code, that should be written thousand times before, I sometimes find only samples that do only half the job or miss important details.
So happened for getting the local IP address(es) of the machine you are running on. I experienced for example performance issues retrieving the IPs when running with a mobile internet stick (point-to-point device).

My example code can be found here: http://pastebin.com/5X073pUc

If you want just one address, that is probably the best fitting then you probable want to use this example: http://pastebin.com/PLAcTXac

Related post: Dynamic method invocation in Java 6.

2010-06-24

Popular Java myths

After developing more than 10 years mostly in Visual Basic (classic), VB Script, VBA etc I started moving to Java after a long evaluation period of different languages about 2 years ago (see also "The programming language") .

Since then when talking with customers, .NET people and even Java folks people come across again and again with the same arguments against Java that are simply wrong. After discussing and researching these arguments a lot of times I am really tired of explaining so this post will hopefully save me from that in the future.

BTW: In discussions you have to distinguish between the Java as a platform (JVM) or the Java language. There are a lot of other languages like Scala, Groovy, JRuby (Ruby interpreter) or Jython (Python interpreter) and others. That the JVM is very popular and far from being dead is not taken into doubt by most people, not so for the Java language.

But why don't these Java language myths finally die:
  1. Java is dead.
    The argument usually comes from the fact that a long time passed since the last major release (Java 6 Update 20 is current at this time) and that they don't see big new stuff coming. At this point have you ever considered C(++) dying? - Or Microsoft Windows? No big changes for many years there either!
    There are other languages that evolve very fast - but take into consideration that most of those languages are very new in relation to Java and there is still much work to be done. Of course with evolution of a language there is legacy generated and it gets more difficult to introduce major new stuff. The newer languages will see the same happening as these problems affects any software getting into age.
    But: It means, Java is proven and stable and I am happy that the language is not changed or enhanced by running after hypes. I really like the decision to think well before really changing a big thing (like introducing closures).
    Another reason why people told Java to death is citing the TIOBE or other indexes showing Java loosing popularity or market share. If you examine how these statistics are built you always find that they are not complete and just investigate a few parameters (like new items in Google search results for example). When I heard the last discussion about TIOBE, Java has fallen on position 2 behind C - now it is back on top again although - according to TIOBE - it still looses popularity (which is logical to me because a lot of new other languages are running on the JVM attracting especially Java developers). On the other hand tht C# is gaining, does not necessarily mean that it is better than Java. Windows developers didn't get major new stuff for about 10 years and basically Microsoft is telling them to move.
    And it remains the question if new is always better, a lot of companies heavily rely on the stability of Java and the long-term return on investment (ROI).
    Besides, although people say, Java is dying, there is so much daily news on Java that I simply can only follow the biggest news. Java land is soooo large and the community is so huge.
    Last but not least: Because there are more operating systems around than ever, platform independent development is getting more important (as developing separately for each platform is costly) - well this is a plus for all languages based on the JVM.
  2. Java is slow.
    There are 3 groups of people saying this. The first group is talking about the startup times and the second is comparing with C(++).

    Regarding the first group: These are mostly people on Windows using Java applications just occassionally. Yes, the JVM takes a while to load (which BTW should be addressed in Java 7) but this applies also for the .NET runtime or other big libraries used in other big applications. The point is, that Windows tends to load everything Windows-related already on Windows startup and if an application using the .NET runtime already then of course the next application will start faster. This issues is (at least partly) already addressed because some Java update comes with an autostarter that also loads the JVM at login time. And BTW: Java 6 is much faster than Java 5 and Java on Linux is much faster than on Windows.

    Regarding the second group: They usually refer to optimized C(++) code. First to say, most developers do not really performance optimize their code (only when necessary); second, in a lot of cases, performance of the language is not the bottleneck (usually network and HDD speed is - or inefficient algorithms/storage methods) and third, the optimization is done at compile time and at runtime. Runtime optimization is not available for C(++)-programs. So it can happen, that Java is even faster than C(++). But of course, in a lot of cases particular optimizations are written in C(++) and then called from Java to improve the overall performance. Of course, C(++) has the potential to be faster than Java. The write once, run everywhere idea introduces a level of abstraction that surely can affect performance - there is no gain that does not introduce a cost somewhere else. But: For most performance issues the performance of the language itself is irrelevant (I mentioned the real bottlenecks above)! Further, I only met once a C(++) developer who really considered performance on everything he did. Anyway, just because C(++) tends to be the fastest of all programming languages, Java is not slow - Java is faster than most other languages! - See e.g. benchmarks at alioth.debian.org.

    Regarding the third group: Those are usually comparing some simple PHP application with some Java EE application that makes use of a component stack that I just get sick when I see it - so no wonder if such a monster app is behaving a little lethargic. Although Java is widely used in the EE world in huge environments, a real lot of connections and a huge amount of data with a huge component stack and a lot of legacy code (and sometimes even still on Java 4 or 5), Java could be used in smaller environments too. Let's say, a typical PHP application contains a lot of DB queries, XML/JSON/HTML parsing and HTML generation. This could be easily done with plain Java also without introducing any particular framework. So most of those people are simply comparing apples with bananas. See also benchmark mentioned before where PHP rates really bad. - That said, according to earlier mentioned real bottlenecks, that does not really matter in most cases.
  3. Java applications need longer time to develop.
    Well, this is maybe not a myth, but a tendency. It is true that while a Ruby-Developer might already have finished the task, the Java developer might still be evaluating the right framework and library to use. But this is not due to the language itself. In many other languages you have not the choices you have in Java land. And for development on Windows, many people just rely on the recommendations given by Microsoft. My experience, after I got member of the local JUG and met some Java developers elsewhere at conferences is, that there are really smart people doing awesome stuff and working on big and critical projects and such with product lifetimes beond 10 or even 20 years. Of course this involves a big responsibility and therefore I can see Java developers investing more time into the evaluation of the architecture, used frameworks and libraries and algorithms.
    And this does not mean that you can't get a small project quickly up and running the "agile style" (using the libraries and frameworks you are already familiar with without starting to evaluate with Adam and Eve).
    Example: Lately I needed a little tool to count all PDF pages of all PDF documents in a certain tree structure (to evaluate needed license volume for OCR processing). In about an hour I had a small tool ready. I was sure, that there exists a tool already that I could use but searching the internet + testing would have been similar amount of work. And if I would have done it with VB on Windows only half an hour for just building a setup that installs the application at client side - but in Java I simply sent the built jar by email and finished. Just run it without the need to install. As another example it took me about 4 days for a prototype of a PDF archiving tool in Swing with embedded PDF viewer and fulltext indexing of the PDF content. Of course this would not have been possible without any experience in Java - any language must be learned first to get really productive. I have a friend who wondered about the long time I spent on evaluation when starting with Java. Yeah, I already can choose between at least 3 great free (see comparison at Wikipedia) Integrated Development Environments (IDE) while on Windows I only have 1 free for .NET in best case (because the most obvious choice here is the costly Visual Studio). Then for thick clients I can choose at least between SWT or Swing for GUI (not to talk about the plenty of choices for web applications). Then there are plenty of logging frameworks and so on. But once you have chosen your preferred toolset, you can use that also if it might not fit 100% best for the next project y after finished project x. And BTW: You could rely on the recommendation of others (if you want to rely on me use NetBeans and/with Swing for thick clients). I myself did not have the appropriate contacts so I went the rocky way.

Related posts: Java applications on the desktop, The programming language, The IDE and the libraries, The dawn after sunset, Dynamic method invocation in Java 6, The future of Java.

2010-01-29

The dawn after sunset

The announcement of Sun being bought by Oracle last year was a shock for many. Since then for months the situation was quite unsure.

As I already wrote in "Sunlight at the end of the tunnel", I had very good experiences with Sun (and that was not just a single time). It was something completely different than my Experiences with Microsoft.

What I did not emphasize in that post (but in my comments on forums and blogs out there) is that all the products managed by Sun seem to have something in common: They are AWESOME!

For example:
  • Open Office
    I used it for a very long time - even successfully for years even under Windows before switching to Linux. The stability, reliability (if you get externally written documents) and the outstanding PDF export makes it already worth using it!

  • Java
    Java is a very mature programming language and when I had to decide my programmer's future, the top favorites (after longer evaluation period) were Java and .NET (C#/Mono). Beside the fact, that platform independency was a big opportunity and the only way for software development with long-term safety of the investment, I found the libraries of Java much more complete than for .NET and especially because of the coding quite strict conventions very readable. And the libraries, toolset and frameworks available is also way bigger. - But this is not only thanks to Sun - this is thanks to the very large community! I also appreciate that they did not bloat Java with too many language features just because somebody wanted to see feature x or y. So I think it was wise to not develop the Java language core too fast.

  • NetBeans
    The best integrated development environment (IDE) I ever worked with. Although starts a bit too slow in my opinion it is still better compared to my last Windows experiences with Visual Studio .NET. I did exhaustive comparison with Eclipse and although Eclipse startup was a bit faster and refactoring options were more, the rest (stability, visual GUI editing and all those small whistles an IDE usually has) was better in NetBeans or either non-existing in Eclipse without searching hours for a matching Eclipse plugin in a version that was reasonable stable.

  • VirtualBox
    I switched over to VirtualBox first when I already planned my move to Linux and VirtualBox OSE (Open Source Edition) was there in the repository by default. So I built new test machines on VirtualBox rather than on VMWare on my Windows development machine. I noticed that it used less resources but from the features lacked a little behind VMWare in some areas. But it developed fast in the last one or two years and so you get everything you need by now. It has even a very cool seamless mode where somehow the client machine gets merged with the host and it seems to be one environment.

  • MySQL
    I think this was one of the last products that joined Sun, but nevertheless they created a very awesome toolset around MySQL that goes a lot further of what is offered along with Microsoft SQL Server.

There are a lot more products, but the above are those I use often and they are a stable and substantial part of my daily work. So Sun was a great, great company - thanks to the people behind.

Now, as the merge with Oracle is finalized, after watching the first press announcement webcasts from Oracle, I am quite positive again. Although I did not watch them all (connection speed got quite down and I was not really able to watch any more), I found the presenters very motivated and excited about the newly added manpower and product portfolio. They are not going to keep everything (Kenai for instance is going to die), but they seem to know the strengths of Sun quite well. They commited strongly to Java, NetBeans and OpenOffice as well as JavaFX for example.

And also the JavaOne conference is going to stay - just moves from the date to be held together/integrated with Oracle World.

So I hope they will continue in honor of Sun with the awareness of the responsibility for those very large communities behind the products I mentioned.

Larry Ellison said "We're in it to win it"! - I am quite positive that Oracle will do a good job. And people reading my blog (and not only those ;-) ) know that I am very critical looking at every new stuff.

Related post: Sunlight at the end of the tunnel, Popular Java myths, The future of Java.

2010-01-23

Web application security

Today I noticed this video: "Clickjacking".

I have no idea how it is done but it shows one more time that web applications are not the overall optimum solution for every development.

If such things are possible, then there are serious risks in using web applications for accessing critical,confidential data!

Is it so much more difficult to download and launch a jar file by double click? Deployment is not necessarily complicated as not every application needs a complex and high sophisticated setup process. ;-)

Related posts: Web vs thick client, Your holy machine.

2008-11-25

The IDE and the libraries

I followed a few discussions lately about Flex, Silverlight and JavaFX and also about the never ending war between the programming languages. Yes, we don't have a sufficient number of programming languages yet and therefore we need new ones - like D for instance. I am sure there will be born others in the future.

But aren't we missing the point? Aren't we trying to reinvent the wheel again and again?

I have seen people pushing languages and technologies one week and and another week something else without having real knowledge or without going deeper into the technologies to get aware of their real purpose. Same type of software is written again and again using different languages and technologies but where is the main additional benefit? Where is the improvement in efficiency while developing?

I have learned over 10 programming languages, really working for a longer time (on real-world projects making money) with about 3 languages. The experience shows it clearly to me, that the programming language itself is only plays a minor role in efficiency of software development. Much more important is the IDE and the libraries. In detail:

  1. The IDE
    • Code-completion
    • Quick tips
    • Debugger (Breakpoints, watches, step-by-step-debugging)
    • GUI-Designer
    • (Online-)Help (or JavaDoc for instance)
    • Editing tools like bookmarks or tasks in code, code folding etc.
    • Refactoring tools
    • build tools (for compiling and deploying)
  2. The Libaries
    • Standard libraries the language offers.
    • Available libraries on the Internet (opensource, free, commercial - the wider the field the better).
    • Your own libraries created while doing your work. The value of those is often underestimated although those include the code you usually do reuse most. And those are what I miss most when learning a new language - the stuff I already did and want to reuse and improve on the fly.
Both - the IDE and the Libraries have to be learned. So being familiar with the syntax of the langauge is one thing. Being familiar with an IDE and with the existing (standard) libraries is a second.

Fact is that one using a language he or she is not familiar with and then either using a simple text editor can never be as productive as a developer knowing the IDE and their features (and use them efficiently) as well as the existing (standard) libraries. When the latter also have a good overview about other free and commercial libraries or tools out there he or she can either efficiently decide where to write own stuff or use 3rd party components.

When I searched for an alternative to my Visual Basic I looked at several languages and the language itself was of minor priority. I liked Python for instance from the general language features and efficiency in coding I also imagine problems due to the indentation orientation when different developers use different editors with different indentation settings. But despite the language itself I tried several IDE's for python and there was none that I was really satisfied with.

Eclipse and NetBeans are IDE's that like to solve the IDE problem in general to be the one IDE for all languages. But from what I read and heard by now they work best for Java (and C++ - which I didn't try yet) so far (which is subject to change). But new languages usually lack of integration with good IDE's - logically.

So all this in a whole made me switch to Java (apart from the very good reason for platform independent development). - I do not urge anyone to use Java but I strongly recommend to not only look at the language itself when choosing a new one for future projects.

Related posts: IT investment, Utility libraries, Popular Java myths, Install NetBeans on Ubuntu 10.04, Choosing a programming language.

2008-11-21

Homogeneous programming style

I am currently on the smooth move from Visual Basic 5 to Java (for new projects). Although I did also some PHP and ASP my focus was on Visual Basic and VB Script for the last about 12 or 13 years. VB was a very good choice for my Windows focused development because the dialect for VBScript, Microsoft Office Macros and ASP was all the same and every COM-component developed with VB could be reused in Scripts, Office Macros as well as ASP web applications.

So whereever there was something to develop I could do it most efficiently using VB and reusing components or single methods I already developed. I also have some little experience with "language hopping" by using a little Python here and more PHP over there.

The experience tells me that every language has its own pitfalls and while hopping from one to the other you either trap in the beginners problems like missing a semicolon here or mixing up indentation there. If you can focus on one language which can be used to do everything then you should prefer that - you are simply more efficient in programming.

The two major benefits of focusing on one language:
  • Easier reusability of components and libraries you already created.
  • Better knowledge of the language and the pitfalls because you have more experience on the particular language.
And that was one reason (but far not the only) I have choosen Java. And although JavaScript is not the same as Java, it has at least same basic syntax.

Related post: The programming language.

2008-09-18

The programming language

The list of available programming languages is very long - many are listed at Wikipedia. A comparison can also be found at Wikipedia.

I would say the most important languages are:
  • C(++)
  • Java
  • Python
  • C# (VB.NET, ...)
  • PHP
  • Javascript
If your favorite language is not listed here then be told that it does not mean that it is a bad language - not always the best things are those that are well known and popular.

According to my last post "The operating system" it is a logical conclusion to choose a programming language which can produce programs that run on several systems and are not limited to Microsoft Windows for example.

So from the languages listed above C# and the complete .NET framework is the one that is less portable to other operating systems. Although there is the Mono port from .NET to Linux, it is in the hand of Microsoft to give them the needed documentation and let them live.

But a programming language cannot be justified only by the compiler. I remember DOS times and the Borland Turbo Pascal or Borland Turbo C - we used them at school and it was not only a compiler - it was Integrated Development Environment. It supported the developer with tools and help. Nowadays IDEs bring features like
  • Debugger (one of the most important features of an IDE).
  • List available classes, properties and methods and autocompletion (also very important).
  • Quick-Help on the used classes and methods.
  • Code folding (collapse and expand blocks and methods to have better overview in the code).
  • Code highlighting (highlight keywords, search terms, matching brackets and so on).
  • Automatic proper formatting of the code.
  • Refactoring (Renaming classes and methods for example).
  • Assistant for creating specific code parts.
  • Macros and hotkeys.
  • GUI Designer (design window dialogs).
  • ...
Most of those features are included in every modern IDE.

From what I read in forums there are still many purists who write their code in text editors. vim might be an exception here because there can be added a lot of stuff and features to it, but mostly using a text editor you can't develop with the same productivity and performance as if you were using an IDE. So IDE is an important thing.

The .NET has a huge IDE and in general I liked also the previous Visual Basic IDE which (if looking at version 5 and not 6) was also very stable and reliable. The .NET IDE however I do consider as bloatware and unstable. That is was just was my experience with the Visual Studio 2005. And for the Visual Studio 2008 I do not have enough harddisk space left. Although there are alternatives to Visual Studio I am sure that the Visual Studio is a more complete suite. I tested only SharpDevelop which lacks on debugging. Installation size of Sharpdevelop is less than 40 MB - I didn't believe that is possible to develop .NET applications with GUI (yes, a GUI designer is included) only with such a little piece of software where Microsoft needs more than 1.5 GB - although I must honestly say that there is no .NET documentation included with SharpDevelop.

In my opinion the portability and the availability of a good IDE are the two most important aspects. As I am using Windows and Linux it should be either an IDE that nearly looks the same on both platforms. Another important thing is the time that you need for getting up and running. The optimum would be if you either can learn the language fast.

I tested several IDEs (or at least tried to install them and get them running) - I tried IDEs for Python, C++ and Pascal as well as for Java.

The largest number of IDEs are available for Java - here I tested Eclipse and NetBeans. Eclipse focuses on SWT from the GUI design (additional plugin needed) and NetBeans on Swing. Eclipse and NetBeans are already very powerful and they are free.

For me the time needed to get up and running and to start into getting productive was shorter on NetBeans and further I prefer the Swing concept because the technology offers more freedom in developing more sohisticated visual controls and more independent from underlying OS. The disadvantage is that the core dialogs like a file chooser do not look as the user might be used to. But as I work on Windows and Linux I already have to get around with two different dialog variants and so at least in my applications the dialogs (the core dialogs and all the other window controls) look the same no matter on which OS it is used.

Although I also like Python very much I could not find a good IDE that is available for free. For C++ I found Code::Blocks which is available on several platforms. For Windows they have a combined setup download including the MingW C++ Compiler. C++ is for me the only real alternative when trying to write code for several platforms. However I know from my earlier experiences with C that writing C-Code you have to pay more attention and it is very likely that you write more buggy code with C than with most other languages (not C-like). But the biggest advantages of C are the faster code and the more complete access to and management of the system resources. Here Java has a disadvantage as it has no direct access to drivers of particular hardware (e.g. a scanner) that might be connected to the machine - you need wrapper libraries to get around this problem. Further C is fitting better if you write commercial software because Java programs can be decompiled easily (and also .NET applications).

Another option is PHP which is platform independent. Although there is a possibility of writing standalone applications PHP is basically for web applications only.

From the portability and usability point of view in my opinion Java and C++ are the two favorite languages to use in the long run as you can't be wrong betting on those. Regarding web development there a lot more options (PHP, SWF, AIR, FLEX and so on) and I do not have the confidence to give a good forecast on that.

Related posts: The operating system., Homogeneous programming style, Popular Java myths, Install NetBeans on Ubuntu 10.04, The future of Java, Choosing a programming language, Java vs .net/C#.