Sunday, April 8, 2012

GWT-Eureka Available

Both in this blog and in stackoverflow I've been writing about different widgets and improvements to already existing GWT widgets.

Due to popular demand (well at least some people asked for it) I decided to finally put all this code publicly available in a new project: GWT-Eureka

Website: GWT-Eureka

The code is available under GPLv3 license and you can simply use it. You're also welcome to fork the git repository or, even better, collaborate with your own widgets and improvements.

Here you have an screenshot of the first widgets:


So far the available widgets are:

TimePicker

An input box for time. It supports both am/pm and 24h formats.

There's also TimePickerSmall widget, that's a simple extension of the TimePicker, but with a different CSS style applied for those cases where you need an smaller element.

iOSButton

A basic button with support for badges. You can see more details here: iPhone like Buttons

ExtendedDatePicker

Is a modified version of GWT DatePicker with some new features:

  • Support to configure the first day of the week, independently of the defined locale
  • Support for minimum date. Any date older will be disabled
  • Support for maximum date. Any date newer will be disabled
You can see it in action here: http://gwt-eureka.appspot.com/

That's everything right now. Looking forward for your feedback and comments.

Thursday, April 5, 2012

I'm back (at least I think so)

I cannot believe it's been more than a year since my last post. A lot of things have happened in the mean time.

I'll do my best to start writing again some interesting stuff, in fact I've already prepared some things to start with.

Let's give a second try to blogging.

See all you here.

Friday, December 17, 2010

HttpClient: Connecting to an SSL Server

In the last days I've been fighting trying to solve an issue connecting to an SSL Server with SSLv2 disabled. For some reason my client code was crashing trying to connect, but as soon as SSLv2 was enabled everything worked fine again.

The problem was that even when my server was not accepting SSLv2 connections, my client code was trying to do a handshake validation using the SSLv2 protocol. This was causing the problem.

Since it took me so much time to find the problem, I though would be nice to share here what did I discover.

The first step is to create the code to properly connect to an SSL server. You can find how to do it with Self-Signed certificates in my previous post "HttpClient: Use Self-Signed Certificates".

Ok, if you followed it without problems now we're going to attack the way our code validates the different protocols.

With the debug enabled, you'll see the whole SSL handshake process.
System.setProperty("javax.net.debug", "all");
In a normal scenario any of the SSL protocols should be accepted, but in some cases, as the one I found, the SSLv2 is disabled. That's because this protocol is considered insecure.

The way of dealing with these scenarios is creating your own SocketFactory.
public class TLSSocketFactory extends SSLSocketFactory {

 private final javax.net.ssl.SSLSocketFactory socketfactory;
 
 public TLSSocketFactory(SSLContext sslContext) {
  super(sslContext);
  
  this.socketfactory = sslContext.getSocketFactory();
 }

    public Socket createSocket() throws IOException {
     SSLSocket socket = (SSLSocket) super.createSocket();
     
     socket.setEnabledProtocols(new String[] {"SSLv3, TLSv1"});
     
     return socket;
    }
    
    public Socket createSocket(
            final Socket socket,
            final String host,
            final int port,
            final boolean autoClose
        ) throws IOException, UnknownHostException {
     
        SSLSocket sslSocket = (SSLSocket) this.socketfactory.createSocket(
                socket,
                host,
                port,
                autoClose
          );
     
     sslSocket.setEnabledProtocols(new String[] {"SSLv3", "TLSv1"});
     
     getHostnameVerifier().verify(host, sslSocket);
     
     return sslSocket;
    }
}
As you can see the code is quite simple. It's simply wrapping the SSLSocketFactory. Where is the trick? The best way to control with protocols can be used for the handshake is configuring them directly in the socket object. So here we're simply overloading the createSocket methods, but inserting a minor tweak
sslSocket.setEnabledProtocols(new String[] {"SSLv3", "TLSv1"});
If for some reason you only want to allow connections using TLS, then remove the SSLv3 protocol from the list.

And that's all. As you can see the code is quite simple.

See you soon.

Tuesday, November 16, 2010

HttpClient: Use Self-Signed Certificates

Lately I've been implementing SSL support between a Java Server and another production server. In my development environment I needed to use self-signed certificates and be able to use them with Jakarta HttpClient 4.x.

Looking through internet I found quite a lot information about how to add SSL support to HttpClient 3.x but not too much about HttpClient 4.x

Lets start with the code

private static DefaultHttpClient createHttpClient(int port) {
  try {
   java.lang.System.setProperty(
     "sun.security.ssl.allowUnsafeRenegotiation", "true");

   // First create a trust manager that won't care.
   X509TrustManager trustManager = new X509TrustManager() {
    public void checkClientTrusted(X509Certificate[] chain,
      String authType) throws CertificateException {
     // Don't do anything.
    }

    public void checkServerTrusted(X509Certificate[] chain,
      String authType) throws CertificateException {
     // Don't do anything.
    }

    public X509Certificate[] getAcceptedIssuers() {
     // Don't do anything.
     return null;
    }
   };

   // Now put the trust manager into an SSLContext.
   // Supported: SSL, SSLv2, SSLv3, TLS, TLSv1, TLSv1.1
   SSLContext sslContext = SSLContext.getInstance("SSL");
   sslContext.init(null, new TrustManager[] { trustManager },
     new SecureRandom());

   // Use the above SSLContext to create your socket factory
   SSLSocketFactory sf = new SSLSocketFactory(sslContext);
   // Accept any hostname, so the self-signed certificates don't fail
   sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

   // Register our new socket factory with the typical SSL port and the
   // correct protocol name.
   Scheme httpsScheme = new Scheme("https", sf, port);
   SchemeRegistry schemeRegistry = new SchemeRegistry();
   schemeRegistry.register(httpsScheme);

   HttpParams params = new BasicHttpParams();
   ClientConnectionManager cm = new SingleClientConnManager(params,
     schemeRegistry);

   return new DefaultHttpClient(cm, params);
  } catch (Exception ex) {
   Log.error("ERROR Creating SSL Connection: " + ex.getMessage());

   return null;
  }
 }

