• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
El proyecto Avatar_ Carlos Martín Martínez
 

El proyecto Avatar_ Carlos Martín Martínez

on

  • 165 views

 

Statistics

Views

Total Views
165
Views on SlideShare
164
Embed Views
1

Actions

Likes
0
Downloads
10
Comments
0

1 Embed 1

https://twitter.com 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • This is a Title Slide with Picture slide ideal for including a picture with a brief title, subtitle and presenter information. <br /> <br /> To customize this slide with your own picture: <br /> <br /> 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.
  • This is a sample Two Pictures with Captions Layout slide ideal for including two pictures with brief descriptive statements. <br /> <br /> To Replace the Pictures on this Sample Slide (this applies to all slides in this template that contain replaceable pictures) <br /> <br /> 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. <br /> <br /> 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. <br /> <br />
  • 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. <br /> <br /> 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. <br /> <br /> 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. <br /> <br /> 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. <br />
  • 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. <br /> <br /> What really differentiates Rhino from the Chrome v8 engine is the fact that you can seamlessly invoke Java code from within JavaScript code. 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. <br /> <br /> What really differentiates Rhino from the Chrome v8 engine is the fact that you can seamlessly invoke Java code from within JavaScript code. 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. <br /> <br /> Because we have multiple instances of the same application in the same JVM, they may want to share state. <br /> <br /> <br /> ¡¡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. <br /> <br /> To Replace the Picture on this sample slide (this applies to all slides in this template that contain replaceable pictures) <br /> <br /> 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. <br /> <br /> 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. <br /> <br /> To Replace the LOGO on this sample slide: <br /> <br /> 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. <br />
  • El primer argumento de registerRestService es la URL del servicio mientras que el segundo es la implementación del mismo
  • Ejemplo aplicacion Avatar> <br /> <br />

