SSLPeerUnverifiedException and debugging SSL connections

I’ve faced the problem of having to deal with a strange exception seen in our application log:

javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated

See full trace in a pastebin.

Looking about this you can find lots of things. Some are a bit mi leading and others give good grasp about what’s happening.

The context here is, we have an edge API that uses other internal API for random access data. We could see this problem for some of the requests (so it was not due a self-signed certificate or anything related). I’m attempting to share my experience of what has happening at the end.

Catching the exception

I started by catching the exception and trying to provide a bit more information about the requests that were producing the exception. I could not find any pattern about the type of requests.

Connection timeout?

One of our sysadmins pointed out that the problem could be generated by the socket timing out during the SSL handshake, as it’s pointed out in the following JIRA ticket: https://issues.apache.org/jira/browse/HTTPCLIENT-1070

While this could be the cause of the problem, we wanted to make sure that this was the case.

Analysing SSL errors

The “How to Analyse Java SSL Errors” post from dzone.com give me a good light about how to proceed. So I turned on the SSL debugging information by adding the following parameter when starting the server and try to find the problem:

-Djavax.net.debug=ssl:handshake

This is what I found:

qtp978883631-84, WRITE: TLSv1 Alert, length = 2
qtp978883631-91, WRITE: TLSv1 Handshake, length = 48
qtp978883631-84, called closeSocket()
qtp978883631-84, IOException in getSession():
    java.net.SocketTimeoutException: Read timed out
qtp978883631-84, called close()
qtp978883631-84, called closeInternal(true)

This is a great indicator that as our Systems guy was suggesting, connection is timing out during the SSL handshake.

At the end

The way I’ve tackled this issue is by silencing this kind of exceptions. We could have tried retrying the connection but we thought that the information provided by the second API is not as important and we will have the chance of trying again later in the following requests.

 

 

 

 

 

Llega Java 8

Que hay de nuevo en Java 8?

Ya llevo tiempo programando en Java y toca recopilar un poco de información para ver que incluye la nueva versión de Java 8.

Esta vez escribo en Español porqué en Inglés ya hay mucha literatura al respecto.

Expresiones Lambda

Es una nueva funcionalidad del lenguaje que nos permite incluir “funcionalidad” a los parámetros de los métodos. Es mas que el “sintactic sugar” (como dicen algunos), pues el compilador puede usar el contexto de la expresión para determinar la interfaz usada y resolver el tipo de los parámetros automaticamente.

Un ejemplo de la frase anterior es lo siguiente:

En vez de:

(String str) -> System.out.println(str)

Podemos hacer:

str -> System.out.println(str)

Metodos “default”

Nos permite añadir funcionalidades en las interfaces. Esto nos permite también añadir nuevos métodos a las interfaces sin romper todas las implementaciones actuales (backwards compatibility).

El comportamiento de este tipo de métodos es el que podemos intuir por su nombre: Cualquier clase que implementa una interfaz pero no sobre-escribe el método, va a adquirir la implementación por defecto.

Nueva colección “Stream”

La interfaz “stream” nos permite realizar operaciones en un estilo funcional sobre stream de elementos. Representa la secuencia de objetos, de un modo similar a un iterador, pero permite su ejecución en paralelo. Permite operaciones típicas como “map”, “reduce” o “filter”.

Un ejemplo de uso de los nuevos “Streams”:

List stringCollection = new ArrayList<>();
stringCollection.add("ddd2");
stringCollection.add("aaa2");
stringCollection.add("bbb1");
stringCollection.add("aaa1");
stringCollection.add("bbb3");
stringCollection.add("ccc");
stringCollection.add("bbb2");
stringCollection.add("ddd1");
 
stringCollection
    .stream()
    .filter((s) -> s.startsWith("a"))
    .forEach(System.out::println);

Programación funcional

Java 8 trata de elevar las funciones en ciudadanos de primera dentro de la programación, justo como se trata en la programación funcional.

Por eso, se incluye la interfaz “Function”, el tipo de datos “Tuple” al mas puro estilo Scala, se añaden algunos tipos inmutable (DateTime, Streams o el Optional, así como ya lo son los String hoy en día).

Como ya hemos dicho, además de las expresiones, también incluyen nuevas interfaces que habilitan Java para un uso mas funcional. Un ejemplo de uso es el siguiente:

