SlideShare a Scribd company logo
Nashorn: novo motor
Javascript no Java 8
Bruno Borges
Principal Product Manager
Java Evangelist
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.3
• Java Evangelist
• Orale Product Manager
• Entusiasta JavaFX e IoT
• Onde me encontrar
• @brunoborges
• plus.google.com/+BrunoBorges
Bruno Borges
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.4
Agenda
• Nashorn Overview
• Nashorn e Java
• Nashorn usando o comando jjs
• Shell Scripting com Nashorn
• Nashorn e JavaFX
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.5
Nashorn Overview
• Runtime Java baseado na linguagem Javascript
• ECMAScript 262 v5.1
• Familar para desenvolvedores de conteúdo
• Permite uso de uma série de bibliotecas e ferramentas escritas em
Javascript
• Node.JS
• Obtém todas as vantagens das tecnologias Java
Scripting for Java
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.6
Nashorn Overview
• Forte integração com a plataforma Java
• Extensões foram adicionadas para prover acesso ao Java
• Nashorn pode ser usado no Java usando a ScriptEngine API
• Nashorn pode também ser usado pela linha de comando jjs
• Suporte para shell scripting
• Suporte completo ao JavaFX
• NetBeans 8 suporta desenvolvimento com Nashorn
Funcionalidades
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.7
NASHORN E JAVA
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.8
Nashorn e Java
import javax.script.*;
public class Main {
public static void main(String[] args) {
final ScriptEngineManager manager = new ScriptEngineManager();
final ScriptEngine engine = manager.getEngineByName("nashorn");
try {
engine.eval("print('hello world');");
} catch (final ScriptException se) {
System.err.println(se);
}
}
}
Exemplo 1
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.9
Nashorn e Java
String script = "var x = 10;n" +
"var y = 20;n" +
"var z = x + y;n" +
"z;n";
Object result = engine.eval(script);
int value = (Integer)result;
System.out.println(value);
Exemplo 2
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.10
Nashorn e Java
engine.put("x", 100);
engine.put("y", 200);
engine.eval("var z = x + y;");
int value = (Integer)engine.get("z");
System.out.println(value);
Exemplo 3
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.11
Nashorn e Java
var HashMap = java.util.HashMap;
var map = new HashMap();
map.put("apple", "red");
map.put("bear", "brown");
map.put("canary", "yellow");
print("A bear is " + map.get("bear"));
for (var key in map) print("key: " + key);
for each (var value in map) print("value: " + value);
Exemplo 4
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.12
NASHORN
USANDO JJS
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.13
Nashorn usando jjs
• Nashorn pode ser chamado usando a ferramenta jjs por linha de
comando
• Facilita o uso de Javascript no dia-a-dia
• Tarefas rápidas
• Prototipação
• Experimento com novas features do Java
• Shell scripts
A partir da linha de comando
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.14
Nashorn usando jjs
>> where jjs
/usr/bin/jjs
>> jjs
jjs> var x = 10;
jjs> var y = 20;
jjs> print(x + y);
30
jjs> quit();
>>
Exemplo 5
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.15
Nashorn usando jjs
Exemplo 6
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.16
SHELL SCRIPTING
COM NASHORN
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.17
Shell Scripting com Nashorn
• Por que não utilizar uma linguagem que você já está familiarizado?
• Acesso a um vasto número de bibliotecas Java
• Extensões de scripting para simplificar
• Documentos
• Templates de Strings
• Execução de comandos
• Variáveis de ambiente
Substituto mais simples para outras linguagens shell
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.18
Schell Scripting usando Nashorn
#!/usr/bin/jjs -doe -scripting
#
var dir = __DIR__ + "photos";
var files = `ls ${dir}`.trim().split("n");
var count = 1;
for each (var file in files) {
if (file.edsWith(".jpg")) {
`mv ${dir}/${file} ${dir}/Photo${count++}.jpg`;
}
}
Exemplo 7
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.19
NASHORN E
JAVAFX
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.20
Nashorn e JavaFX
• Método bem natural de trabalhar com JavaFX
• Nashorn pode ser invocado a partir de FXML
• FXML é uma opção, em formato XML, para definir interfaces em JavaFX
• Modelo familiar para desenvolvedores de conteúdo
Nashorn foi feito para o JavaFX
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.21
Nashorn e JavaFX
load("fx:base.js");
load("fx:controls.js");
load("fx:graphics.js");
$STAGE.title = "Hello World!";
var button = new Button();
button.text = "Say 'Hello World'";
button.onAction = function() print("Hello World!");
var root = new StackPane();
root.children.add(button);
$STAGE.scene = new Scene(root, 300, 250);
$STAGE.show();
Exemplo 8
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.22
Recapitulando
• Forte integração com Java
• Pode ser usado a partir do Java
• Nova ferramenta por linha de comando jjs
• Supore a Shell Scripting
• Suporte completo ao JavaFX
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.23
Para saber mais
• Download: java.oracle.com
• Documentação: docs.oracle.com/javase
• Treinamentos: education.oracle.com/java
• Central do Java 8: www.oracle.com/java8
• Nashorn para Usuários
• wiki.openjdk.java.net/display/Nashorn/Nashorn+Documentation
• Exemplos: blogs.oracle.com/nashorn/
• Dúvidas: nashorn-dev@openjdk.java.net
Java 8 e outros sites
youtube.com/java
blogs.oracle.comjava
facebook.com/ilovejava
@java
@javaembedded
nighthacking.com
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.25
The preceding is intended to outline our general product direction. It is intended
for information purposes only, and may not be incorporated into any contract.
It is not a commitment to deliver any material, code, or functionality, and should
not be relied upon in making purchasing decisions. The development, release,
and timing of any features or functionality described for Oracle’s products
remains at the sole discretion of Oracle.
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.26
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.27

