Thursday, October 13, 2011

Java File Handling

Lately I been working on a Java file manipulation project and I came across an issue which I never expected.

This is a sample code.

public class FileReader {

    public static void main(String[] args) throws IOException {
        new FileReader().fileDelete();

    public void fileDelete() throws IOException {

        final String fileLocation = System.getProperty("user.dir") + "/test.txt";

        File fileCreate = new File(fileLocation);
        final boolean isFileCreated = fileCreate.createNewFile();

        if (isFileCreated) {
            System.out.println("File Successfully Created");
        } else {
            System.out.println("File Creation Failed");

        final BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(fileLocation));
        for (int i = 1; i <= 5; i++) {
            bufferedWriter.append("Line : " + i + "\n");

        final BufferedReader bufferedReader = new BufferedReader(new;
        String line;
        while ((line = bufferedReader.readLine()) != null) {

        File fileDelete = new File(fileLocation);
        final boolean isDeleteSuccess = fileDelete.delete();

        if (isDeleteSuccess) {
            System.out.println("File Deleted Successfully");
        } else {
            System.out.println("File Deletion Failed");
Assume the file test.txt does not exists when running the programme. Can you predict the output of this programme? 
If you have thought it will print

File Successfully Created
Line : 1
Line : 2
Line : 3
Line : 4
Line : 5
File Deleted Successfully

If you have thought a bit more you might have predicted it will print

File Successfully Created
File Deleted Successfully

You’re completely wrong at least on a Windows, both the above outputs are wrong. Actual output on windows is "File Deletion Failed". It took me some time to actually realize the issue when my programme dint work as expected. As for the part of the Line 1 .. 5 not printing that’s straight forward I dint close the bufferedWriter. The problem here is that if you read or write to a file and you don’t close the stream you cannot delete the file in windows. Even when you’re actually creating a new File object it will still not let you delete the file and to make things worse it does not give you any other explanation except for Boolean false Imagine searching for this in thousands of line. So guys whenever you’re reading or writing to streams always remember to close them.

Friday, September 2, 2011

CSS Hacks For Every Browser

There are many CSS hacks that I have come across while developing web applications, mostly used one is the IE's conditional comments to apply classes to the body tag but there are some situation where you will want to add conditional CSS within the stylesheet, specially if your working with Vaadin

The following is a documentation of browser specific CSS style attribute I've seen. These CSS will help you better make specific changes to IE, Firefox, Chrome, Safari and Opera from within the CSS.

/***** Selector Hacks ******/

/* IE6 and below */
* html #uno { color: blue }

/* IE7 */
*:first-child+html #dos { color: blue }

/* IE7, FF, Saf, Opera */
html>body #tres { color: blue }

/* IE8, FF, Saf, Opera (Everything but IE 6,7) */
html>/**/body #cuatro { color: blue }

/* Opera 9.27 and below, safari 2 */
html:first-child #cinco { color: blue }

/* Safari 2-3 */
html[xmlns*=""] body:last-child #seis { color: blue }

/* safari 3+, chrome 1+, opera9+, ff 3.5+ */
body:nth-of-type(1) #siete { color: blue }

/* safari 3+, chrome 1+, opera9+, ff 3.5+ */
body:first-of-type #ocho { color: blue }

/* saf3+, chrome1+ */
@media screen and (-webkit-min-device-pixel-ratio:0) {
#diez { color: blue }

/* iPhone / mobile webkit */
@media screen and (max-device-width: 480px) {
#veintiseis { color: blue }

/* Safari 2 - 3.1 */
html[xmlns*=""]:root #trece { color: blue }

/* Safari 2 - 3.1, Opera 9.25 */
*|html[xmlns*=""] #catorce { color: blue }

/* Everything but IE6-8 */
:root *> #quince { color: blue }

/* IE7 */
*+html #dieciocho { color: blue }

/* Firefox only. 1+ */
#veinticuatro, x:-moz-any-link { color: blue }

/* Firefox 3.0+ */
#veinticinco, x:-moz-any-link, x:default { color: blue }

/* FF 3.5+ */
body:not(:-moz-handler-blocked) #cuarenta { color: blue; }

/***** Attribute Hacks ******/

/* IE6 */
#once { _color: blue }

/* IE6, IE7 */
#doce { *color: blue; /* or #color: blue */ }

/* Everything but IE6 */
#diecisiete { color/**/: blue }

/* IE6, IE7, IE8 */
#diecinueve { color: blue\9; }

/* IE7, IE8 */
#veinte { color/*\**/: blue\9; }

/* IE6, IE7 -- acts as an !important */
#veintesiete { color: blue !ie; } /* string after ! can be anything */

/* IE8, IE9 */
#anotherone {color: blue\0/;} /* must go at the END of all rules */

Thursday, May 26, 2011

Gnome 3 New Features and Does It Look Like Windows 7 ?

As most of you all know Gnome 3 is released ( so as always I wanted to try it out, so I installed it on my fedora 14, and then wanted to check it out with fedora 15. After messing around with it for some time, It was okay but not that great, For the most part of it I could notice the similarities to Windows 7s normal theme. So went around searching to see what were others opinion about it, but tomy surprise there were NO or just a bit of talk about it, This gave me no other option but to write something for myself.

I'm not going to compare in detail and break down the things, maybe that's for another post. This will be a comparison between the major functionalities shown on the home page of Gnome 3 (you can checkout the videos)

Feature 1:  Instance Messenger Notification

Who are you kidding?? I have not come across a messenger which actually distracts me while I'm working all the messengers I have worked with just gives a small notification on the right side corner with the beginning of the message. What is the use of putting this as a feature on Gnome 3 ?? I seriously don't get that. If any of you disagree with me on this think about a messenger which does not actually do this. I do get, Integrating the messenger to Gnome might be a good thing, but the problem is if all my messengers notification look alike its just going to be dull in the end. Sometimes it is nice to have your mind distracted with Messenger specific notification than having a black themed notification.

Feature 2:  Easier Window Management

The next video goes on to say if you drag the window to the top it gets maximized and if you drag it to the left it goes to left, ext.. First thing that pop into my head was 'This is just the same feature Windows 7 gives' So whats the big deal?

Feature 3:  App-based Window Management

There is nothing to be said on this. This is no other than 'Quick Launch' feature introduced in Windows Vista. I dint not see anything new here. Its just the same old thing.

Feature 4:  Deeper Hardware Integration

'We only show Suspend option if it's supported by you hardware' That was there even on Windows XP which is more than ten years old. Showing options that are supported by your hardware was already available in Gnome 2. Firmware is not done by Gnome it just front ends it, so even how much support you have on this first the Firmware has to be updated if you want to use this at all.

Feature 5: Create Workspaces

Well this is actually good, but I still feel the static workspace is better. The problem with this is, I actually need to do another mouse move or a keyboard shortcut to see the workspaces that I have used. Anything that makes me do one more step is something thats not worth it.Workspace is something that we use a lot so I want to be able to see the free workspaces like on Gnome 2 without another command involved.

Where the Hell is the Task-bar ?

At first  you will see is that the task-bar is missing. Whats the point? I don't want to move my mouse or do a keyboard shortcut to see the programmes that are running I want to just see it in one glance when I want to, Its not worth to remove something just to save like 10 px of space. Again anything that makes me to something more is not worth it.

I'm not trying to persuade that all features are bad, there are some good features as well, but Gnome 3 was a disappointment for me. I was expecting more than what I received. Alas, none of the features were good enough for me to switch from Gnome 2 to Gnome 3.

Tuesday, May 17, 2011

Spring Security and CAS Integration with Vaadin

We have been working with Vaadin for some time now. We have done multiple websites and admin applications. There was a customer who requested a SSO (Single Sign On) to be added to one of the new website we are creating. So we thought its not that big of a deal; we just needed to add Spring security and then do the CAS filter and we are all done. Well the solution is striaght forward but don't even try to search this on the web, there is not even one fully integrated working solution out there, so what I did was I sat down and did a Vaadin wrapper with spring security integrated. I have used Spring 3.0.5 so all spring security tags are written for that.

This is how it looked like in the end

public class SampleVaadinApplication extends VaadinApplication {

    private UriFragmentUtility fragmentUtility;
    private VerticalLayout layout;

    public void init() {
        final Window mainWindow = new Window("Vaadin Cas Sample");
        fragmentUtility = new UriFragmentUtility();
        layout = new VerticalLayout();

public void buttonClick(Button.ClickEvent event) {
     final String path = getURL().getPath();
     if (!hasAnyRole("ROLE_DEFAULT_ACCESS")) {
        getMainWindow().open(new ExternalResource(path + "do-something/"));
     } else {

web.xml you just need to add this to be the wrapper (and of cos the spring tags ;) ).



I have hosted it in git you can have a look at the sample to get your self up and running.

Saturday, May 14, 2011

5 Reasons Why I Changed from Linux to Windows

I'm sure the heading is going to make some people go, 'This guy is nuts' specially me being a Java developer. Let me explain why I chose to change from Linux to Windows.

1) Hardware Support

The biggest problem I had running Linux (I use Fedora 14) on my laptop is the hardware support. I agree Linux has come to a point where it supports most of the drivers (and yes Ubuntu has more support) the problem is the drivers are done by third party developers and companies and not from the actual vendors. The drivers work fine I'm not complaining about that, but it does not support the hardware fully to a point I would prefer it to. It is evident as the laptop heats up.

2) Flash and Video Streaming

One of the second most thing that I do when I'm not coding is streaming Movies and TV series. Have you even tried it? let me tell you what happens, It sucks your processor usage at-least to 70-80% I can check for prime numbers on Java programme and it still would not have to take so much, and yes I have tried it on Firefox 4 and Chrome 11 this is because of Flash. If you search for a solution regarding this on the net, you will see a lot of people have complained about this but there is no proper solution to this. Maybe this is because of the hardware support.

3) Programmes and Games

I am not much into games, but once in awhile (once in three months ;) ) I just like to play a game. With linux its not possible, just the option knowing I can is more then enough, and yes Linux has its games but nowhere close to the once you have on windows.

yum and apt-get are really powerful and I'm definently going to miss this on Windows, but I'm sure I can download any programme that I want to install on Windows. I have still not come across programme that is available in Linux but not available in Windows (the functionality vice).

4) MS Office and Graphical Programmes

Open Office is really good, but no where close to as MS Office, you can argue much as you want but if you use it couple of times you will feel the difference, and when specially all the customers documents are done using MS Office.

Gimp is good, but not as Photoshop and other programmes like Dreamweaver and Flash you cant find it on Linux

5) Intellij Idea and Visual Paradigm

As you guessed it correctly I use them more then any other programe. VP is defiantly faster on Windows than on Linux it's even faster if you run it on VMware on the same machine. Same applies to Idea, it runs faster on Windows but this has not as much differences as VP but it is defiantly faster.

That raps it up. The above reasons are more then enough for me to switch to Windows. Definently there are some things I will miss in linux following are some ;)

1) All shell commands and the linux terminal, windows powershell does not come close to it but cygwin will fix that.
2) You can delete a file while its been executed on linux, specially commands like mvn clean and remove can be done without any problem in linux, but if you do that on windows there could problems like file been access by some other programme errors.
3) I'm into bit of Ethical Hacking most of the hacking tools are in linux so that will be a definite disadvantage.
4) Most spoken thing when comparing linux and windows is the boot time. linux could be couple of seconds faster, but until now I have never sat in-front of my laptop waiting it to start I have more than enough things to do at that time, and be honest with your self. when was the last time you shutdown your computer?

Windows does all the things I need better than linux and some things that I cant do in linux. So why do I still need to be in linux?

Wednesday, May 11, 2011

Clojure and Vaddin

I been working on Clojure and Vaadin for some time now and I think It's right about time I write a blog on how to do it. This is a really simple example for someone to get start on.

First thing that we need to do to get things started is to create a servlet clojure file which will load the Vaadin application.

(ns example.vaadin-servlet
    :extends com.vaadin.terminal.gwt.server.AbstractApplicationServlet
    :name example.VaadinServlet))

(defn ^Class -getApplicationClass [this]

(defn ^hms.appstore.ui.main.VApp -getNewApplication [this request]

This will be the servlet that you will add into the web.xml keep in mind the java class name will be example.VaadinServlet.

Next is to create the Vaadin Application which would look something this.

(ns example.vapp
    :extends com.vaadin.Application
    :name example.VApp
    :init cjinit))

(defn -cjinit []
  [[] (ref {})])

(defmacro window [name caption container & body]
  `(let [caption# ~caption
         container# ~container
         ~name (com.vaadin.ui.Window. caption# container#)
         ~(symbol (str name "-" "container")) container#]

(defn -init [this]
  (println "=== Initiating Vaadin Application ==")
  (let [comps (transient {})]
    (window w "Clojure Vaadin Application" (com.vaadin.ui.VerticalLayout)
      (.setSizeUndefined w-container)
      (.setMainWindow this w)
      (let [layout (com.vaadin.ui.VerticalLayout.)])
      (.addComponent w-container layout)
      (.addComponent layout (com.vaadin.ui.Label. "Test Message")))))

Thats all. I have used a macro for the window can do without that as well.

Saturday, February 26, 2011

How to Access JBoss Queue with a Standalone Client

In this post I'm going to talk about how to access a JBoss queue using a standalone client. I'm not going to talk about the basic details of creating a queue that you can find in JBoss documents.

There is two steps to this
  1. Setup the JBoss queue
  2. Setup the standalone client
Lets start with the JBoss queue, lets create a normal queue

<mbean <name="jboss.messaging.destination:service=Queue, name=Queue1" code="org.jboss.jms.server.destination.QueueService">
  <attribute name="JNDIName">queue/Queue1</attribute>
  <depends optional-attribute-name="ServerPeer">jboss.messaging:service=ServerPeer</depends>

Now lets setup the remote client. Make sure the JBoss necessary libraries are in the classpath.
public static Context getInitialContext( ) throws javax.naming.NamingException {
   Properties p = new Properties( );
   p.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
   p.put(Context.URL_PKG_PREFIXES," org.jboss.naming:org.jnp.interfaces");
   p.put(Context.PROVIDER_URL, "jnp://");
   return new InitialContext(p);

 now lets setup the queue

    String queueName = "queue/Queue1";
    Context ic = null;
    ConnectionFactory cf = null;
    Connection connection =  null;
    QueueSession queueSession;

    connectionFactory = (ConnectionFactory) ctx.lookup("/ConnectionFactory");
    conn = connectionFactory.createQueueConnection();

    queueSession = conn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    queue = (Queue) ctx.lookup(queueName);
    MessageProducer queuePublisher = queueSession.createProducer(queue);

You can change the JNDI name of connection factory or you can create your own.

Now lets setup a listener.
    MessageConsumer consumer = queueSession.createConsumer(queue);

You can test the connection by sending simple message
TextMessage message = queueSession.createTextMessage("Hello Sourabh Girdhar");

To receive messages you will need to implement MessageListener interface and override the onMessage()  
public void onMessage(Message msg) {
 TextMessage message = (TextMessage) msg;
 String text = null;
  text = message.getText();
  System.out.println("Message received - " + text);
 }catch (JMSException jme){


Wednesday, February 2, 2011

Harnessing Developer Communities for Telco Apps

It is no secret today that one of the imperative sources of innovation in the Mobile Industry are application Developers. The innovative potential can be derived from an average high school kid to the likes of Mobiquest, all of which contribute to this rapidly growing industry. Every mobile application developer dreams of building the next cutting edge application and monetizing it. The success of a mobile application is based upon creativity and relevance to its intended audience. Furthermore the uniqueness of the application, its functionalities and time-to-market add on to the foundations which contribute to its success. A major challenge for Telecom operators therefore is to channel the creation of these applications that monetizes network assets and accelerating the roll out of “Telco Apps” which undoubtedly adds value to their service offering. This creates a need for telecom operators to have a platform that can entice innovation starting from idea generation, necessary tools, best practices and also a test bed where application developers can endeavor their brainchild with utmost freedom.

Enticing Developers

According to Mobile Developer Economics 2010, a study by Vision Mobile, 75% of surveyed Developers opted for Market Penetration as the most important reason to choose a Developer platform against any of its favorable technical aspects. Compared to the makers of mobile devices or mobile operating systems, few operators have a “global blanket reach” but most of them possess the advantage of strong brands in their local markets, the ability to steer traffic via network capabilities and a great deal of local knowledge of subscribers enabling “targeted reach”. We believe this is a great opportunity to inspire developers based around their localities to come up with applications suited to their surroundings. The diversity of the market could play as much a role in attracting developers. It cannot be denied that device vendor apps and the mobile web have brought out a rich wave of sophistication enhancing user experience. However this doesn’t utilize the potential of reaching out to the diversity of the masses that GSM coverage has enabled today. Operators should exploit the advantages of its network capabilities with channels such as SMS made available on every mobile handset and it is one that nearly every mobile user understands how to use. This potential materializing should spark the possibility of apps serving various spectrums of a market and operators will therefore have the unique strength to attract low to very high-end application developers.
The convergence of technologies that operators are engaged with today provides multiple interfaces for developers to reach out to their audiences via bundling, packaging, cross-product opportunities, location based services, segmentation and profiling capabilities amongst a few. The operator therefore becomes a unique and powerful channel to collaborate with, in providing applications. Pricing and charging are underlying drivers influencing the ambitions of applications. Developers of established application platforms have long been stuck with rigid pricing variants of the pay-per-download revenue model. The operator has the opportunity to provide an application its due flexibility with numerous options such as fixed price, recurring fee on usage, subscription based etc

Easing the Developer Task

Of course the proof of the pudding is in the eating of it and the platform that operators provide have to be technically sound for what developers do best – to develop applications. The Vision Mobile report goes on to say that the learning curve of the Symbian Platform and the Anrdoid Platform is approximately 15months and 6 months respectively. This is a great opportunity for operators to exploit, provide a platform that reduces the learning curve significantly. Mobile application developers who thrive to unleash their creativity in the form of novel applications crave for a simple and streamlined application development process. They want to create applications with minimal intervention and understanding of the need to connect to the telecom operator’s backend, as well as their underlying protocols. Operator platforms aiming for “developer-friendliness” will be successful in harnessing abundant creative talent amongst those who possess ground-breaking ideas but are inhibited by the technical obstacles involved in materializing these ideas. In addition to “developer-friendliness” imperatives, the availability of useful resources that enhance the applications during the development process in the form of sample applications, development tool kits and guides will help inspire budding developers and boost the development process from rapid creation, deployment and commercialization of their mobile applications.

Marketing of Telco Apps.

Market Penetration was earlier highlighted as a key factor for Developers choosing platforms and this is exemplified by Operators being able to facilitate multiple interfaces when delivering applications to subscribers. Operator’s capabilities in providing the “Telco App store” as a web based, USSD Interface appeal to a larger and a more diverse audience rather than those only having smart phones. The power of identity management options such as user profiling information coupled with network capabilities such as location provides the opportunity for developers to customize apps for distinct subscriber segments. The Vision Mobile report highlights the key challenge Developers face is, marketing their own applications. There can be various reasons for this especially if the developer and his target audiences are geographically disconnected. With operators having There is now a better opportunity for developers to do so around their own communities and interest groups especially if they have deployed the app based on the area where they are present.

Birth of a Vibrant Telco Developer Community

In a day and age where mash-ups are enriching consumer experience, the best-of-breed mobile applications are sometimes born out of collaborative ideas from many people from all walks of life. Fierce competition has led individual developers to be on the lookout for partnerships with larger communities of developers that can bring out better applications. This can be enabled with interactive online forums that are supported by technical counseling, developer workshops & networking sessions for idea generation, knowledge sharing & potential business partnerships, thus creating a vibrant developer community.

hSenid Mobile recently launched its state of the art Cloud Enabled Telco Developer Portal that is set to pave the way for a vibrant Developer Community with a simplified Development Path resulting in a Plethora of “Telco” Applications for Mobile Operators to provide its diverse subscriber base.

Tuesday, February 1, 2011

Telco based SMS and MMS application using JAVA and .NET

AppZone is the Worlds first ever Telco based mobile application appstore launched by Etisalat Sri Lanka partnered with hSenid Mobile. This platform allows the users to browse the mobile applications and also gives the opportunity for application developers to create, test and sell their own unique applications.
It helps developers to create application using Java , .NET or any other programming language (which supports HTTP) they prefer, to send a receive SMS and MMS to mobile phones. Which gives the opportunity for developers to get recursive revenue which is not available in downloadable application for mobile handsets.

Sample Code
public class SimpleSmsMt {
public static void main(String[] args) {
      try {
MchoiceAventuraSmsSender sender = new MchoiceAventuraSmsSender(new
                                                                    URL("http://appzone.server:8899/"), "SMS_6063",
// send message to a single destination
String message = "hi im jason";
String address = "+94969696969";
sender.sendMessage(message, address);
} catch (Throwable e) {

Use the API's to create your applications and services. The downloads you need are here, as well as the documentation and the community to speed things up.

    If you have created the application its easy as to drop a mail to go live.
    Drop a mail to to get your account details or if you want any clarification.