Function<String, String> atr = (name) -> {return "@" + name;};

Y como empezar?

Para terminar, podéis descargar Java Runtime Environment. Ahí tenéis un review con un botón al link para descargarlo.

Learning Symfony 2

There are some good friends that has recommend me to learn Symfony 2. I’ve been programming with Zend Framework (not even version two) and with our own framework at VisualDNA, so I was eager to see how the frameworks ecosystem has evolved during this 2 or 3 years that I haven’t been keeping myself updated.

I’ve done the first part of the learning stage, which consists in information gathering. In this post I only wanted to aggregate some useful resources I’ve found and that I still need to consume myself.

Reading

This is basically browsing on the Symfony 2 official documentation. It’s pretty well organised and structured.

Not much going on here, really, but I think it’s interesting to spend some time having a first read about what the official documentation says.

Practising

On the “getting started” you have already checkout and played a bit with the code, but there are two good blog posts / tutorials that look interesting:

Doing this tutorials looks really interesting but the real way to learn is to try it yourself without looking at those. Probably, think about something you have wanting to do for some time and just do it using Symfony 2, that will be IMO the best way to learn.

Videos

Finally, there is some good amount of knowledge on the Internet regarding to video material. Talks from the “Symfony Live” in Paris or San Francisco, or many other conferences that has been happening recently. Here they are:

That’s all for me. If you have any useful resource where you can learn from, please, leave a comment and I will be very happy to update this list of resources.

Tmux cheat sheet

I’m getting started using tmux, and I’ve done my own “cheat sheet”. It’s useful to do that so you write harder in your memory and you will always remember the place to look at the commands, which will be this page :) !

For those who don’t know tmux, it’s a “terminal multiplexor”, like screen (which is another similar tool). It allows user to acces multiple separated terminal sessions. Because I work remotely , this tools are really useful for me and saves a me a lot of pain. The main benefits of using this kind of tools are:

  • I can have all the time my session saved, and if I loose connection or my terminal hangs I will be able to restore it.
  • I can put multiple “panes” into the view, dividing horizontally, vertically, etc.
  • I can share session with my colleagues and we can “pair program” remotely.

Basic (outside tmux)

// create session
tmux new -s {name}

// attach
tmux attach -t {name}

// kill
tmux kill-session -t {name}

// list all sessions
tmux ls

Modes (once you are inside tmux)

Ctrl+a c        # create a new window
Ctrl+a d        # detach current client
Ctrl+a x        # kill a pane or window

Ctrl+a "        # split pane horizontally
Ctrl+a %        # split pane vertically
Ctrl+a {        # move to the left pane
Ctrl+a }        # move to the right pane
Ctrl+a o        # switch to the next pane
Ctrl+a q        # show pane numbers (used to switch between panes)
Ctrl+a space    # toggle between pane layouts

Ctrl+a j (or k) # move up or down a pane
Ctrl+a h (or l) # move left or right a pane

Ctrl+a ,        # name the window (test, vim, console, log, etc.)
Ctrl+a l        # move to previously selected window
Ctrl+a n        # move to the next window
Ctrl+a p        # move to the previous window
Ctrl+a w        # list all windows
Ctrl+a {n}      # move to specified window number
Ctrl+a ?        # list all keybindings