The code is quite documented, so I will not add too much. Anyway I want to clarify somethings.

This code is not secure. This code accepts any certificate from any host, so don't use it in production code (or use it if you're really sure you known what you're doing)

In case you've any problem, there's a command that will really help you to debug the whole process.

System.setProperty("javax.net.debug", "all");

I really hope it will help you to save sometime.

Monday, August 30, 2010

GWT: iPhone Like Buttons

In a new entry dedicated to GWT we're going to learn how to create an iPhone like button.

The objective is to create a rounded button with an image and support for badges.

Let's compare the iPhone button with the result of our tutorial
iPhone Button
Our CoolButton

Do you like it? Then stay with me for the How To.

Create the new Widget

We'll start creating a new Composite Widget, we'll call it CoolButton.

public class CoolButton extends Composite implements HasClickHandlers,
  ClickHandler {

 private final AbsolutePanel wrapper;
 private final PushButton pushButton;
 private final Label badge;
 
 public CoolButton(Image buttonIcon) {
  
  wrapper = new AbsolutePanel();
  badge = new Label();
  badge.setStyleName("badges");
  badge.setVisible(false);

  pushButton = new PushButton(buttonIcon);
  pushButton.setStyleName("CoolButton");

  wrapper.add(pushButton, 0, 20);
  wrapper.add(badge, 40, 10);
  wrapper.setWidth("75px");
  wrapper.setHeight("80px");

  this.addClickHandler(this);

  initWidget(wrapper);
 }
 
 @Override
 public HandlerRegistration addClickHandler(ClickHandler handler) {
  return addDomHandler(handler, ClickEvent.getType());
 }

 @Override
 public void onClick(ClickEvent event) {
  //toggleButton.fireEvent(event);
 }

 public void setEnabled(boolean enabled) {
  pushButton.setEnabled(enabled);
 }

 public void setBadge(int total) {
  if (total > 0) {
   badge.setVisible(true);
   badge.setText(String.valueOf(total));
  } else {
   badge.setVisible(false);
  }
 }
}

We'll analyze this code:

We're creating a Composite Widget, so basically we're creating a wrapper around already existing Widgets and adding some logic on top.

private final AbsolutePanel wrapper;
 private final PushButton pushButton;
 private final Label badge;

For you Widget we're using an AbsolutePanel, a PushButton and a Label.

The PushButton is our main component. It's a real button and displays an image, so it's perfect for our needs. The Label will be used to show the badge. Finally, the AbsolutePanel will allow us to layout the components, overlapping them to create the desired effect.

public CoolButton(Image buttonIcon) {
  
  wrapper = new AbsolutePanel();
  badge = new Label();
  badge.setStyleName("badges");
  badge.setVisible(false);

  pushButton = new PushButton(buttonIcon);
  pushButton.setStyleName("CoolButton");

  wrapper.add(pushButton, 0, 20);
  wrapper.add(badge, 40, 10);
  wrapper.setWidth("75px");
  wrapper.setHeight("80px");

  this.addClickHandler(this);

  initWidget(wrapper);
 }

In the constructor we create the badge label, and hide it by default. We'll show it later if needed. We create also the button with the specified image.

The tricky part here is the use of AbsolutePanel. The AbsolutePanel doesn't resize automatically to show properly all its children, as other LayoutPanels, so we need to position everything manually and make sure that it will fit.

wrapper.add(pushButton, 0, 20);

We place the button in the coordinates 0,20 that leaves some vertical space on top of the button that will be needed to place the badge.

wrapper.add(badge, 40, 10);

The badge is placed in the coordinates 40,10 so vertically will overlap with the button, and horizontally will be close to the right side.

wrapper.setWidth("75px");
wrapper.setHeight("80px");

Finally we make sure we've enough space to show everything.

All these coordinates and sizes are hardcoded, because they're relative to the image size.

The rest of the code doesn't have too much mystery. Since it's a button we need to add the needed code to fire the ClickEvents and register a ClickHandler. Also we need a method to set the badge and properly show and hide it.

With that we've our widget done. Now we need to attack the styling, so take a look to the CSS.

.badges {
 text-align: center;
 display: inline-block;
 font-size: 16px;
 color: white;
 background: #ff3333;
 border: 2px solid white;
 padding: 0px 5px;
 -moz-border-radius: 15px;
 -webkit-border-radius: 15px;
 -moz-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.5);
 -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.5);
}

The badges style is quite simple, but let's check the different elements:
  • color: Defines de text color
  • background: defines the color of the background
  • border: defines the white border
  • border-radius: defines de rounding border (for Firefox and Webkit)
  • box-shadow: defines a tiny shadow for the badge (also for Firefox and Webkit)
.CoolButton {
 padding-left: 2px;
 padding-top: 2px;
 cursor: pointer;
 border: 1px solid black;
 -moz-border-radius: 5px;
 -webkit-border-radius: 5px;
 -moz-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.5);
 -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.5);
 background: #00b5e2;
}

The button style is again the same CSS elements.

Note: That's not the case in our example, but GWT doesn't recognize properly some CSS styles, for those cases we need to wrap it in a literal call

background: -moz-linear-gradient(top, #e4e4e4, #cfcfcf);
background: literal("-webkit-gradient(linear, 0% 0%, 0% 100%, from(#e4e4e4), to(#cfcfcf))");

And that's it. You can download the code from the next link: iPhoneDemo - CoolButton

See you soon.

Monday, August 16, 2010

GWT: Best 5 GWT Libraries

Continuing with the GWT series we're going to see some of the best GWT libraries.

Ext GWT

Ext GWT, also known as GXT, is a complete widget library for GWT. It gives you Grid, Trees, Drag&Drop, Forms, Data Binding and much more.

The beauty is that everything comes perfectly integrated and works perfectly with GWT. GXT can be compared with SmartGWT, but the main difference is that SmartGWT is a wrapper around a JavaScript library, but GXT is a pure GWT implementation.

If the GWT widgets are not enough for you application, that should be your first option. GXT has a Commercial and Open Source license, so if your application is not Open Source, you'll need to pay.

GWT-Mosaic

GWT-Mosaic is a great expansion to the standard GWT library. Distributed with an Apache License, allows you to use it in any application.

GWT-Mosaic provides enhanced Trees and Tables, compared to GWT. But probably the best feature is the layout implementation. If you're used to the Swing layouts, you'll feel at home. On top of that it also provides a great Form and DataBinding support.

Probably the main complexity is mixing the Mosaic layouts with GWT components. But checking the demos and documentation helps to solve it. As a best practice tip you need to remember only that: don't insert a Mosaic layout inside a GWT layout.

GWT-DND

GWT-DND is one of the basic components of other libraries, like GWT-Mosaic and GWT-Cal. Distributed with an Apache License only makes it better ;)