More Related Content

PDF
Nashorn: Novo Motor Javascript no Java SE 8
PPTX
ColdFusion 10 CFScript Enhancements
PDF
rsyslog v8: more than just syslog!
PDF
Gazelle - Plack Handler for performance freaks #yokohamapm
PPTX
Good practices for PrestaShop code security and optimization
PDF
Scala Frustrations
PDF
[131]해커의 관점에서 바라보기
KEY
About Data::ObjectDriver
Nashorn: Novo Motor Javascript no Java SE 8
ColdFusion 10 CFScript Enhancements
rsyslog v8: more than just syslog!
Gazelle - Plack Handler for performance freaks #yokohamapm
Good practices for PrestaShop code security and optimization
Scala Frustrations
[131]해커의 관점에서 바라보기
About Data::ObjectDriver

What's hot (19)

PDF
PL/Perl - New Features in PostgreSQL 9.0
PDF
Introductory Overview to Managing AWS with Terraform
PDF
The cost of learning - advantage of mixer2
PDF
Assetic (Zendcon)
KEY
Python在豆瓣的应用
PPTX
Bioinformatics p5-bioperl v2013-wim_vancriekinge
PPTX
Bioinformatica p6-bioperl
PDF
Test driven programming beginner quick start
PDF
Everything as Code with Terraform
KEY
Intro To jQuery In Drupal
PDF
All about Erubis (English)
PDF
AWSをテラフォーミングする会(Terraformハンズオン)
PDF
Assetic (OSCON)
KEY
Picconf12
KEY
JavaScript in Drupal 7: What developers need to know
PPT
Introduction To Moco
PDF
Hacking Mac OSX Cocoa API from Perl
PDF
Puppet Module Reusability - What I Learned from Shipping to the Forge
PDF
Py conkr 20150829_docker-python
PL/Perl - New Features in PostgreSQL 9.0
Introductory Overview to Managing AWS with Terraform
The cost of learning - advantage of mixer2
Assetic (Zendcon)
Python在豆瓣的应用
Bioinformatics p5-bioperl v2013-wim_vancriekinge
Bioinformatica p6-bioperl
Test driven programming beginner quick start
Everything as Code with Terraform
Intro To jQuery In Drupal
All about Erubis (English)
AWSをテラフォーミングする会(Terraformハンズオン)
Assetic (OSCON)
Picconf12
JavaScript in Drupal 7: What developers need to know
Introduction To Moco
Hacking Mac OSX Cocoa API from Perl
Puppet Module Reusability - What I Learned from Shipping to the Forge
Py conkr 20150829_docker-python
Ad