Ctrl+a [        # enter copy mode

Finally, let me say I’ve updated my .tmux.conf. This is the content:

# act like vim
setw -g mode-keys vi
bind h select-pane -L
bind j select-pane -D
bind k select-pane -U
bind l select-pane -R
bind-key -r C-h select-window -t :-
bind-key -r C-l select-window -t :+

# act like GNU screen
unbind C-b
set -g prefix C-a

# look good
set -g default-terminal "screen-256color"

Learning about AngularJS

Last Saturday I got the chance to go and hear Misko Hevery talking about AngularJS. Misko, who works at Google, is the creator of the framework and, while staying in his holidays in Barcelona, he was very keen to spend some time with us and introduce AngularJS to all the GDG Barcelona.

I’m going to write down some bits of information I gathered from the talk.

  • Nowadays users are happy with browsers, but developers has to put to much effort to make everything working in all versions of all browsers. Complexity kills!
  • We should have reusable components. We all copy & paste way too much code from sites like Twitter Bootstrap or any particular jQuery plugin.
  • Data binding is the link between the model and the view. Whenever model gets updated, changes are automagically propagated to the view.
  • AngularJS tries to make the web developing a process like it’s going to be in the future. It implements features that Misko suggested are going to be implemented into the future browsers.
  • The framework has been designed to be testable and has a great documentation that covers how to setup tests for you Javascript (using any test library).

If you visit the site and check the introductory videos you will get the idea pretty fast, but I wanted to put this snippet that illustrates very well how it works:

&lt;!doctype html&gt;<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>


Hello {{yourName}}!

So, as you can see in the example, it implements a lot of nice features but one of the more interesting is the Data Binding. You can bind the content of the input with the {{ variable }}. I haven’t play too much yet, but it looks really interesting. Definitely, Misko looks like he knows what he is doing, so let’s see how it evolves.

My first Katayuno

Coding Katas are small problems from a known domain, with the objective of practise basic programming elements and TDD.

Katayunos are the combination of “Coding Katas” and “Desayunos” (which means breakfast in Spanish). It consists on sitting in pairs, in front of a laptop, choose one of the available katas and programming language and have breakfast while working on the given problem practising TDD and thinking about the best approach to solve the problem.

Well, this weekend I’ve been involved on my first Katayuno experience, at Softonic offices. The practised kata was KataBankOCR, where we are given with an ASCI numbers and we have to transform that into a String, not very complex but it had an interesting point into the test.

At the first iteration, we were tackling the problem wrong. We spend some time trying to validate the input and where a bit slow because our strict state (RED – GREEN – REFACTOR) of TDD work-flow. At the end of the first iteration we were discussing about how much we have to cover with the test. On that problem, we can’t test much more than “for a given input” which is the “expected output”.

What you think about testing private methods?

Obviously you can’t test private methods straight away, but you can work around that. However, we agree that doing that is not a good test case. The main reason is that we want to test the problem, not our concrete solution about the problem. The point is that at the end of the exercise, we could switch tests and our code shall keep passing both tests.    

On the second iteration we got it right (in PHP) and in the third and last iteration I had the chance to play with Jasmine, a test library for Javascript (pretty cool stuff). I’ve uploaded my code into Github. Pretty good exercise overall, and felt like I’ve learned and enjoyed.

 

Get Facebook access_token

I’m going to try to document the experience of creating an access_token so my app. can post messages on my Facebook Page. As a summary, I have the following elements:

1) Facebook Page

This is the Doonish Facebook Page. It’s a page that describes the project and that try to get as many fans as possible.

2) Facebook Application

In the other side I’ve created an application for allowing the remote post to my page. This is application that will do that.

What I want to do is promote each day a new question from doonish into my Doonish Facebook Page.

 

How to automatically post in a Facebook Page?

1) Get application “access_token”

The first step is to get application “token_id” so we can post to the Facebook Page.

https://www.facebook.com/dialog/oauth?
    client_id={facebook-app-id}&
    redirect_uri={your-url}&
    scope=manage_pages&
    response_type=token

That will return with something like the following:

access_token={your-access-token}

2) Find the page “access_token”

Then, using the above token, you can go to the following location:

https://graph.facebook.com/me/accounts?
    access_token={your-access-token}

And you will see something like the following:

{
    "data": [
    {
        "name": "{your-page}",
        "access_token": "{page-token-id}",
        "category": "Website",
        "id": "{page-id}"
    },
    ...
    ]
}

3) Write the actual script

Whith the above “page-token-id” you can then write a PHP snippet that can do something like the following:

/**
 * Promote
 *
 * This method will automatically post a message on the facebook wall.
 *
 * @param integer $questionId The id of the question that we want to 
 *     promte.
 */
public function promote($questionId)
{
    $message = $this->generateMessage($questionId);
 
    $facebook = new Facebook(
        array(
            'appId'  => $this->facebookConfig['app_id'],
            'secret' => $this->facebookConfig['secret'],
            'scope'  => $this->facebookConfig['scope'],
            'cookie' => $this->facebookConfig['cookie'],
            'acceptUrl' => $this->facebookConfig['acceptUrl']
        )
    );
 
    $status = $facebook->api(
        '/' . $this->facebookConfig['page_id'] .'/feed',
        'post',
        array(
            'access_token' => $this->facebookConfig['token_id'],
            'message' => $message,
            'cb' => ','
        )
    );
}