El proyecto Avatar_ Carlos Martín Martínez El proyecto Avatar_ Carlos Martín Martínez Presentation Transcript

  • Copyright © 2014 Oracle and/or its affiliates. All rights reserved. | Proyecto Avatar JavaScript en la JVM del Servidor Carlos Martín Martínez Technology Sales Consultant Fusion Middleware 12 de Junio, 2014
  • Copyright © 2014 Oracle and/or its affiliates. All rights reserved. | ¿Qué es el proyecto Avatar? Un manera muy rápida y sencilla de crear aplicaciones web ágiles Un framework para desarrollar vistas y servicios utilizando lenguajes estándar como JavaScript, HTML5 y CSS3, aprovechando tecnologías como Node.js, Nashorn (JDK8), REST, WebSockets y SSE 2
  • Copyright © 2014 Oracle and/or its affiliates. All rights reserved. | Agenda Conceptos básicos (10 minutos) Arquitectura y Características (10 minutos) Ejemplo práctico (10 minutos) 1 2 3 Oracle Confidential – Internal/Restricted/Highly Restricted 3
  • Copyright © 2014 Oracle and/or its affiliates. All rights reserved. | Agenda Conceptos básicos (10 minutos) Arquitectura y Características (10 minutos) Ejemplo práctico (10 minutos) 1 2 3 Oracle Confidential – Internal/Restricted/Highly Restricted 4
  • Copyright © 2014 Oracle and/or its affiliates. All rights reserved. | Conceptos básicos 5 Arquitectura aplicación Web Moderna Presentation (Servlet/JSP, JSF) Connectivity (WebSocket, REST,SSE) EnterpriseConnectivity andBusinessLogic Java EE / JVM View Controller JavaScript Browser ClientServer • Auge de “Single-page applications” • Vista y controlador en el navegador • Únicamente el modelo permanece en el servidor
  • Copyright © 2014 Oracle and/or its affiliates. All rights reserved. | Conceptos básicos • JavaScript en el servidor • Basado en motor Chrome v8 • Diseñado para aplicaciones web escalables • Crisol de culturas: Java, .Net, PHP • Más de 75.000 módulos • Preceptos de Node.js – La concurrencia es complicada  Código de desarrollador se ejecuta en un único hilo – Bloquear en E/S es malo  Bucle de eventos 6 Node.js HTTP Callback Example:
  • Copyright © 2014 Oracle and/or its affiliates. All rights reserved. | Conceptos básicos • Motor JavaScript sobre JVM • Cumple con ECMAScript 5.1 • Incluido en JDK8 • Interoperabilidad Java  JavaScript 7 Nashorn
  • Copyright © 2014 Oracle and/or its affiliates. All rights reserved. | Conceptos básicos • Node en la JVM 8 Avatar.js = +  Modelo programación Node – Código en JavaScript – Único bucle de eventos / hilo – Importa módulos Node  Invoca código Java – Tipos y librerías Java – new java.lang.Thread(); – new com.mydom.MyObj()Java JavaScript java.lang.Thread java.util.SortedSet java.math.BigInteger Node App Proceso JVM com.mydom.MyObj require (‘async’)
  • Copyright © 2014 Oracle and/or its affiliates. All rights reserved. | Ventajas Avatar.js • Reutilización de librerías y middleware Java existentes • Puede aprovechar múltiples cores • Securización de aplicaciones con el modelo de seguridad de Java • Gestión de la aplicación con herramientas Java existentes • – VisualVM, MBeans, Flight Recorder, Mission Control • Acceso a las APIs de Java para complementar las APIs de Node • – BigInteger, Date, Calendar, XML, SQL, Multicast, etc • Suficientemente pequeño para uso embebido (menos de 2 MB) 9
  • Copyright © 2014 Oracle and/or its affiliates. All rights reserved. | • Aprovechando la potencia de Chrome V8, se desarrolla Node.js para, básicamente, ejecutar código JavaScript fuera de navegadores, es decir, en servidores • Diseñado para aplicaciones con poco tiempo de proceso y mucho de E/S • Programación mono-hilo ¡STOP! 10 Repaso de conceptosView Controller JavaScript Browser • Auge de “Single-page applications” • Vista y controlador en el navegador • Únicamente el modelo permanece en el servidor • Código JavaScript cada vez mayor • Necesidad de interpretes (motores) rápidos • Surge Chrome V8, más rápido que JScript (en Internet Explorer), SpiderMonkey (en Firefox) y JavaScriptCore (en Safari) • Donde Chrome V8 ofrece potencia, Nashorn ofrece integración completa de JavaScript con JVM y, por tanto con décadas de desarrollo de librerías y módulos totalmente probados • ¿Cómo introducir los conceptos y módulos innovadores del mundo Node en el probado mundo JEE, con su enorme ecosistema de librerías? Avatar.js¿VS?
  • Copyright © 2014 Oracle and/or its affiliates. All rights reserved. | Agenda Conceptos básicos (10 minutos) Arquitectura y Características (10 minutos) Ejemplo práctico (10 minutos) 1 2 3 11
  • Copyright © 2014 Oracle and/or its affiliates. All rights reserved. | Arquitectura 12
  • Copyright © 2014 Oracle and/or its affiliates. All rights reserved. | • service – Contiene los servicios Avatar (JavaScript) – Rest, WebSocket o SSE – Aprovechan módulos Node, 3rd Party o librerías Java • view – Contiene los HTML, CSS y JS necesarios para mostrar la aplicación • WEB-INF – Únicamente para que la aplicación sea reconocida por el contenedor de Servlets • avatar.properties – debug=true – service.threads=1 ; cores / 2 13 Estructura aplicación Avatar
  • Copyright © 2014 Oracle and/or its affiliates. All rights reserved. | Servicios Avatar 14 Balanceo de carga, estado compartido y almacenamiento de datos Java JVM Process HTTP Load Balancer JavaScript Services Services ServicesServices shared state Database Data Notification JSON JSON JSON JSON
  • Copyright © 2014 Oracle and/or its affiliates. All rights reserved. | Avatar EE 15 JPA, EJB, JMS
  • Copyright © 2014 Oracle and/or its affiliates. All rights reserved. | Agenda Conceptos básicos (10 minutos) Arquitectura y Características (10 minutos) Ejemplo práctico (10 minutos) 1 2 3 16
  • Copyright © 2014 Oracle and/or its affiliates. All rights reserved. | Ejemplo práctico Aplicación Reloj 17
  • Copyright © 2014 Oracle and/or its affiliates. All rights reserved. | Ejemplo práctico: Reloj • Fichero clock/service/src/main.js • Primer paso, referenciar “avatar” – var avatar = require("org/glassfish/avatar"); • Registramos servicio REST en la URL data/message que establece el valor de message al valor de msg de la petición PUT – avatar.registerRestService({ url: "data/message" }, function() { this.onPut = function(request, response) { message = request.data.msg; response.send(null); }; } ); 18 Servicios (REST)
  • Copyright © 2014 Oracle and/or its affiliates. All rights reserved. | Ejemplo práctico: Reloj • Registramos un servicio PUSH en la url push/time que, al iniciar la conexión PUSH (onOpen), establece un valor de timeout de 1000ms y sobreescribe la función onTimeout para devolver el resultado de la función getTime • avatar.registerPushService({ url: "push/time" }, function() { this.onOpen = this.onTimeout = function(context) { context.setTimeout(1000); return context.sendMessage(getTime()); }; } ); • Función getTime – var getTime = function() { var current = new Date(); return { msg: 'The server time is ', h: current.getHours(), m: current.getMinutes(), s: current.getSeconds() }; }; 19 Servicios (PUSH/SSE)
  • Copyright © 2014 Oracle and/or its affiliates. All rights reserved. | Ejemplo práctico: Reloj • Definición de modelos de datos: – Defino el modelo de datos Message vinculado a un servicio REST con el atributo msg • <script data-model="rest"> var Message = function() { this.msg = ''; }; </script> – Defino el modelo de datos Time vinculado a un servicio PUSH con atributos msg, h, m y s • <script data-model="push"> var Time = function() { this.msg = this.h = this.m = this.s = ''; }; </script> • Instanciación de los modelos mediante llamada al servicio correspondiente – <script data-type="Message" data-instance="message" data- url="data/message"></script> – <script data-type="Time" data-instance="time" data-url="push/time"></script> 20 Vista
  • Copyright © 2014 Oracle and/or its affiliates. All rights reserved. | Ejemplo práctico: Reloj • Vinculamos mediante EL output HTML con los valores del modelo de datos time – <output class="time">#{time.msg}#{time.h}:#{time.m}:#{time.s}</output><br><br> • Vinculamos mediante EL el input HTML con el valor del modelo message – <label for="im">New Message: </label> – <input id="im" size="35" data-value="#{message.msg}"/> • Vinculamos mediante EL la función onclick del button HTML con el método PUT (actualización) del servicio REST vinculado al modelo message – <button onclick="#{message.put()}">Update</button> • El uso de EL (Expression Language) evita la necesidad de crear lógica de control en JavaScript para hacer la página dinámica 21 Vista
  • Copyright © 2014 Oracle and/or its affiliates. All rights reserved. | Repaso • Framework de desarrollo de aplicaciones web ágiles – Vistas: HTML5, CSS3 y JavaScript – Servicios REST, WS y SSE: Avatar.js (implementación de Node sobre Nashorn). • Ejecución código Java • Aprovecha la infraestructura Java EE • Optimización multi-hilo – Balanceo de carga entre hilos – Estado compartido entre hilos 22 Conceptos Proyecto Avatar
  • Copyright © 2014 Oracle and/or its affiliates. All rights reserved. | 23