Similar to Nashorn: nova engine Javascript do Java SE 8 (20)

PPT
Nashorn
PDF
Nashorn - JavaScript on the JVM - Akhil Arora
PDF
Nashorn: JavaScript Running on Java VM (English)
PDF
Nashorn in the future (English)
PPTX
JCConf2019: Next Step of JavaScript on Java
PPTX
Nashorn
PPTX
Nashorn
PDF
Jax keynote
PDF
Server-Side JavaScript with Nashorn
PDF
Nashorn in the future (English)
PDF
Java 8: Nashorn & avatar.js di Enrico Risa al JUG Roma
PPTX
Nashorn: JavaScript that doesn't suck - Tomer Gabel, Wix
PPTX
Nashorn: JavaScript that doesn’t suck (ILJUG)
PDF
Java 8 new features
PDF
Java 8 new features
PDF
JavaOne 2013: «Java and JavaScript - Shaken, Not Stirred»
PPTX
Nashorn, what is the whole buzz about
PPTX
Nashorn, what is the whole buzz about #4developers
PPTX
4Developers 2015: Nashorn - o co ten cały szum - Michał Gruca
PPTX
Java 9 new features
Nashorn
Nashorn - JavaScript on the JVM - Akhil Arora
Nashorn: JavaScript Running on Java VM (English)
Nashorn in the future (English)
JCConf2019: Next Step of JavaScript on Java
Nashorn
Nashorn
Jax keynote
Server-Side JavaScript with Nashorn
Nashorn in the future (English)
Java 8: Nashorn & avatar.js di Enrico Risa al JUG Roma
Nashorn: JavaScript that doesn't suck - Tomer Gabel, Wix
Nashorn: JavaScript that doesn’t suck (ILJUG)
Java 8 new features
Java 8 new features
JavaOne 2013: «Java and JavaScript - Shaken, Not Stirred»
Nashorn, what is the whole buzz about
Nashorn, what is the whole buzz about #4developers
4Developers 2015: Nashorn - o co ten cały szum - Michał Gruca
Java 9 new features
Ad

More from Bruno Borges (20)

PDF
Secrets of Performance Tuning Java on Kubernetes
PDF
[Outdated] Secrets of Performance Tuning Java on Kubernetes
PDF
From GitHub Source to GitHub Release: Free CICD Pipelines For JavaFX Apps
PDF
Making Sense of Serverless Computing
PPTX
Visual Studio Code for Java and Spring Developers
PDF
Taking Spring Apps for a Spin on Microsoft Azure Cloud
PDF
A Look Back at Enterprise Integration Patterns and Their Use into Today's Ser...
PPTX
Melhore o Desenvolvimento do Time com DevOps na Nuvem
PPTX
Tecnologias Oracle em Docker Containers On-premise e na Nuvem
PPTX
Java EE Arquillian Testing with Docker & The Cloud
PPTX
Migrating From Applets to Java Desktop Apps in JavaFX
PDF
Servidores de Aplicação: Por quê ainda precisamos deles?
PDF
Build and Monitor Cloud PaaS with JVM’s Nashorn JavaScripts [CON1859]
PDF
Cloud Services for Developers: What’s Inside Oracle Cloud for You? [CON1861]
PDF
Booting Up Spring Apps on Lightweight Cloud Services [CON10258]
PDF
Java EE Application Servers: Containerized or Multitenant? Both! [CON7506]
PDF
Running Oracle WebLogic on Docker Containers [BOF7537]
PPTX
Lightweight Java in the Cloud
PDF
Tweet for Beer - Beertap Powered by Java Goes IoT, Cloud, and JavaFX
PDF
Integrando Oracle BPM com Java EE e WebSockets
Secrets of Performance Tuning Java on Kubernetes
[Outdated] Secrets of Performance Tuning Java on Kubernetes
From GitHub Source to GitHub Release: Free CICD Pipelines For JavaFX Apps
Making Sense of Serverless Computing
Visual Studio Code for Java and Spring Developers
Taking Spring Apps for a Spin on Microsoft Azure Cloud
A Look Back at Enterprise Integration Patterns and Their Use into Today's Ser...
Melhore o Desenvolvimento do Time com DevOps na Nuvem
Tecnologias Oracle em Docker Containers On-premise e na Nuvem
Java EE Arquillian Testing with Docker & The Cloud
Migrating From Applets to Java Desktop Apps in JavaFX
Servidores de Aplicação: Por quê ainda precisamos deles?
Build and Monitor Cloud PaaS with JVM’s Nashorn JavaScripts [CON1859]
Cloud Services for Developers: What’s Inside Oracle Cloud for You? [CON1861]
Booting Up Spring Apps on Lightweight Cloud Services [CON10258]
Java EE Application Servers: Containerized or Multitenant? Both! [CON7506]
Running Oracle WebLogic on Docker Containers [BOF7537]
Lightweight Java in the Cloud
Tweet for Beer - Beertap Powered by Java Goes IoT, Cloud, and JavaFX
Integrando Oracle BPM com Java EE e WebSockets

