Sie sind auf Seite 1von 96

ANGULAR 2 BOOT

Arnaud Tournier - LTE Consulting - JavaOne 2016 - San Francisco


ARNAUD TOURNIER
LTE Consulting founder.
Speaker Devoxx France, JUGs, GWT.create, GWTCon, etc
Training : Java, C#, .net, Typescript, GWT, Angular 2, JavaEE,
Spring, git
Email : ltearno@gmail.com
Twitter : @ltearno
Web : www.lteconsulting.fr
Full stack (x86_64 to JavaScript)
THIS PRESENTATION IS ONLINE!
lteconsulting.fr/angular2boot-javaone
works on your phone too ;)
Demo code available at

github.com/ltearno/tour-of-heroes
github.com/ltearno/angular2boot-demos
ANGULAR 2 BOOT?
A new RIA paradigm for Java : programming Angular 2 with
Java 8.
The coolest Java 8 RIA framework in the place ;)
lteconsulting.fr/angular2boot
A MORE TECHNICAL TITLE
Integrating Angular 2 and GWT 2.8:
problems and solutions
WHY?
Angular 2 natively supports Typescript and Javascript.
Angular 2 for Dart is maintained by the Dart team.
Nevertheless Java has all the required features.

Why is not Java in the party? Lets remedy!


It all started as an experiment
But since it rocks, I wanted to show it to the world!
THE RECIPE

ANGULAR 2
non invasive,
ef cient,
modern architecture, simple and effective.
GWT 2.8
Java 8 (strong typing, lambdas, streams, )
JsInterop (easy integration with JS)
SuperDevMode (compile on reload)
Optimized compilation (generated js size, ef ciency)
JSR 269
Java Annotation Processing API,
Code generation integrated with compilation.
SPRING BOOT
Standalone server application (-service friendly),
Easy to start with,
Rich API,
Note: Angular2Gwt works with any backend.
PRESENTATION STRUCTURE
Angular 2,
GWT,
Angular2Boot,
Demonstration,
Challenges,
Roadmap,
Q&A
ANGULAR
Angular 1 was released in 2009.
AT THAT TIME, THERE WAS NOT A LOT OF
JAVASCRIPT RIA FRAMEWORKS
ANGULAR BROUGHT THE DATA BINDING INTO
THE BROWSER
AND YOU SUDDENDLY WERE ABLE TO WRITE A
TODO LIST APPLICATION IN 15 LINES OF CODE!
ENORMOUS SUCCESS!
MILLIONS OF APPLICATIONS WERE BUILT WITH
ANGULAR
WHEN IT CAME TO EVOLVE THE FRAMEWORK,
THE TEAM DECIDED TO BUILD UPON THE
(ENORMOUS) RETURN OF EXPERIENCE THEY
HAD
AND THEY DECIDED TO WRITE ANGULAR 2 FROM
SCRATCH!
WHY? WHAT WERE THE PROBLEMS?
ARCHITECTURAL PROBLEMS
Dynamic scoping,
Slow dirty checking,
Insane amount of directives to learn,
Dif cult debugging
ANGULAR 2 FUNDAMENTALS
Modules,
Components,
Dependency Injection,
Change detection.
MODULES
Parts of the application are encapsulated into modules.
Leads to clean code and more advanced AOT compilation.
COMPONENTS
Basic blocks of your application.
A component is:

a view (template),
and a model (data and methods).

Interaction between view and model through data binding.


COMPONENTS
Each component is responsible for a part of the DOM tree.
Components also form a tree.
Components can interacts with each other through cleanly
de ned ways.
COMPONENTS TREE
DEPENDENCY INJECTION
Sharing services between components.
Lifecycle and dependencies are managed by Angular.
Each component has a Dependency Injector.
Those also form a tree.
CHANGE DETECTION
Angular uses Zone.js to track changes.
Zones == asynchronous TLS.
Preserve an execution context accross asynchronous calls.
(done by patching most of the browsers async functions)
GWT
HISTORY
First version released in 2006.
Really big success!
Community of ~ 100k+ developpers.
CONTEXT
At that time, Javascript ecosystem sucked!
Browsers were incompatible
Developping complex web applications was hell!
WHAT GWT BROUGHT
Hide browsers incompatibilities,
Widgets to build the UI : Swing-like,
A complete toolkit for the Web (resource caching, RPC, ),
A very good compiler!
COMPILER POWER SAMPLE
Shapes=newSquare(2)
inta=s.getArea()
BECOMES
Squares=newSquare(2)//NoneedfortheShapeinterface
inta=s.length*s.length//Methodinlining
AND THEN
inta=4//constantsresolution

All that at compile time!