GWT-DND provides all the needed support for all type of Drag&Drop operations, you can even expand them for your own needs.

GWT-Log

GWT-Log is the best option nowadays to have client side logging capabilities. The lack of a real logging system is probably one of the big missing features of GWT, but GWT-Log solves it perfectly.

It even provides multiple ways of see the logs, allowing to send the logs to the server, show them in a window or a console client side. As any log system is possible to configure the logging level.

GWT 2.1 implements java.util.logging emulation that seems will be able to super-seed this library, but until it's released, GWT-Log will still be an irreplaceable library in my GWT projects.

GWT-Cal

GWT-Cal is probably my favorite GWT library. If provides a great looking a really flexible calendar component for GWT projects. If you need an iCal / Outlook / Google Calendar component, don't look more, that's what you need.














Why do I like it? Well mainly because is the core part of the GWT application I'm working with, but also  because both developers are really helpful and collaborative.

Conclusion

As you can see all the proposed libraries are based in Apache License, except GXT and GWT-Cal. As I said at the beginning, if GXT covers your needs, don't make your life complex and use it.

Before using any GWT library, check that's really a GWT library and not a wrapper around a JavaScript library. The main problem with this kind of solutions is that are hard to mix with pure GWT components and usually slower and harder to expand.

As a last tip remember that any extra library that you add to your project will have 2 side effects: the compilation of your application will take longer and your application will need to load bigger files.

See you soon.

Friday, August 13, 2010

La Odisea del iPhone 4

El pasado viernes 30 de Julio de 2010 recibí una amigable llamada de un comercial de Movistar ofreciéndome el iPhone 4. La verdad es que la oferta era muy tentadora, pero quería ver que me ofrecía Vodafone, por lo que quedé con el comercial que me llamaría el siguiente martes.

Hablé con un comercial de Vodafone y me dijeron que la única opción era a través del programa de Puntos (me tocaba pagar más de 300 euros). Así que llame al departamento de bajas, donde me dijeron lo mismo. Les digo que tengo 2 líneas y que me llevaré las 2 a Movistar. Nada, que adiós....

El martes 3 de Agosto me vuelve a llamar el comercial de Movistar y le digo que acepto la oferta. Me confirma que recibiré el iPhone4 en 1 semana y que la portabilidad de línea se realizará el viernes 13 de Agosto. El iPhone4 me sale por 69 euros y contrato la otra linea con un Nokia Navigator para mi mujer. Perfecto!!!!

El miércoles 4 de Agosto recibo una nueva llamada, diciéndome que en estos momentos no hay disponibilidad de iPhone4 y que como cortesía me enviarán un iPhone3GS hasta que el modelo solicitado esté disponible, y que para compensar las molestias me descuentan 40 euros del iPhone (ahora sólo me costará 29 euros) Me dicen que no me preocupe y que se mantienen las fechas.

Llegamos al jueves 12 de Agosto, ni rastro del terminal ni de las tarjetas. Llamo al 1004 y me confirman que durante el mismo jueves recibiré el paquete.

Estamos a viernes 13 de Agosto y no hay rastro del terminal. La portabilidad se ha realizado y estoy sin línea. Vuelvo a llamar al 1004 y, sorpresa, resulta que el iPhone3 llega HOY al almacén. Sí, sí, el iPhone3, el de cortesía para que no me quedase sin línea. Y que no está previsto que yo lo reciba hasta la próxima semana.

La única solución que me dan es solicitar un duplicado de la tarjeta y que me abonarán el coste en la próxima factura. Claro para eso necesito tener un terminal de Movistar.

Mientras espero alguna solución estoy sin línea y la única solución es que me busque la vida.

