Developing Modern Java Web Applications with Java EE 7 and AngularJS

Post on 13-Jan-2015

6.984 views 1 download

description

Developing Modern Java Web Applications with Java EE 7 and AngularJS

Transcript of Developing Modern Java Web Applications with Java EE 7 and AngularJS

OPENSHIFT Workshop

PRESENTED BY

Shekhar Gulati

Developing Modern Java Web Applications with Java EE 7 and

AngularJS

WHO AM I?

•  Shekhar  Gula+  -­‐-­‐  OpenShi1  Developer  Evangelist    •  Java  /  JavaScript  /  Python  /  NoSQL  /  Cloud  Guy    •  TwiEer  Handle  :  shekhargula*    •  Github  :  h,ps://github.com/shekhargula*  

•  Author  of  30  technologies  in  30  days  blog  series  h,ps://www.openshi9.com/blogs/learning-­‐30-­‐technologies-­‐in-­‐30-­‐days-­‐a-­‐developer-­‐challenge  

l  Define  Modern  Web  Applica+on  

l  Introduce  Java  EE  7  

l  GeRng  Started  with  Java  EE  7  

l  OpenShi1  for  Java(EE)  Developers  

l  Write  HackerPins  Applica+on  REST  Backend  

l  Look  at  AngularJS  

l  Write  HackerPins  AngularJS  Frontend  

l  Deploy  to  OpenShi1  

AGENDA

http://www.hackerpins.com/

CODE DU JOUR

https://github.com/shekhargulati/hackerpins-drdobbsindia-conference

Modern  Web  Applica*on  

 What  make’s  a  modern  web  applica*on?  

•  Exposes  REST  JSON  web  services  •  Single  backend  and  mul+ple  front  ends  

•  Embraces  HTML  5    •  GeoLoca+on,  Local  Storage,  Web  Sockets  

•  Single  page  web  applica+on  •  Uses  MV*  JavaScript  framework  

•  Stateless  so  that  you  can  scale  horizontally  

