El desarrollo Web está cambiando. HTML5, CSS3 y JavaScript han avanzado tanto que surgen las Single-Page Applications, aplicaciones web cuya visualización y navegación está completamente controlada por dichos lenguajes cliente, dejando al servidor como mero facilitador de datos. Hasta ahora siempre hemos concebido lenguajes distintos para cliente y servidor hasta que a un innovador ingeniero se le ocurrió desarrollar una API de servicios JavaScript en el servidor, surge Node.js. Ahora tenemos JavaScript en el cliente y JavaScript en el servidor pero ¿qué pasa con toda nuestra infraestructura Java? ¿Cómo podemos reutilizar todas las funcionalidades de Java EE como EJB, JMS o JPA y también nuestras propias librerías? La respuesta está en el Proyecto Avatar.
Más información en https://avatar.java.net/
This is a Title Slide with Picture slide ideal for including a picture with a brief title, subtitle and presenter information.
To customize this slide with your own picture:
Right-click the slide area and choose Format Background from the pop-up menu. From the Fill menu, click Picture and texture fill. Under Insert from: click File. Locate your new picture and click Insert.
¿Que qué es el proyecto Avatar?
Antes de contaros ningún detalle quiero que os quedéis con una de estas 2 definiciones para cuando mañana os pregunten que os contaron ayer en UltimateJava sobre eso del Proyecto Avatar podáis contestarles en función de si os lo preguntan subiendo al ascensor o subiendo por las escaleras:
Ascensor: El proyecto Avatar es una nueva manera, muy rápida y sencilla, de crear aplicacoines web ágiles
Escaleras: Un framework para desarrollar vistas y servicois utilizando lenguajes estándar, end to end, aprovechando tecnologías como Node.js y Nashorn (JDK8), de las que a continuación os hablaré, y REST, WebSockets y SSE, de las que os acaba de hablar Joan Carles.
Pero si os preguntan sobre qué es el proyecto Avatar durante el desayuno o el almuerzo, vais a necesitar una definición un poco más larga y, para empezar, comprender unos conceptos básicos con los que algunos de los que estáis aquí es probable que ya estéis familiarizados. Tras 10 minutos ya estaremos listos para hablar de la arquitectura y las características del proyecto Avatar y finalmente, porque una demostración vale más que mil lecciones, veremos un ejemplo práctico.
Empezamos!
Esta es la arquitectura de aplicación web a la que todos los aquí presentes estamos más que acostumbrados.
Tenemos una serie de tecnologías exclusivas del servidor con su correspondiente lenguaje, Java, por si había alguna duda ;), y otras propias del cliente, lo cual siempre ha sido un engorro ya que normalmente se requiere estar especializado en front-end o back-end. No le pidas a un programador de back-end que te haga la web promocional de una película, con más efectos especiales que la película en si, y ni se te ocurra pedirle al gurú de CSS y JavaScript que te cree los servicios que dicha web promocional. ¿No podríamos unir un poco más ambos mundos?
Hablando de gurús del front-end, están ayudando a que las tecnologías de cliente están avanzando a pasos agigantados como se puede ver en la página de Facebook, que responden a la moda de las “Single-page applications”: aplicacoines web donde tanto visualización como “navegación” se controlan totalmente mediante JavaScript, HTML y CSS.
Esto ha aumentado drásticamente la relevancia de los motores de JavaScript. A mayor potencia, mayor fluidez de la página. Entre los motores JavaScript actuales, destaca el Chrome V8, el que utiliza el navegador homónimo.
Tenemos el auge de JavaScript por un lado pero seguimos necesitando otros lenguajes en el otro. ¿Podemos saltar esta brecha, unificando el lenguaje de desarrollo de una aplicación web, desde el front hasta el back-end?
La respuesta es Node.js.
Un ingeniero llamado Ryan Dahl se le ocurrió coger las librerías del Chrome V8 y construir en C++ una capa de servicios JavaScript que nos permite ejecutar código JavaScript fuera de su habitat natural, los navegadores, para ejecutarlo directamente en del lado del servidor.
Node.js se ha hecho muy popular ya que todas las tecnologías de back-end, .Net, Java, PHP… siempre han tenido en común el front-end, el JavaScript, y ahora es este JavaScript quien viene a ponerse entre dichas tecnologías, por lo tanto, la comunidad de desarrolladores es muy numerosa y aportan distintas ideas en función de la plataforma de la que vienen y hoy por hoy ya se han desarrollado más de 75.000 módulos.
El modelo de programación que plantea Node se basa en 2 preceptos:
1.- La concurrencia es complicada y no debería exponer al programador, como ocurre en Java, por ejemplo. Java no obstante tiene numerosas APIs asíncroncas para evitar problemas de concurrencia
2.- Las llamadas a dispositivos bloqueantes es mala, ya que ralentiza el rendimiento final de la aplicación. Programando en Node.js, en lugar de esperar a una petición del cliente y procesarla, registramos nuestro interés por un evento de manera que cuando ocurra dicho evento (una petición HTTP
The Node programming model is very different from the Java EE programming model. Java EE is based on a multi-threaded runtime, where concurrency is often exposed to the developer.
Node, on the other hand, takes the approach that developing multi-threaded applications is hard. There are potentially thousands of concurrent connections and dealing with synchronized blocks of code, deadlocks, race conditions, etc, is hard. In addition, many application platforms block on I/O. Blocking I/O blocks a thread from running, and therefore wastes system resources. By the way, historically this was true even with Java EE, but more recent versions of Java EE have added asynchronous APIs and Non-blocking I/O to address this.
Node takes a very different approach as a web application platform. Node on the Chrome v8 JavaScript engine executes user code in a single thread with a development model that is similar to writing browser apps. In Node’s reactive model, developers register interest with events (callbacks/promises) as the occur in the system. Events are added to the event queue and processed by the event queue. If you have ever written User Interface code (onClick for example), this approach is very similar. The difference is that the event loop can handle many events in parallel because I/O calls to slower resources (network & filesystem for example) are non-blocking, executing in their own threads that do not execute the developer’s code.
What we have here is an example of a simple HTTP server written in JavaScript. Instead of waiting for a request and then processing it, we register a function (in the dark grey box) that is called each time a client makes an HTTP request. Each client request is added to the event queue to be processed.
Nashorn is a new EcmaScript 5.1 compliant JavaScript engine for the JVM. Nashorn ships with JDK 8 and replaces the older Rhino engine. Nashorn utlizes the InvokeDynamic bytecode introduced in JDK 7 for improved performance. Say something here about security.
What really differentiates Rhino from the Chrome v8 engine is the fact that you can seamlessly invoke Java code from within JavaScript code. <CLICK> As you can see from this snippet of code, we can easily create a javafx client-side application by invoking Java APIs from JavaScript. In this case, we create a Button object, assign the button text, and invoke a callback when the button is pushed.
Nashorn is a new EcmaScript 5.1 compliant JavaScript engine for the JVM. Nashorn ships with JDK 8 and replaces the older Rhino engine. Nashorn utlizes the InvokeDynamic bytecode introduced in JDK 7 for improved performance. Say something here about security.
What really differentiates Rhino from the Chrome v8 engine is the fact that you can seamlessly invoke Java code from within JavaScript code. <CLICK> As you can see from this snippet of code, we can easily create a javafx client-side application by invoking Java APIs from JavaScript. In this case, we create a Button object, assign the button text, and invoke a callback when the button is pushed.
Scaling a node application typically requires adding node processes that run the same application. From a Java perspective, we can accomplish this by replicating the application across new threads within the same JVM. Each thread is essentially a new node event loop, maintaining the single-threaded node programming model. In addition, HTTP requests are automatically load balanced across the threads by the Avatar framework. This offers in-process scaling with no management overhead.
Because we have multiple instances of the same application in the same JVM, they may want to share state.
¡¡Hay que tener cuidado al compartir estado a través de objetos Java!!
This is a Announcement slide ideal for including a picture and partner or product logo with a brief title and subtitle or description.
To Replace the Picture on this sample slide (this applies to all slides in this template that contain replaceable pictures)
Select the sample picture and press Delete. Click the icon inside the shape to open the Insert Picture dialog box. Navigate to the location where the picture is stored, select desired picture and click on the Insert button to fit the image proportionally within the shape.
Note: Do not right-click the image to change the picture inside the picture placeholder. This will change the frame size of the picture placeholder. Instead, follow the steps outlined above.
To Replace the LOGO on this sample slide:
Right-click the sample LOGO and choose Change Picture. Navigate to the location where the new logo is stored, select desired logo file and click on the Open button to replace the sample logo.
El primer argumento de registerRestService es la URL del servicio mientras que el segundo es la implementación del mismo