Movistar: Ya recuerdo porqué me marche hace 3 años. Apenas llevo unas horas con vosotros y ya me arrepiento :(

Os mantendré informados.

Monday, August 9, 2010

PC vs Mac (from Microsoft Point of View)

Microsoft just opened a new page on their website comparing PCs and Macs in an attempt to counter attack the "Get a Mac" campaign.

I'm sorry to say that even when Microsoft as all the right to play to the same game as Apple, the reasons they are showing are, at least, weak:

Having Fun

It's true that's not possible to play Blue-Rays in a Mac or connect it to an XBox. The first is due to an Apple's decision and the second is probably because either Microsoft or Apple are interested in this kind of connection.

Regarding the problem of connecting a Mac to a TV, really I've done it and it's not a big deal. Sure you need an special connector, but works fine.

The lack of games in the OSX OS seems that's finally changing and shouldn't be an issue in the near future.

In any case these could be reasons for a home user, but no company should be stopped due to these points.

Simplicity

The computer that's easiest to use is typically the one you already know how to use. Another nice one is Unlike Macs, many PCs running Windows 7 support Touch
To me that's a really weak reason. In fact if you saw my post from some days ago I would say that OSX is much more easier to use than Windows.  Apple is a reference regarding usability and OSX is a really easy system to use. Just think about how easy is to install something in OSX. 

Also in OSX there's almost no need for antivirus or other maintenance programs. Try to do that in Windows and you'll see how works.

Affirmations as "the mouse works differently. And many of the shortcuts you're familiar with don't work the same way on a Mac" Sound really egocentric to me. Sure they are different, but I don't think that anyone would need more that 5 minutes to learn them.

The last one is hilarious "Unlike Macs, many PCs running Windows 7 support Touch" Is Microsoft the only one that missed the "Magic Mouse" and "Magic TrackPad" devices, not to talk about the normal TrackPad in the MacBooks. We could also talk about the touch support in iPhone and iPad, but since are not using OSX (yet) we'll leave them aside.

Working Hard
If most of the computers in your office or school run Windows you may find it harder to get things done with a Mac.

Can we apply the same argument if most of the computers use OSX? I'm using my MacBookPro in a network with Windows and Linux computers and I don't have any problem accessing to any kind of file. iWorks works perfectly well with Office documents (even OpenOffice work fine) and accessing the network drives is not a problem.

Or maybe Microsoft means that Windows is really bad sharing files with different OS (sarcastic mode off).

Sharing

Macs don't like share. I'm sorry but I don't known what is Microsoft talking about. The Macs can share using NFS, Samba or even the beautiful "BonJour" system. That's an affirmation without any base or explanation.


Compatibility
Plain and simple, if you're a PC user, lots of your favorite stuff just might not work on a Mac. With PCs outselling Macs 10 to 1, the reality is that most computer software is developed to run on PCs

Let's start with the most obvious point that's "More doesn't mean better" Also again the affirmation is quite egocentric. Almost all the most important programs have an OSX version or a substitute. And in most of the cases the OSX version is as good as the Windows version, or event better.


Choice
PCs give you a lot more choice and capabilities for your money. You can get the PC you want, in the size and color you want, with the features you want. You just don't have as many options with a Mac.

That's again quite obvious. When only 1 company is making Mac computers is not possible to have all the combinations that Windows have with all the hundreds of manufacturers of PCs. Again they are mixing quantity with quality.

One of the main problems of Windows stability is that Windows needs to work with thousands of hardware combinations, and not all the drivers are as stable as expected. Meanwhile Apple keeps a low number of hardware combinations, making easier to keep the stability.

As another point, I think is hard to find in the market more beautiful and well design computers than the Macs.

Conclusion

I known that seems that I'm an anti-Microsoft guy. That's not the case, but I got pissed off with the weak excuses that Microsoft is showing to publicity their operating system. Most of the affirmations are simply false, and the others are quite subjective.

What do you think?


Thursday, August 5, 2010

GWT: Extend The DatePicker/CalendarView

We're going to start this series of articles related with GWT with a tutorial about extending the DatePicker/CalendarView.

With the DatePicker you can choose any date in a Calendar and browse through it. The DatePicker uses internally the CalendarView class to configure the way the Dates are showed.

The nice thing about the DatePicker is that is really simple to use, but this simplicity comes with a high cost for Enterprise developments: It's really hard to extend, since is highly dependent of internal classes.

One of the most requested features is the ability to limit the valid dates, basically configuring a minimum and a maximum date.

To accomplish that we need to extend the DefaultCalendarView class.

In you GWT Project create a new com.google.gwt.user.datepicker.client package in your /src directory

Go to the GWT subversion repository and copy the DefaultCalendarView file to your code.

Now we're going to start doing our changes:

Create a new constructor adding support for the minimum and maximum dates and define the new variables

private Date minDate = null;
 private Date maxDate = null;

 /**
  * Constructor.
  */
 public DefaultCalendarView() {
 }

 /**
  * Constructor.
  * 
  * @param minDate
  *            Minimum allowed date.
  * @param maxDate
  *            Maximum allowed date.
  */
 public DefaultCalendarView(Date minDate, Date maxDate) {
  this.minDate = minDate;
  this.maxDate = maxDate;
 }

Ok that was easy, now we can define which are the minimum and maximum valid dates, but that's still doing nothing by itself

The easiest way to accomplish our objective is to disable the non-valid dates in the calendar, so let's modify the ......

@Override
 public boolean isDateEnabled(Date d) {
  if (minDate != null && maxDate != null) {
   if (d.after(minDate) && d.before(maxDate)) {
    return true;
   } else {
    return false;
   }
  }
  return getCell(d).isEnabled();
 }

We are almost done. Now let's modify the update method of the CellGrid subclass.

public void update(Date current) {
    // * Another Tweak *//
    setEnabled(getDatePicker().isDateEnabled(current));
    getValue().setTime(current.getTime());
    String value = getModel().formatDayOfMonth(getValue());
    setText(value);
    dateStyle = cellStyle;
    if (isFiller()) {
     dateStyle += " " + css().dayIsFiller();
    } else {
     String extraStyle = getDatePicker().getStyleOfDate(current);
     if (extraStyle != null) {
      dateStyle += " " + extraStyle;
     }
    }
    // We want to certify that all date styles have " " before and
    // after
    // them for ease of adding to and replacing them.
    dateStyle += " ";
    updateStyle();
   }

Note that we only changed the first line of the method, so we are not enabling the cell by default anymore, but we're checking if should be enabled.

The last missing part is that the DatePicker class needs also to be extended to use our new code:

public class DatePickerEx extends DatePicker {

 public DatePickerEx(Date minimum, Date maximum) {
  super(new DefaultMonthSelector(),
    new DefaultCalendarView(minimum, maximum), new CalendarModel());
 }

 public DatePickerEx(MonthSelector monthSelector, CalendarView view,
   CalendarModel model) {
  super(monthSelector, view, model);
 }
}

For your convenience you can also download the code in this archive

We're done. Enjoy your new DatePicker.

Introduction to GWT

This is the Part 1 of what I expect will become a series of articles about my personal experiences when developing with GWT.

Some months ago I started a project with GWT for my current employee. This was my first GWT project, so I needed to do some research and quite a lot of proof of concept, to make sure I could cover all the requested features.

What’s and what’s not GWT
 

That’s what Google says about GWT in their official page. 
Google Web Toolkit (GWT) is a development toolkit for building and optimizing complex browser-based applications. GWT is used by many products at Google, including Google Wave and Google AdWords. It's open source, completely free, and used by thousands of developers around the world. 
In this paragraph we have the first key about what’s GWT “is a development toolkit for building complex browser-based applications”. GWT is not the toolkit to use in your homepage or a simple website. For those tasks it’s much better to use pure Javascript toolkits (like JQuery) or maybe some PHP backend. 

GWT is useful when you want to create complex enterprise browser-based applications. But “what’s a complex enterprise browser-based application”? 

Well, I imagine that really depends, but I would say that any browser-based application that requires support for multiple simultaneous users, access to some backend with complex rules and wants to use a rich user interface. 

GWT only solves the rich user interface part, but is a perfect complement for a J2EE backend, allowing an easy integration and a rich experience. 

How is different GWT from other web toolkits? 

I would say that the most important difference is that when developing you only need to known Java, there’s no need to known anything about HTML or Javascript (even when it helps when you need to do really complex features) 

Ok, but JSP or IceFaces/RichFaces also allow to do that. Yes and no. JSP is the Java equivalent to PHP. That means that you need to known HTML and Javascript and inject the PHP in the middle. IceFaces/RichFaces are a really good alternative. In fact I almost choose IceFaces for my project, but the widgets and the flexibility of the components where not matching my expectations. 

Why should I choose GWT? 

For me GWT was the correct solution due to multiple factors:
  • Google is putting quite some efforts in this toolkit and the community around it is really active
  • GWT can be easily customized using CSS and even with direct DOM interaction
  • There are some really interesting extensions for GWT
    • GWT-Cal: Covert one of my main requisites and the developers are really friendly and helpful
    • GWT-Mosaic: Perfectly complements some missing feature and widgets in GWT
    • GWT-Log: Nice and easy integrated logging system
    • GWT-DND: Wonderful Drag&Drop API
Is everything that good? Really?
Well, not really. When I started my project I used SmartGWT. At the beginning it was awesome, everything was really simple, tons of widgets and a lot of people giving good reviews.
I was decided to use it, in fact I even started my project using SmartGWT, but not everything was that perfect.
When using SmartGWT I started finding problems, some were more annoyances than bugs, others required tons of extra work. My first disappointment came from the lack of help in the official forums. In fact I was even surprised by the hard reaction of some of the developers with some users questions. The next problem came when I tried to modify the theme. Was a complete nightmare, everything seemed like a problem and I found myself investing too much time in something that should be really simple.
By then I knew enough to create my own components and libraries like GWT-Mosaic only made everything easier. So I took the way that I wanted to avoid using SmartGWT, but at the end was easier than expected. And now I could use simple CSS and PNGs to create my UI.
Conclusion
Here I finish the first part of these tour through GWT. As you saw GWT is easy enough to use, but powerful enough to tweak it as you want. The ecosystem of libraries is rich enough, but keep always in mind what to you want to achieve.
In the Part 2 I will show you how to create some nice effects and widgets in GWT.
See you soon.

Wednesday, July 28, 2010

Switching Experience (I finally moved to Mac)

I finally did it, I´m finally a switcher. Last month I bought my first Mac (a new MacBook Pro 17” i5) I have been playing with the idea of buying a Mac since some time ago, but I never found a good excuse or reason. When last month my laptop start dying (a 4 years old Fujitsu) I decided it was the proper time to jump to OSX. I was a Windows user for more than 10 years (I started with Windows 3.0), 5 years ago I started to use Linux seriously and 3 years ago was already my main working environment. I must say that I´m a happy Linux user, but the idea of doing some iPhone/iPad application  was the final push to move to Mac.


My first 5 minutes
I always though that all the buzz around the Apple products was exaggerated. As you may known, I got an iPod in Christmas and I´m really happy about it, but I didn’t felt what was owning an Apple product until now.
The box design was beautiful, there is a magic sensation when un-boxing the computer. I saw a nice box with the CDs and some simplified manual, but I took the shortcut. I simply put the MacBook at the table, I connected the power adapter and turned it on.
My kids where playing around, without paying attention to Daddy (in fact there’s nothing weird if Dad is in his computer, right?). But at the moment the MacBook turned on the first time, the speakers started playing a nice music, the screen was filled with a great welcome presentation and both of them came to see what was that. My 2 years old kid directly sit down saying “Daddy, it’s cooool”.
The whole OSX configuration took 5 minutes, asking from time to time for some information. Everything was really easy and straight forward, without any complex stuff. When it finished I had a completely working OS running.
Ok, what do I do now?
Perfect, it’s working, and now what? That was not my first time using an OSX, so probably for me was faster to start playing around that for a normal Windows user. Anyway I really felt at home. Everything was responding really fast and things where really intuitive. I went to Preferences to configure the multitouch trackpad and I was simply wordless when I saw the way the different gestures are explained.
Then I playing a little bit with my kids and the “Photo Booth” application. OSX doesn’t come with games, but I can say that the “Photo Booth” application can be really funny :)
Time to get serious, where are my apps?
The first thing I did was to install all my usual communication, browsing and other common applications. So I started installing Firefox, Google Chrome, Skype, DropBox, OpenOffice, VirtualBox, VLC, FileZilla, Transmission and TrueCrypt (see Essential List of the Best Mac Free Downloads for more recommendations). But I was still missing some functionalities from my Linux/Windows machines.
My first problem was to find a proper replacement for 7Zip. After some googling I found a really nice project which solved my needs perfectly: Keka.
Next problem, I wanted to properly play my DivX and Xvid files using QuickTime. VLC is really great, but I’m always looking for the best integrated solution. This time the answer came from the Perian project.
Ok, now I can browse, execute my virtual machines, use my compressed files and play my  video files.
My first surprise came when I tried to access my external drives. Both of them are formatted using NTFS, I simply connected them and I could access my files perfectly .... but I was not able to modify them !!!! Back to Google and I find that there’s no NTFS writing support in OSX. The solution came from Tuxera, but I find it really slow, so I’m still looking for an optimal solution
Time for the Developer
Until now I was able to cover all my basic needs, but now was time to configure my future development environment.
As I already said, I always try to use the best tool for my projects, so I don’t hesitate to install different IDEs and tools if I get some benefits.
So I first started with my NetBeans installation. Then I followed with Eclipse 64bits and I must say that the speed difference with my Linux Eclipse is amazing. The version in OSX runs like a breeze and feels much faster. Then I followed with “Komodo Edit” which is quite powerful when working with scripting languages and finally I got the XCode from Apple, just to start learning Cocoa and Objective-C.
So I can now continue working with my different projects, but I’m still missing a good way of working with my Subversion repositories. I known, both Eclipse and Netbeans have SVN plugins, but I always feel limited when using them, compared to the power of TortoiseSVN + WinMerger.
Back to Google and my second problem. There’s nothing that can be compared with my Windows TortoiseSVN + WinMerge or my Linux RabbiVCS + Merger. After some search and testing I found CornerStone, Versions and Kaleidoscope. Even when from a visual point of view these are amazing tools, from a functionality point of view I’m missing some basic features, like branch merging. So far I’m using my bellowed command-line svn, using the CollabNet installers.
Conclusions
Casual / Home Users: The MacBook Pro is a great tool, really intuitive and gives all the needed tools out-of-the-box
Advanced Users: Again, a great system that you can tweak as needed
Developers: I miss some of my Windows / Linux tools. The options in OSX are great and maybe I just need to change the way I do some stuff, but right now I would say that’s a good system, but needs some extra effort to make it great. 