Hope this code is useful for someone, it took me a while to figure out the right way to do it. I’ve used Facebook PHP SDK and I’ve got all the information from the Authentication page from Facebook Developers.

Some good and bad things from PHP

As a PHP developer I recognise that I’m not as opinated as I should be. When someone asks me “Why I’ve choose PHP” I just say that it’s because it was the first language I’ve deep into and I’ve keep developing myself into PHP (it’s what it allows me to develop more in less time). Once you know a language and you have enough knowledge is interesting to move into other languages so you can open your mind and get a better understanding of your preferred language (exactly like learning another spoken language). I hope I can learn any other language soon ;)

I’m going to summarize some pros and cons from PHP as a interesting excersise for myself:

Advantages:

  • Documentation: At the beginning is difficult to get use to (like any other documentation) but when you are into it, it’s pretty handy. My usual searches on google are “php array functions” or “php string functions”. A good point is allowing the comments from the users, some of them really interesting.
  • Easy to start: It’s easy to install WAMP (on Windows) or using php on cli with *NIX. There are lots of tutorials and all-known open source projects to look at the source code to learn more (WordPress, Drupal, etc.). Furthermore, you can got a cheap host easily.
  • Web optimized: Really easy to access to GET and POST variables and by default there is a direct map between the file and the URL. This kind of things make it easy to learn.
  • Right model: Requests are isolated from other requests and if it goes wrong, that is too isolated, which means that you can leak memory, have terrible bugs or infinite loops and you will not kill your server beause Apache is on top of that.
  • Scaling: Is relative common knowledge to scale PHP, you can search on Internet and you will find lots of tutorials, tips, etc.

Disadvantages:

  • Error handling: There is more than a single way to handling errors: trigger_error(), Exceptions and returning codes. Not having a unique and organized way make libraries mix all of this methods and sometimes makes it difficult to trap.
  • Too many falses: Not having a typed variables makes all this expressions evaluate as false: null, false, empty string, zero, the string containing ‘0’ and empty array.
  • Initialization: There is a lot of things that can be modified on the php.ini and it could change from server to server. Not a big pain but should be aware.
  • Returning arrays: If a function returns an array you have to assign it to a variable before accessing an element, you can’t just add an index after the function call.
  • No multiple inheritance: PHP doesn’t support multiple inheritance.
  • Evolving language: The fact that it’s evolving and having new features in each release has other constraints: “register_globals” (“script.php?auth=1″ sets $auth as TRUE by default), “magic_quotes” (that’s not for security and people is relying on that) and “PHP4’s object reference model” (where references didn’t point to the object, they were pointing to the variable).
  • Others: Lack of case sensitivity (“$variable” is the same than “$VaRiaBLe”), needle and haystack vs haystack and needle in different array methods, having to use “array()” instead of just “[]”.

Profiling your database in Zend Framework

Just a quick tip for all Zend Framework developers.

Imagine I’m getting an error from a select that I’ve created:

$questionRow = $this-&gt;fetchRow($select);

If you want to see which query is being executed on your database, you can go with something like that:

$db = Zend_Db_Table::getDefaultAdapter();
$profiler = $db-&gt;getProfiler()-&gt;setEnabled(true);
 
// like before
$questionRow = $this-&gt;fetchRow($select);
 
$query = $profiler-&gt;getLastQueryProfile();
var_dump($query);
die;

That will print the SQL query that has just been executed.

Configurar l’idioma Català a Linux

Estic fent algunes probes per a mostrar les dates a PHP en Català. Al meu servidor local tot funcionava correctament, pero al passar-ho al servidor remot ha deixat de funcionar.

El codi font es el següent (en PHP):

setlocale(LC_ALL, $lang . "_ES.UTF-8");
echo strftime("%A %e de %B del %Y a " . $translate-&gt;_("las") . " %H:%M", strtotime($time));

En castellà funcionaba correctament, pero al passar-ho al català no funciona.

Per a que funcioni, he hagut de fer la següent modificació: Obrir el fitxer /var/lib/locales/supported.d/local i afegir la darrera línea.

es_ES.UTF-8 UTF-8
ca_ES.UTF-8 UTF-8

Despres de desar el fitxer, he executat la següent comanda:

sudo dpkg-reconfigure locales

I ja ha funcionat, ja puc veure la data tant en català com en castellà :) !