AND NOW IN 2016
The Javascript ecosystem really rocks! (we need to
leverage that)
The evergreen browsers are compatible (do not require a
layer above them anymore)
OTHER PROBLEMS
The compilation was (really very) slow.
GWT did too much: build system, optimisations,
permutations, not following standards, proprietary RPC, code
change detection, templating
Many things GWT did are now available as standard web
tools.
IN OTHER WORDS
GWT is now very far away from the Web we know today.
GWT-RPC REST Json Web services

Widgets Native HTML5 (ok lacks


encapsulation)

Code splitting ES7 modules, WebPack


code splitting

Optimisations Closure compiler,

Code Generators JSR-269

JVM debugging SourceMaps


GWT 2.8
GWT 2.8 is the transition version to a new future:

JsInterop,
Java 8 language,
Time to drop Widgets and old stuff!
GWT 3 (AKA J2CL)
not released yet

Lightweight,
More unopiniated (can be integrated anywhere),
Drops a lot of functionalities done now by standard tools.
GWT FUNDAMENTALS
THE COMPILER
Preserves Java semantic,
Still does a bunch of optimisations (pruning, static
analysis..),
Mostly ouputs modern Javascript, optimizable with
Closure Compiler.
JSINTEROP
A very easy way to integrate Javascript and Java code.
A two-way road (JSJava, JavaJS)
JSINTEROP
To use JS code from Java, you just have to describe the JS
type :
@JsType(isNative=true)
publicclassXMLHttpRequest
{
@JsMethod
publicnativevoidopen(Stringmethod,Stringurl)

@JsMethod
publicnativevoidsend(Objectdata)

//...
}
JSINTEROP
Then use the class as a normal Java class
XMLHttpRequestrequest=newXMLHttpRequest()