Thursday, March 11, 2010

The True Behind the Software Patents

Finally someone said the true about the Software Patents. Since yesterday all the blogosphere is talking about the latest Jonathan Schwartz (former Sun CEO) post "Good Artists Copy, Great Artists Steal".

For years I've seen the big companies (Microsoft, Apple, Nokia, Adobe, ....) defending the need of software patents. The main reason, the excuse, was always to protect the intellectual property, the investments these companies where doing in research and development. And that's the point that was never clear to me.

Let's see. If you create a chip, or an engine, or a car, there's always a big amount of work, design, engineering, models, tests, .... The same could be said about a software package. Any Operating System (Windows, OSX, Linux) or production software like the ones created by Adobe, Microsoft, .... All of those cannot be pirated or illegally copied, since there was a huge amount of work to create them.

But what happens with the Software Patents? Most of them are only ideas, and the patent owner is not always the one that had the idea. Patents like Amazon's "1-Click", or some of the crazy Microsoft patents like "the sudo command", "XML", or "the click". In Amazon's case, the "1-Click" is an obvious choice if you want a nice user experience in your online shop. Regarding Microsoft patents ... well I think it's quite obvious that they where only trolling.

Now finally someone said the true. The software patents are nothing else that a way to protect your company against trolls. The software patent alone has no value, the real value appears when you can use it to do a deal with another company so you can use the others ideas for free.