Recently uploaded (20)

PDF
Encapsulation theory and applications.pdf
PDF
Machine learning based COVID-19 study performance prediction
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
A comparative analysis of optical character recognition models for extracting...
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
Big Data Technologies - Introduction.pptx
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Electronic commerce courselecture one. Pdf
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Chapter 3 Spatial Domain Image Processing.pdf
Encapsulation theory and applications.pdf
Machine learning based COVID-19 study performance prediction
Advanced methodologies resolving dimensionality complications for autism neur...
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
A comparative analysis of optical character recognition models for extracting...
sap open course for s4hana steps from ECC to s4
Dropbox Q2 2025 Financial Results & Investor Presentation
MIND Revenue Release Quarter 2 2025 Press Release
Mobile App Security Testing_ A Comprehensive Guide.pdf
MYSQL Presentation for SQL database connectivity
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Big Data Technologies - Introduction.pptx
“AI and Expert System Decision Support & Business Intelligence Systems”
Network Security Unit 5.pdf for BCA BBA.
NewMind AI Weekly Chronicles - August'25-Week II
Electronic commerce courselecture one. Pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Spectral efficient network and resource selection model in 5G networks
Chapter 3 Spatial Domain Image Processing.pdf

Nashorn: nova engine Javascript do Java SE 8

  • 1. Nashorn: novo motor Javascript no Java 8 Bruno Borges Principal Product Manager Java Evangelist
  • 2. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.3 • Java Evangelist • Orale Product Manager • Entusiasta JavaFX e IoT • Onde me encontrar • @brunoborges • plus.google.com/+BrunoBorges Bruno Borges
  • 3. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.4 Agenda • Nashorn Overview • Nashorn e Java • Nashorn usando o comando jjs • Shell Scripting com Nashorn • Nashorn e JavaFX
  • 4. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.5 Nashorn Overview • Runtime Java baseado na linguagem Javascript • ECMAScript 262 v5.1 • Familar para desenvolvedores de conteúdo • Permite uso de uma série de bibliotecas e ferramentas escritas em Javascript • Node.JS • Obtém todas as vantagens das tecnologias Java Scripting for Java
  • 5. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.6 Nashorn Overview • Forte integração com a plataforma Java • Extensões foram adicionadas para prover acesso ao Java • Nashorn pode ser usado no Java usando a ScriptEngine API • Nashorn pode também ser usado pela linha de comando jjs • Suporte para shell scripting • Suporte completo ao JavaFX • NetBeans 8 suporta desenvolvimento com Nashorn Funcionalidades
  • 6. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.7 NASHORN E JAVA
  • 7. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.8 Nashorn e Java import javax.script.*; public class Main { public static void main(String[] args) { final ScriptEngineManager manager = new ScriptEngineManager(); final ScriptEngine engine = manager.getEngineByName("nashorn"); try { engine.eval("print('hello world');"); } catch (final ScriptException se) { System.err.println(se); } } } Exemplo 1
  • 8. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.9 Nashorn e Java String script = "var x = 10;n" + "var y = 20;n" + "var z = x + y;n" + "z;n"; Object result = engine.eval(script); int value = (Integer)result; System.out.println(value); Exemplo 2
  • 9. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.10 Nashorn e Java engine.put("x", 100); engine.put("y", 200); engine.eval("var z = x + y;"); int value = (Integer)engine.get("z"); System.out.println(value); Exemplo 3
  • 10. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.11 Nashorn e Java var HashMap = java.util.HashMap; var map = new HashMap(); map.put("apple", "red"); map.put("bear", "brown"); map.put("canary", "yellow"); print("A bear is " + map.get("bear")); for (var key in map) print("key: " + key); for each (var value in map) print("value: " + value); Exemplo 4
  • 11. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.12 NASHORN USANDO JJS
  • 12. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.13 Nashorn usando jjs • Nashorn pode ser chamado usando a ferramenta jjs por linha de comando • Facilita o uso de Javascript no dia-a-dia • Tarefas rápidas • Prototipação • Experimento com novas features do Java • Shell scripts A partir da linha de comando
  • 13. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.14 Nashorn usando jjs >> where jjs /usr/bin/jjs >> jjs jjs> var x = 10; jjs> var y = 20; jjs> print(x + y); 30 jjs> quit(); >> Exemplo 5
  • 14. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.15 Nashorn usando jjs Exemplo 6
  • 15. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.16 SHELL SCRIPTING COM NASHORN
  • 16. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.17 Shell Scripting com Nashorn • Por que não utilizar uma linguagem que você já está familiarizado? • Acesso a um vasto número de bibliotecas Java • Extensões de scripting para simplificar • Documentos • Templates de Strings • Execução de comandos • Variáveis de ambiente Substituto mais simples para outras linguagens shell
  • 17. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.18 Schell Scripting usando Nashorn #!/usr/bin/jjs -doe -scripting # var dir = __DIR__ + "photos"; var files = `ls ${dir}`.trim().split("n"); var count = 1; for each (var file in files) { if (file.edsWith(".jpg")) { `mv ${dir}/${file} ${dir}/Photo${count++}.jpg`; } } Exemplo 7
  • 18. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.19 NASHORN E JAVAFX
  • 19. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.20 Nashorn e JavaFX • Método bem natural de trabalhar com JavaFX • Nashorn pode ser invocado a partir de FXML • FXML é uma opção, em formato XML, para definir interfaces em JavaFX • Modelo familiar para desenvolvedores de conteúdo Nashorn foi feito para o JavaFX
  • 20. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.21 Nashorn e JavaFX load("fx:base.js"); load("fx:controls.js"); load("fx:graphics.js"); $STAGE.title = "Hello World!"; var button = new Button(); button.text = "Say 'Hello World'"; button.onAction = function() print("Hello World!"); var root = new StackPane(); root.children.add(button); $STAGE.scene = new Scene(root, 300, 250); $STAGE.show(); Exemplo 8
  • 21. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.22 Recapitulando • Forte integração com Java • Pode ser usado a partir do Java • Nova ferramenta por linha de comando jjs • Supore a Shell Scripting • Suporte completo ao JavaFX
  • 22. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.23 Para saber mais • Download: java.oracle.com • Documentação: docs.oracle.com/javase • Treinamentos: education.oracle.com/java • Central do Java 8: www.oracle.com/java8 • Nashorn para Usuários • wiki.openjdk.java.net/display/Nashorn/Nashorn+Documentation • Exemplos: blogs.oracle.com/nashorn/ • Dúvidas: nashorn-dev@openjdk.java.net Java 8 e outros sites youtube.com/java blogs.oracle.comjava facebook.com/ilovejava @java @javaembedded nighthacking.com
  • 23. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.25 The preceding is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle.
  • 24. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.26
  • 25. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.27