request.open("GET","service.json")
request.setOnreadystatechange(event>{
...
}

request.send(...)
JSINTEROP
And the other way around (exporting Java to JS)
packagefr.lteconsulting

@JsType
publicclassRobot
{
@JsProperty
privatebooleanwifiOn

@JsConstructor
publicRobot(DataServicedataService){...}

@JsMethod
protectedvoidmove(){...}
}
JSINTEROP
In Javascript :
letrobot=newfr.lteconsulting.Robot(dataService)

robot.wifiOn=true

robot.move()

ps: can we drop semicolons in Java?


SUPERDEVMODE
Fast incremental compiler for development,
Compile time function of code changes and not code base
size!
JSR 269 - PLUGGABLE ANNOTATION
PROCESSING API
Code generation in Java (source, byte-code and resource).
Integrated with the Java compiler.
Based on annotations. The developers annotation processor
receives parts of the programs AST.
GOOD POINTS
API is easy to use.
Generated code is visible and debuggable,
Generated code is known before end of compilation so you
can reference it in your code.
No overhead at runtime.
(Does not depend on byte code: GWT compatible)
HOW IT WORKS
You must register your Annotation processors (through SPI).
Java source les are compiled during rounds.
Each round, processors are activated and receive the
programs AST.
They can then generate les which will be part of the next
round.
When no le is generated during a round, real compilation
happens.
ANNOTATION PROCESSOR
@SupportedAnnotationTypes("fr.lteconsulting.AutoUi")
@SupportedSourceVersion(SourceVersion.RELEASE_8)
publicclassAutoUiProcessorextendsAbstractProcessor{
@Override
publicbooleanprocess(
Set<TypeElement>annotations,
RoundEnvironmentround){
for(TypeElementelement:
round.getElementsAnnotatedWith(AutoUi.class)){
...
JavaFileObjectjavaFile=filer.createSourceFile(classFqn)
Writerwriter=javaFile.openWriter()
...
}
returntrue
}
}
JAVA WORKFLOW
JUST ONE MORE THING
A processor can break the compilation by outputting errors.
It can also provide the user with tips by outputting warnings.
ANGULAR2BOOT
Angular2Gwt: GWT and Angular2 integration library,
Spring boot: powerful and simple backend,
Dead simple bootstrapping to begin development.
EASY TO TRY
mvnarchetype:generate\
DarchetypeGroupId=fr.lteconsulting\
DarchetypeArtifactId=angular2gwt.archetype\
DarchetypeVersion=1.5

mvncleaninstall

javajartarget/YOUR_ARTIFACT_ID.jar
COMPILE ON RELOAD
#Backend
mvnspringboot:run

#Frontend
mvngwt:runcodeserver
PRODUCTION CODE
mvncleaninstall

You get an autonomous fat jar!


ARCHITECTURE
QUICK DEMONSTRATION
JAVA/JAVASCRIPT COMMUNICATION
JsInterop can do that.
Java can provide components to Angular runtime.
And vice-versa.
FEEDING ANGULAR WITH METADATAS
Angular requires metadata on components (DI, routing,
inputs/ouputs, )
Angular uses ES7/Typescript decorators (ex @Component()).
Those decorators alter class prototypes at runtime.
Less required boilerplate code.
IN JAVA?
Annotations can play the role of decorators (ex
@Component).
Those are processed at compile time.
And generate RTTI code for Angular.
HOW?
JSR-269 is used to generate RTTI,
Use Angular JS api through JsInterop to provide the RTTI.
HOW?
Fetch Java class compiled JS constructor at runtime with
JsInterop,
Patch it with Angular required metadata,
Provide the patched constructor function to Angular.
CONSISTENT SYNTAX
The developper should be able to read JS documentation and
know how to code in Java.
In brief, we want syntax consistency.
TYPESCRIPT WRITTEN COMPONENT
@Component({selector:"myherodetail",
templateUrl:"herodetail.component.html",
styleUrls:"herodetail.component.css"})
exportclassHeroDetailComponent
{
@Input()hero=null
@Output()updated=newEventEmitter()

HeroDetailComponent(privateHeroServiceheroService){}

ngOnInit(){...}

//...
}
JAVA EQUIVALENT
@Component(selector="myherodetail",
templateUrl="herodetail.component.html",
styleUrls="herodetail.component.css")
@JsType
publicclassHeroDetailComponentimplementsOnInit
{
@InputpublicHerohero=null
@OutputpublicEventEmitter<Hero>updated=newEventEmitter<>()

privateHeroServiceheroService

publicHeroDetailComponent(HeroServiceheroService)
{
this.heroService=heroService
}

@Override
publicvoidngOnInit(){...}
THE INSTANCEOF PROBLEM
Angular checks at runtime that components are valid.
With SuperDevMode, code is loaded in an external frame
thus breaking instanceof operator.
Few places needed to be patched
MODULE LOADING PROBLEM
GWT is not SystemJS (ES7 modules) friendly.
Need to generate a bundle with all Angular inside (you can
choose/build your bundle depending on what you need).
BUILDING ANGULAR
Angular 2 requires a strict environment to be built.
Docker to the rescue!
From RC6 to nal: 1 hour of work!
LEGACY GWT WIDGETS INTEGRATION
In fact it worked out of the box, no problem, cool!
EMULATING ES6 GET AND SET OPERATORS
Java does not provide this language facility
So we use JSR-269 to generate trampoline functions,
triggered by @PropertyGetter and @Input annotations.
TESTING
Unit tests,
Integration tests.
UNIT TESTS
No production-ready way to do that with Angular yet,
Dif cult to use the GWTTestCase facility (need to
bootstrap Angular in the testing environment which runs
under HTMLUnit which is not ready for ES6. More, GWT
uses Jetty as a testing backend but we want to be able to
use any backend - Angular2Boot uses SpringBoot).

No real solution yet


INTEGRATION TESTS
Using Selenium WebDriver and Spring integration testing
facilities, it is done easily!
Demonstration!
MORE DEMOS
ADVANTAGES OF ANGULAR2BOOT
Developper doesnt need to know internals of
Angular2Gwt, everything is taken care of.
Work ow is really comfortable.
GWT compilation without User module (Widgets) is dead
fast.
Really easy to bootstrap a working application (only one
maven dependency in fact).
Optimizations done by GWT are still very powerful: fast
application, small download.
JAVASCRIPT AND JAVA COMMMUNITIES NEED
TO EXCHANGE!
WebPack inspired by GWTs code splitting,
Problems solved by Java since 20 years should inspire JS!
Dynamism of the JS ecosystem should inpire Java!
USE CASES
100% Java applications (small or big),
Service implementations in Java (strongly typed Web
service interfacing),
JS, Typescript and Java integration,
Would t well with JHipster
FUTURE WORK, IDEAS
GENERATE UI CODE FROM MODEL OBJECTS
Code generation is not easy in Javascript but really easy in
Java.
(see GWTCon talk on JSR-269).
GENERATE SERVICE ACCESS CODE FROM
BACKEND INTERFACE
Same idea as the previous one
TS DEFINITIONS GENERATION
Generate TS descriptions of Java components for easy
integration of Java components into a TS Angular application.
RUN ANGULAR IN NASHORN TO DO SERVER-SIDE
RENDERING (ANGULAR UNIVERSAL)
TRY THAT IN NATIVESCRIPT
MODULE LOADING
Not easy!
Best is maybe to wait for GWT3 (J2Cl) which will be more
ES7 module friendly.
This will allow more AOT compilation optimizations (Angular
compiler may be able to work on the generated code).
Better integration with JS build and packaging tools.
STATIC ANALYSIS OF JAVA CODE IS REALLY
EASY!
BUNDLING THE GWT GENERATED JS TOGETHER
WITH ANGULAR RUNTIME FOR BETTER
COMPRESSION.
CONCLUSION
Tested on little projects, was very impressive!
Gives GWT a second youth! (only uses the core of it).
(IMHO) Take the opportunity to throw some rules out of
the window! (getter/setter, naming, ).
QUESTIONS?
THANKS, IT WAS A PLEASURE!
lteconsulting.fr/angular2boot

Das könnte Ihnen auch gefallen