•  Uses  OAuth  •  Integrates  with  social  pla`orms  like  TwiEer,  Facebook,  Google+  

•  Embraces  Polyglot  Persistence  

•  Cloud  aware  

CAN  WE  BUILD  MODERN  WEB  APPLICATIONS  USING  JAVA  EE?  

Short  answer  is…  

 Yes  

This  session  will  try  to  convince  you  to  use  Java  EE  7  for  your  next  web  app.  

http://www.hackerpins.com/

Choose  Session  Delivery  Mode  

1.  Hands-­‐on  coding  –  No  slides  –  J  

2.  Slides  with  code  fragments  –  L  

Java  EE  *meline  

0  

10   12  

18  

24  

30  

38  

JPE  (1998)   J2EE  1.2  (1999)  

J2EE  1.3(2001)  

J2EE  1.4(2001)  

Java  EE  5(2006)  

Java  EE  6(2009)  

Java  EE  7(2013)  

Java  EE  Timeline  

Java  EE  Timeline  

Java  EE  6  changed  the  game…  It  was  lightweight  

•  Introduc+on  of  web  profile  

•  EJBs  can  be  packed  in  WAR  files  

•  Servlet  3.0  •  web.xml  became  op+onal,  @WebServlet,  @WebFilter  

•  Type  safe  contextual  dependency  injec+on(CDI)  •  DI  for  Java  EE,  event  support  

•  @Asynchronous  and  @Schedule  support  

•   RESTFul  web  services  support  with  JAX-­‐RS  1.1  

Java  EE  7  –  Produc*vity  and  HTML  5  Focused  

•  Builds  on  top  of  Java  EE  6  •  Embraces  HTML  5  

•  4  new  specs  •  3  major  spec  updates  

•  6  minor  spec  updates  

•  5    micro  updates  

The  Java  EE  7  Pla]orm  

Java EE 7 Platform

C

DI 1

.1

BEA

N V

ALI

DAT

ION

1.1

INTE

RC

EPTO

RS

1.2

CO

NC

UR

REN

CY

1.0

JPA 2.1

JTA 1.2 EJB 3.2 JMS 2.0

WEBSOCKET 1.0

SERVLET 3.1

JSP 2.3 EL 3.0 JSF 2.2

JCA 1.7

MAIL 1.5

BATCH 1.0

JSON-P 1.0

JAX-RS 2.0

New Major updates Minor/macro updates

Our  modern  Java  EE  7  stack  

Java EE 7 Platform

C

DI 1

.1

BEA

N V

ALI

DAT

ION

1.1

INTE

RC

EPTO

RS

1.2

CO

NC

UR

REN

CY

1.0

JPA 2.1

JTA 1.2 EJB 3.2

WEBSOCKET 1.0

JSON-P 1.0

JAX-RS 2.0

LETS  LOOK  AT  FEW  JAVA  EE  7  SPECS  

CDI  1.1-­‐-­‐  Context  and  Dependency  Injec*on    •  Allows  you  to  use  dependency  injec+on  in  Java  EE  

environment  without  third  party  libraries.  

•  Don’t  call  us.  We  will  call  you.  

•  CDI  container  manages  the  life  cycle  of  components.  

•  CDI  brings  dependency  injec+on,  context  and  scopes,  interceptors,  loose  coupling  and  strong  typing.  

•  Injected  bean  lifecycle  depends  on  the  target  bean.  

•  Turns  nearly  every  Java  class  into  CDI  bean  •  It  is  not  a  non  sta+c  inner  class  

•  It  is  a  concrete  class  or  annotated  with  decorators  

•  Has  default  constructor  with  no  parameters  or  declares  a  constructor  with  @Inject  

Enable  CDI  –  beans.xml  

<?xml  version="1.0"  encoding="UTF-­‐8"?>  

<beans  

               xmlns="hEp://xmlns.jcp.org/xml/ns/javaee"  

               xmlns:xsi="hEp://www.w3.org/2001/XMLSchema-­‐instance"  

               xsi:schemaLoca+on="hEp://xmlns.jcp.org/xml/ns/javaee    

                                           hEp://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"  

               bean-­‐discovery-­‐mode="all">  

</beans>  

CDI  Example  

Simple CDI Bean Injecting a bean

 public  class  LowercaseBeau+fier  implements  MessageBeau+fier  {  

       @Override  

       public  String  beau+fy(String  message)  {  

               return  message  !=  null  ?  message.toLowerCase()  :  null;  

       }  

}  

 public  interface  MessageBeau+fier  {  

       public  String  beau+fy(String  message);  

 }  

 

 @Applica+onScoped  

 public  class  StatusService  {  

       @Inject  

       private  MessageBeau+fier  messageBeau+fier;  

       public  Status  postStatus(String  message)  {  

               Status  status  =  new  Status(messageBeau+fier.beau+fy(message));  

               return  status;  

       }  

 }  

 

CDI    -­‐-­‐  Two  implementa*ons  MessageBeau*fier  

public  class  UppercaseBeau+fier  implements  MessageBeau+fier  {  

       @Override  

       public  String  beau+fy(String  message)  {  

               return  message  !=  null  ?  message.toUpperCase()  :  null;  

       }  

}  

public  class  LowercaseBeau+fier  implements  MessageBeau+fier  {  

       @Override  

       public  String  beau+fy(String  message)  {  

               return  message  !=  null  ?  message.toLowerCase()  :  null;  

       }  

}  

Code will throw exception-- Ambiguous dependencies for type MessageBeautifier

CDI  –  Use  @Qualifier  

@Qualifier  

@Reten+on(Reten+onPolicy.RUNTIME)  

@Target({ElementType.METHOD,  ElementType.TYPE,  ElementType.FIELD})  

public  @interface  Beau+fier  {  

       Beau+fierType  type();  

}  

public  enum  Beau+fierType  {  

       LOWERCASE,  UPPERCASE  

}  

 

 

CDI  -­‐-­‐  @Qualifier  usage  

 @Beau+fier(type  =  Beau+fierType.LOWERCASE)  

 public  class  LowercaseBeau+fier  implements  MessageBeau+fier  {  

       @Override  

       public  String  beau+fy(String  message)  {  

               return  message  !=  null  ?  message.toLowerCase()  :  null;  

       }  

}  

 @Beau+fier(type  =  Beau+fierType.UPPERCASE)  

 public  class  UppercaseBeau+fier  implements  MessageBeau+fier  {  

 

       @Override  

       public  String  beau+fy(String  message)  {  

               return  message  !=  null  ?  message.toUpperCase()  :  null;  

       }  

}  

CDI  –  Loose  Coupling  and  Sta*c  Typing  

@Applica+onScoped  

public  class  StatusService  {  

       @Inject  

       @Beau+fier(type  =  Beau+fierType.UPPERCASE)  

       private  MessageBeau+fier  messageBeau+fier;  

 

       public  Status  postStatus(String  message)  {  

               Status  status  =  new  Status(messageBeau+fier.beau+fy(message));  

return  status;  

       }  

}  

CDI  1.1:  What’s  new  in  Java  EE  7?  

•  Finer  scanning  control  in  beans.xml  •  bean-­‐discovery-­‐mode  aEribute  –  all,  none,  annotated  

•  @Vetoed  annota+on  to  veto  processing  of  a  package  or  class.  

•  You  can  use  @Transac+onal  with  CDI  beans.  •  You  can  get  away  from  EJBs.  

Bean  Valida*on  

•  Specifies  common  valida+on  concept  for  JavaBeans.  

•  Allow  you  to  put  constraints  on  data  to  make  sure  it  is  valid.  

•  Annota+on  based  constraints  •  Use  constraint  in  any  layer  

Bean  Valida*on  Example  

public  class  Status{  

       @NotNull      @Size(max  =  140)  

       private  String  message;  

       @NotNull  @Past  

       private  final  Date  postedAt;  

       @UniqueUrl  

       private  String  url;  

       public  Status()  {}  

}  

Bean  Valida*on  1.1  –    What’s  new  in  Java  EE  7?  

•  You  can  validate  method  parameters  and  return  types.  

•  Integra+on  with  JAX-­‐RS  

 @Path(“/statuses”) public class StatusService { @POST @Produces(“application/json”) public @NotNull Status postStatus(@Valid @NotNull Status status) { // persist in database return status; } }

Interceptors  

•  Allows  you  to  add  cross  cuRng  concerns  to  your  beans.  

•  Lightweight  AOP  •  You  can  use  them  to  intercept  method  calls,  

constructor  invoca+on,  Method  +meouts.  

Interceptors  in  ac*on    @Interceptor  

 @Loggable  

 public  class  LoggingInterceptor  {  

       @Inject  

       private  Logger  logger;  

       @AroundInvoke  

       public  Object  logMethodCall(Invoca+onContext  invoca+onContext)  throws  Excep+on  {  

 logger.trace(String.format("Entering  method  %s",  invoca+onContext.getMethod().getName());  

 try{  

 return  invoca+onContext.proceed();  

 }finally{    

 logger.trace(String.format("Entering  method  %s",  invoca+onContext.getMethod().getName());  

 

 @InterceptorBinding  

 @Reten+on(Reten+onPolicy.RUNTIME)  

 @Target({ElementType.TYPE,  ElementType.METHOD})  

 public  @interface  Loggable  {  

 }  

   

 @Loggable  

 @Applica+onScoped  

 public  class  StatusService  {  

 }  

Interceptor InterceptorBinding and usage

Interceptors  1.2  –  What’s  new  in  Java  EE  7?    

•  You  can  now  intercept  constructor  invoca+ons  using  @AroundConstruct  

•  You  can  priori+ze  interceptors  using  @Priority.  

JPA    

•  Describes  the  management  of  rela+onal  data  in  applica+ons.  

•  JPA  implementa+ons  provide  ORM  framework  

•  JPA  provides  an  API  to  perform  CRUD  opera+on  on  en++es.  

•  An  en+ty  is  a  POJO,  whose  state  is  mapped  to  a  rela+onal  database.  

•  JPA  also  provides  a  query  language  to  make  queries  against  en++es  stored  in  rela+onal  database.  

JPA  in  ac*on  

 @En+ty  

 public  class  Status  {  

       @Id  

       @GeneratedValue(strategy  =  Genera+onType.AUTO)  

       private  Long  id;  

       private  String  message;  

       private  final  Date  postedAt  =  new  Date();  

 }  

 @Stateless  

 public  class  StatusService  {  

       @Inject  

       private  En+tyManager  en+tyManager;  

       public  Status  postStatus(String  message){  

               Status  status  =  new  Status(message);  

               en+tyManager.persist(status);  

               return  status;  

       }  

 }  

 

JPA  2.1  –  What’s  new  in  Java  EE  7?  

•  Schema  genera+on  using  standard  proper+es.  

•  Use  @Index  to  define  addi+onal  indexes  in  schema  genera+on.  

•  New  En+tyGraph  API  available  in  En+tyManager.  

Web  Socket  1.0    -­‐-­‐  New  in  Java  EE  7  

•  Bidirec+onal  full  duplex  messaging  

•  Annota+on  based  or  interface  based  programming  model  

•  Server  and  Client  WebSocket  Endpoint  

•  Integrated  with  Java  EE  

Web  Sockets  in  Ac*on  @ServerEndpoint("/reverse")  

public  class  ReverseEchoWebSocketServerEndpoint  {  

       @OnOpen  

       public  void  onOpen(){  

               System.out.println("Connec+on  opened");  

       }  

       @OnMessage  

       public  String  onMessage(String  message){  

               return  StringU+ls.reverse(message);  

       }  

       @OnClose  

       public  void  connec+onClose(){  

               System.out.println("Closed  connec+on");}  

 

 var  wsUrl  =  'hEp://localhost:8080/example/reverse’;  

 var  ws  =  new  WebSocket(wsUrl);  

 ws.onopen  =  func+on(event){};  

 ws.onclose  =  func+on(event){  

   console.log("Remote  host  closed  or  refused  WebSocket  connec+on");  

 };  

 ws.onmessage  =  func+on(event){  

       $("textarea#outputMessage").val(event.data);  

 };  

 $(".btn").on('click',func+on(){  

       var  message  =  $('textarea#inputMessage').val();  

       ws.send(message);  

});  

Server Endpoint JavaScript Web Socket client

JSON-­‐P  1.0  

•  API  to  read  or  write  JSON  •  Two  API’s  

•  Streaming  API  •  Low  level  API  to  parse  and  generate  JSON  

•  Similar  to  StAX  API  in  XML  world  

•  Object  model  API  •  High  level  API  

•  Similar  to  DOM  API  in  XML  world    

JsonReader  and  JsonWriter  Example  

JsonReader  jsonReader  =  Json.createReader(new  StringReader(response));  

JsonObject  jsonObject  =  jsonReader.readObject();  

String  bannerImage  =  jsonObject.getString("image");  

String  descrip+on  =  jsonObject.getString("text");  

String  +tle  =  jsonObject.getString("+tle");  

Map<String,  String>  fetchedData  =  new  HashMap<>();  

fetchedData.put("picUrl",  bannerImage);  

fetchedData.put("descrip+on",  descrip+on);  

fetchedData.put("+tle",  +tle);  

 

JsonObjectBuilder  builder  =  Json.createObjectBuilder();  

               builder.add("firstName",  "Shekhar")  

                             .add("lastName",  "Gula+");  

               JsonObject  result  =  builder.build();  

               StringWriter  sw  =  new  StringWriter();  

               try  (JsonWriter  writer  =  Json.createWriter(sw))  {  

                       writer.writeObject(result);  

               }  

               sw.toString();  

JsonReader Example JsonWriter Example

Gefng  Started  with  Java  EE  7    

Three  ways:  

1.  Use  Maven  archetype  1.  Use  com.airhacks  JavaEE7  archetype  

2.  Use  template  Git  repository  

3.  Use  OpenShi1  to  create  a  publicly  accessible  web  applica+on  in  minutes.  

OpenShift

OPENSHIFT  OVERVIEW  

OpenShift is

PaaS by Red Hat

Multi-language, Auto-Scaling, Self-service,

Elastic, Cloud Application Platform

l  Focus  on  code,  not  on  configura+on  

l  Speeds  up  deployment  

l  Scales  your  app  

l  Efficient  

l  Embraces  polyglot  programming  and  persistence.  

WHY PAAS?

OUR STACK

origin

Public Cloud Service

On-premise or Private Cloud Software

Open Source Project

FLAVORS OF OPENSHIFT

l   Scalable  Java  EE  6  supported  stack  via  JBoss  AS7  and  JBoss  EAP  6.  

l   Java  EE  7  supported  via  WildFly  community  cartridge.  

l   Scalable  Tomcat  6  and  Tomcat  7  support.  

l   Hot  deployment.  

l   Debugging.  

l   Supports  Maven,  Ant,  and  Gradle.  

l   Supports  con+nuous  integra+on  via  Jenkins.  

l   Eclipse  and  IntelliJ  Idea  support.  

l   Can  run  Java  8,  JeEy,  Tomcat  8,  Tom  EE,  etc.  

OPENSHIFT JAVA STORY

Demo  -­‐  Crea*ng  OpenShi9  WildFly  Applica*on  

•  Go  to  hEps://www.openshi1.com/  and  sign  up  for  OpenShi1  Online.  

•  Verify  your  email  

•  Login  into  OpenShi1  web  console  •  Search  for  WildFly  applica+on  type  

•  Give  applica+on  name  and  press  “Create  Applica+on”  buEon.  

Demo  :  Add  MySQL  Cartridge  

 

 

 

Add  MySQL  5.5  cartridge  from  web  console  

Demo  :  Import  applica*on  in  Eclipse  

 

 

 

Use  OpenShi1  Eclipse  plugin  

Demo  :  Pull  the  Code  from  Github  Repository  

$  git  rm  -­‐rf  src/  pom.xml  

$  git  commit  -­‐am  “deleted  template  sourcecode”  

$  git  remote  add  upstream  -­‐m  master  hEps://github.com/shekhargula+/hackerpins-­‐drdobbsindia-­‐conference  

$  git  pull  -­‐s  recursive  -­‐X  theirs  upstream  master  

 

Demo  :  Code  walkthrough  REST  backend  

$  git  checkout  remotes/origin/backend  

•  JAX-­‐RS  resources  •  Async  JAX-­‐RS  •  JPA  layer  •  CDI  usage  •  Bean  valida+on  

AngularJS  –  in  one  slide  

•  Extending  HTML  to  add  dynamic  nature  so  that  we  can  build  modern  web  applica+ons  with  ease.  

•  Brings  you  back  to  HTML  

•  Declara+ve  approach  

•  Eliminates  DOM  manipula+on  by  two  way  data  binding  

•  Ideal  for  building  single  page  web  applica+ons  

AngularJS  –  Main  Components  

•  Services  :  Objects  or  func+ons  to  carry  out  specific  tasks  common  to  the  whole  web  applica+on.  

•  Direc+ves  :  allows  you  to  extend  HTML  by  defining  your  own  project  specific  direc+ves.  

•  Controller  :  constructor  func+ons  that  define  the  app  business  logic.  

•  Scope  :  contains  model  data.  Glues  controller  and  views.  

Angular  in  Ac*on  <!DOCTYPE  html>  

<html  ng-­‐app>  

<head></head>  

<body>  

<div  ng-­‐init=”friends=  [{name:’karan'},{name:'rahul'},{name:'sameer'}]”>  

       <ul>  

       <li  ng-­‐repeat=”friend  in  friends">  

                 {{friend.name}}  

       </li>  

       </ul>  

</div>  

<script  src="hEp://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>  

</body>  

</html>  http://plnkr.co/edit/NU9wjQppgLMWujpH4bGU?p=preview

AngularJS:  Controller  and  Scope  in  Ac*on  <!DOCTYPE  html>  

<html  ng-­‐app>  

<head></head>  

<body>  

<div  ng-­‐controller="FriendsCtrl”>  

       <ul>                <li  ng-­‐repeat="friend  in  friends”>{{friend.name}}  </li></ul>  

</div>  

<script  src="hEp://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>  

<script>  

       func+on  FriendsCtrl($scope)  {  

               $scope.friends  =  [{name:  'karan'},{name:  'rahul'},{name:  'sameer'}]  

       }  

</script>  

</body>  

</html>  

http://plnkr.co/edit/1txkaBnZhy5vZuTU6W4S?p=preview

AngularJS:  Adding  func*ons  to  controllers  <div  ng-­‐controller="FriendsCtrl”>  

       <ul>  

               <li  ng-­‐repeat="friend  in  friends">  

                       <a  ng-­‐click=hello(friend.name)>{{friend.name}}</a>  

               </li>        </ul></div>  

<script  src="hEp://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>  

<script>  

       func+on  FriendsCtrl($scope)  {  

               $scope.friends  =  [{name:  'karan'},{name:  'rahul'},{name:  'sameer'}]  

               $scope.hello  =  func+on(name){  

                       alert("Hello,  "+name)  

               }  

       }  

</script>  http://plnkr.co/edit/hjGbzeo3QNBeWpVE7H03?p=preview

Demo  :  Code  walkthrough  Angular  frontend  

$  git  checkout  remotes/origin/frontend  

•  Controllers  

Deploy  to  OpenShi9  

 

 

 

$  git  push  

QUESTIONS?

DONE!