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.