Guys, do you known something? You can do the same using some of the Open Source licenses laying around. I would really prefer more investment in real technology: new protocols (someone said IPV6 support?), better languages (HTML5 before 2015?) or simply more stable, secure and mature software.

What's clear is that Jonathan Schwartz won a new fan in me. I'm waiting to see what else he couldn't say...

See you soon.

Thursday, January 28, 2010

iPad: What can we do with it?

After months of rumors the iPad is finally here. It's a great device, but is also missing some great features, that for sure will be included in iPad v2. But right now we have a first version opening a new way (or as Apple usually does, converting an existing market).


Worldwide the media is talking about this new device, saying things like "The future is here", "The best device for ....". But, what's really the iPad? What we will do with it? How is it going to change our way of working?


Let's see different examples:


iPad in the Education


That's the first situation that comes to my mind. Maybe because I've children, maybe because in Spain the government is starting to invest in netbooks for the schools.


The iPad looks like the perfect solution for the 21st century education. Some countries are investing in netbooks (like Spain) to introduce the new technologies to our kids. But looks like the iPad is a much better choice.


The main objective of the netbook is that the children can learn how to use internet, read the text books and write their works. The problem appears when the netbook is hit by a virus, someone needs to install the applications, configure the computer, ......


The iPad can do everything that the netbook needs to do, but is also easier to manage, safer, everything can be installed easily and the UI is really intuitive. 


In fact, the iPad seems to be a winner as an educational tool.



iPad in the Company


I see the iPad in the company doing mainly 2 different jobs. 


The first one is again in substitution of a netbook. If you need to travel a lot, but you need to be always in touch, a netbook is a good option, but probably an iPad with a bigger screen and a lighter weight is a better partner. If you need a tool to write email, surf the web and read the latest news the iPad is a good solution. If you add a 3G connection and a GPS is a winner. I can foresee different scenarios where a GPS can be an extra benefit. Simply looking for the closest restaurant or hotel for a meeting is an example.


The second example is when you're always at the office, but your work request continuous walks inside the company (think of a secretary or a warehouse worker) The iPad is a good way to have all your worksheets, documents and email always with you.


Another situation (I known, I said "2 different jobs") is when your work requires an specific image. Design or Media companies are just an example of companies that are alway looking for the cooler device for their receptions, for a device that says "we care about how things look". And right now, the iPad is the best way of saying it.


iPad at Home


And of course, the iPad is also a great device to have at home. The iPhone has already proven itself as a great gaming platform, just imagine with a bigger screen. 


At home, the iPad, can be ideal as a family device for "quick tasks". Checking your email, twitter or social network is just an example. Using it as a photo album or contacts manager is just another. You can also watch your movies or series or listen your favorite music. And now you can also read books.


Most of these things were already possible with the iPhone/iPod Touch, but the screen is making here all the difference. I'm the owner of an iPod Touch, and even when I use it a lot, I cannot write more than a short answer to an email, or do a quick check to a website. I cannot imagine myself working hours with this tiny screen. But I can see myself perfectly working with the iPad, in fact, I can see myself writing in this blog with the iPad in a couple of months.


Conclusion


The iPad is far away from being perfect. The fact that doesn't have a camera is, from my point of view, an error. The apparent lack of multitasking is also a problem, the fact that the screen is 4:3 is another drawback.


It's clear that the iPad is not a computer, is not a portable console, is not an MP3 player and is not an ebook reader. 


We can only wait that the next generation will solve all these negative points. But the iPad is also a bit of everything, and that's its strength.


See you soon.

Friday, January 1, 2010

Is Desktop Development Dying?

After the Oracle/Sun issue and the poor Java 7 announcement, a lot of people has been talking about the "Java is Dead" issue. I completely disagree with this statement, but I really think that something is dying: desktop development.

Last year's improvements in languages and frameworks related with desktop development can be easily reduced to CUDA and OpenCL (please tell me if I'm missing something else). The improvements in frameworks for desktop applications was null (at least in the Java world). On the other hand, let's check other technologies and see the consolidation of the "App Store" and the whole iPhone OS world, how well Android is doing (maybe slower than expected), the quality jump in the Google WebToolkit, Google Chrome OS, the consolidation of Cloud Computing, ....

All these technologies are related with mobile development, web development, ... but desktop development is not following. From my point of view, desktop development is stuck at the same place since some years ago. Let's see what will bring the next year, but so far all the buzz seems to point to the same place, again mobile development.

Not so many years ago a lot of people was looking the whole HTML/JavaScript coding as "second class development" (well maybe was not that many), but nowadays it's an essential part of any developer work. Almost all the restrictions that we had 10 years ago to do "web applications" are gone. And the rest will disappear when HTML 5 finally arrives. So if there's any of you that's still not looking into this new world, it's about time to jump into it ;)

See you soon,

Tuesday, December 22, 2009

The iPhone/iPod As an IT Tool

It's not Christmas, but I've already got my present :) Some days ago, my current employee, gave me an iPod Touch 2G. It was not a simple present, but also a tool to work with a new iPhone application that we're developing.

As many of you, I'm working in a small company. My main job is as developer, but I'm also doing some IT and technical support work, so I was curious to see how could the iPod help me with these tasks.

As I said, I have an iPod, but everything explained here is also applicable to the iPhone. In fact the iPhone is even more useful since you don't need to look for a WIFI connection ;)

Let's start:

A Communication Tool

Here we will see how can we use the iPhone as a communication tool:

  • Mail: Configure your e-mail accounts (check here for the documentation to setup your email accounts)
  • Skype: Even if you have an iPod, you can use Skype to stay in contact with your friends and colleagues. If you also want to talk, you'll need to buy a headphone+microphone kit.
  • Social Networks: Almost all the social networks have an iPhone widget. In my case I installed Facebook, LinkedIn and Twitter (Twitterrific). But you can also find widgets for Xing, MySpaces, ...
An Administrator Tool

Let's see what do we need to have control over our computers and network:
  • Network Ping Lite: It's a simple application that gives you the power of ping, traceroute and telnet commands
  • Mocha VNC: With this tool we can control any computer with a VNC Server installed.
  • iSSH: Another great application. With this one I've all the power of an SSH console, but I can also do remote X connections
  • VPN: Integrated in you iPhone is a cool VPN client, so you are never outside your network.
  • iNet Pro: With this one you can ping, scan ports, scan network, ...

Other Useful Tools

That's the miscellaneous section where I list other tools that I feel are really useful
  • DropBox: Does it even need a presentation?
  • GoodReader: A really good PDF reader
  • AppBox Pro: It's a useful package with different applications.

I'm still investigating what other cool things I can do, but what's your preferred iPhone application?

Sunday, November 8, 2009

How to Properly Comment Code? (Part II)

It took longer than expected to find the time to write the second part, but finally here it's

For some reason, the last month has been full of articles about commenting code, like Is Commenting Your Code Useless?, Code Comments: The Lowest Form of Communication or Comments are a sign of bad code

You're free to visit those sites and see their arguments. I must say that I only agree with the first of them, in fact this article is almost a duplicate of his arguments.

When should I comment my code?

To properly answer this question you need to look at your code and think if your comment is improving in some way the understanding of what you're doing.

// We're done
isDone = true;

Is not really helpful, is it? Your comments must aggregate some value to your code, otherwise are worthless.
Also you must always keep in mind that your code should be clean enough that's self-descriptive. Keeping your code self-descriptive have 2 benefits. The first one is that you'll not need to add comments, the second, and most important, that will make things easier when arrives the time to maintain it  (and believe me, this time will come).

Only in the case that your code is not descriptive enough, you must add a comment. Is that bad? not at all.

My code is self-descriptive, why should I comment it?

Some pieces of code can be quite complex, mainly when you work in real projects. You only need to thing about financial, graphic or simulation software. They require tons of complex coding to achieve their objectives and it's usually quite hard to get the mentioned self-descriptive code.

Even when your code can be really clear, the purpose of this code may be not. I'm going to copy a good example from Jani

//Calculate if two circles intersect
$xd = $c2->x - $c1->x;
$yd = $c2->y - $c1->y;
$diameter = $c1->radius + $c2->radius;
$intersection = ($xd*$xd + $yd*$yd) < ($diameter * $diameter);


Simply reading this code would be a bit hard to known what's happening. The variable names could help, but the comment is giving us the final information

Monday, September 28, 2009

How to Properly Comment Code? (Part I)

If you do a search in Google for "code comment" you'll find 216,000 hits and if you do the search for "comment code" you'll find 505,000 hits. Then, why is so difficult to find properly commented code?

The first point that I want to clarify is that I'm talking about "commenting code" not "documenting code" which is slightly different.

The code documentation is used to generate the API documentation, to known which methods are available, what arguments are accepted and what's the result of the call. The documentation is destined to be used and understood by the users of your code (like users of you code library and/or classes).

On the other hand, the code comments are helpful to understand the internals of your methods. Usually these comments are only read by your colleagues.

Now that the difference is clear we can continue.

As developers we usually ignore or forget the "code comments", but we always try to write some information (even minimum) when is related with the "code documentation", we even have tools to autogenerate the documentation or whine if it's not correct.

Why do we keep forgetting and ignoring the "code comments"? From my point of view there are 2 main reasons:

"It's not needed"

That's what we think when we're writing new code. At the moment the code is always so clear and beautiful that there's no need to document it. Why should we spend time? Who can be so dummy that needs extra info about our code?

Well the dummy guy that will need this comment is usually ourselves. When we come back to this block of code in the future, things will not look so clear and obvious.

"Laziness"

That's the other major reason. The typical "I'm really busy right now, I'll do it later". You known what? If you leave it for later, is almost sure that never will happen.

The lack of proper comments in our code is always going to come back in the future and bite us.

The next day we'll see some tips about how to properly comment our code.

See you.

Friday, September 18, 2009

StackOverflow and the Lazy Developers

Hi again,

During the last days I've been looking deeply into StackOverflow and I must confess that's a great source of information and knowledge. But I've also found something that worries me a bit, lazy developers.

Most of the questions in StackOverflow are really valid. Complex questions about special cases, people looking for the help of a more experience developer or even questions that can be due to a lack of knowledge in an specific subject or a part of a language or API. But I've also found a big number of questions that can only be caused by pure laziness.

Why am I saying that? Because simply putting the question keywords in google you can find the answer. I've even seen cases where the first result in Google points to the valid answer (sometimes even inside StackOverflow).

Why does it worry me? Because I've always believed that a software developer must be capable of reading documentation, creating test cases and find solutions by himself (doing trial and error if needed). If we just limit ourselves to ask the most simple questions, means that we don't care enough about what we're doing. If we just ask about stuff that can be easily in our language/API/SDK documentation, I don't want to think what we'll do with more complex problems.

This behaviors will produce tons and tons of copy&pasted code in our programs and will create a generation of developers unable to think by themselves, solve the most easy problems or understand the real consequences of the pieces of code they write.

See you soon.

Monday, September 7, 2009

Howto Install SwingX in NetBeans 6.7

Today I feel like doing some graphic stuff in my pet application. Even when Swing is really nice, I usually miss a lot of more cool effects. Just thinking in all the needed code to create an usable JTable gives me a headache.

So I've decided to use SwingX. For those of you that doesn't know about SwingX, please check their website, but as a resume I will simple say that are a collections of advanced Swing components and that some of them will become part of the default Swing set in JDK 7.

Let's start the party:

Download SwingX to you computer

You can do it from here: SwingX Download. Now I would recommend you to unpack it.

Add SwingX Library to NetBeans
  1. In NetBeans go to Tools -> Library Manager and click the "New Library..." button
  2. Type a name: SwingX
  3. Now in the ClassPath tab you need to add the jar files you will find the /dist
  4. (Optional) You can also add the SwingX sources and documentation (The SwingX 1.0 javadoc zip file is incomplete, but I used the "Hudson Continuous Build Javadoc" without problems)
Add SwingX to your Project
  1. Right click on your project and choose "Properties"
  2. Select the "Libraries" section in the left tree
  3. Now click in "Add Libraries..." in the right panel
  4. Select the Library you created in the previous step ("SwingX" if you followed my suggestion)
  5. Finally hit the "Add Library" button
Add SwingX Components to the Palette
  1. Create or open a GUI class form. You'll then see the Palette on the right side (by default)
  2. Right click on the Palette and choose "Palette Manager..."
  3. Click "New Category..." and choose a name. I would suggest to type SwingX again.
  4. Select the newly created category and choose "Add from Library..."
  5. Now choose all the components you want to have available (use Ctrl+A to select all)
  6. Finally choose again the "SwingX" category
  7. Click "Finish"
We're done. Now you can use the SwingX components in your NetBeans Projects.

Happy coding

Thursday, September 3, 2009

The Best Way of Working with Zip Files in Java

Finally I found the best way of working with zip files in Java :)

In one of my hobby projects I need to work intensively with compressed files (mainly zip files). My first approach was to use the java.util.zip package, but was too slow. So I started looking for other options.

My second approach was to create a wrapper for the 7zip executable (so I could have cross-platform support). This approach was much better, from a performance point of view, but to retrieve any info I needed to parse console output and solve a lot of problems with the java.lang.Runtime class.

Today I've finally found the best solution .... but before some really simple comparations:

java.util.zipHome Made
7zip.exe Wrapper
"Best Solution"
Extract All 1220341094094
Get Number of Elements4000410978
  • All the measurements are in milliseconds
  • The test was done with a 104MB zip file containing 110 jpg files.
  • The "Get Number of Elements" with the "Home made Wrapper" is also done extracting everything and counting the number of files (I'm sorry I was a bit lazy here)
I don't think that I need to add too much to these numbers. The integrated Java zip package is nice, but painfully slow.

And finally is time to show the "Best Solution" and an example comparing it with the Java zip code ;)

The winner is "7-Zip-JBinding" and has they explain in their website:
7-Zip-JBinding is a java wrapper for 7-Zip C++ library. It allows extraction of many archive formats using a very fast native library directly from java through JNI.

Get the Number of files using java.util.zip
    static public int getSize(File file) {
ZipFile zf = null;
int total = -1;

try {
zf = new ZipFile(file);
total = 0;
for (Enumeration e = zf.entries(); e.hasMoreElements();) {
e.nextElement();
total++;
}
zf.close();
} catch (ZipException ex) {
Logger.getLogger(Zip.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Zip.class.getName()).log(Level.SEVERE, null, ex);
}

return total;
}

And the same with 7-Zip-JBinding

public int getSize (File file) {
RandomAccessFile randomAccessFile = null;
ISevenZipInArchive inArchive = null;
int total = -1;
try {
randomAccessFile = new RandomAccessFile(file.getAbsolutePath(), "r");
inArchive = SevenZip.openInArchive(null, // autodetect archive type
new RandomAccessFileInStream(randomAccessFile));

total = inArchive.getNumberOfItems();

} catch (Exception e) {
System.err.println("Error occurs: " + e);
System.exit(1);
} finally {
if (inArchive != null) {
try {
inArchive.close();
} catch (SevenZipException e) {
System.err.println("Error closing archive: " + e);
}
}
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
System.err.println("Error closing file: " + e);
}
}
}

return total;
}

As you can see the code is quite similar, but the performance is quite different.

See you.