Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Java SE 8 for Java EE Developers

17,465 views

Published on

Java SE 8 brings a bounty of improvements - Lambda expressions, the new Date Time API, Completable Futures, streams and repeatable annotations. In this session we will explore how these features can be utilized inside Java EE 7 and Java EE 8 applications with APIs such as Servlet, JAX-RS, JSON-P, JSF, EJB 3, JPA and Java EE Concurrency Utilities.

Published in: Technology

Java SE 8 for Java EE Developers

  1. 1. Others Talk, We Listen. Java SE 8 for Java EE Developers Reza Rahman Senior Architect rrahman@captechconsulting.com @reza_rahman
  2. 2. CapTech Full-service US national IT consulting firm that focuses on client best interests, trust, servant leadership, culture, professionalism and technical excellence. #28 in Vault's Consulting Top 50 #3 Best Consulting Internship #9 Best Overall Internship #1 in Meeting Client’s Needs #7 Best Firm to Work For #1 in Career Development Ranked for the 7th Consecutive Year Copyright © 2015 CapTech Ventures, Inc. All rights reserved.
  3. 3. Java SE 8 and Java EE • Java SE 8 is one of the most significant releases in years • Extremely well adopted • Most Java EE 7 runtimes support Java SE 8 • Java SE 8 can already be used well with Java EE • Further alignment being done in Java EE 8 and beyond Copyright © 2015 CapTech Ventures, Inc. All rights reserved.
  4. 4. Lambdas • Introducing functional programming without breaking Java • Requires change in thinking to become true believer • Practical benefits for the rest of us • Streams, CompletableFuture • Forward compatible – good for use with Java EE 7 • An actual syntax change at the language level • Syntactic sugar over anonymous inner classes? Copyright © 2015 CapTech Ventures, Inc. All rights reserved.
  5. 5. Lambdas Copyright © 2015 CapTech Ventures, Inc. All rights reserved. The Problem List<Student> students = ... double highestScore = 0.0; for (Student s : students) { if (s.gradYear == 2011) { if (s.score > highestScore) { highestScore = s.score; } }
  6. 6. Lambdas Copyright © 2015 CapTech Ventures, Inc. All rights reserved. An Inelegant Solution List<Student> students = ... double highestScore = students. filter(new Predicate<Student>() { public boolean op(Student s) { return s.getGradYear() == 2011; } }). map(new Mapper<Student,Double>() { public Double extract(Student s) { return s.getScore(); } }). max();
  7. 7. Lambdas Copyright © 2015 CapTech Ventures, Inc. All rights reserved. The Elegant Solution SomeList<Student> students = ... double highestScore = students. filter(Student s -> s.getGradYear() == 2011). map(Student s -> s.getScore()). max();
  8. 8. Asynchronous Servlet and Lambdas Copyright © 2015 CapTech Ventures, Inc. All rights reserved. @WebServlet(urlPatterns={"/report"}, asyncSupported=true) public class AsyncServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { ... final AsyncContext asyncContext = request.startAsync(); asyncContext.start(() -> { ReportParameters parameters = parseReportParameters(asyncContext.getRequest()); Report report = generateReport(parameters); printReport(report, asyncContext); asyncContext.complete(); }); } }
  9. 9. Streams Copyright © 2015 CapTech Ventures, Inc. All rights reserved. • Applying lambdas to the Collections API • Bulk operations • Sequence (“stream”) of data int sum = transactions.stream(). filter(t -> t.getBuyer().getCity().equals(“Philly”)). mapToInt(Transaction::getPrice). sum(); Source Intermediate operation Terminal operation
  10. 10. JSON-P Stream Copyright © 2015 CapTech Ventures, Inc. All rights reserved. [ { "name":"Duke", "gender":"male", "phones":[ "home":"650 123- 4567",‐ ‐ "mobile":"650- 111- 2222"‐ ‐ ] }, { "name":"Jane", ... ] JsonArray contacts = Json.createArrayBuilder() .add(...
  11. 11. JSON-P Stream Copyright © 2015 CapTech Ventures, Inc. All rights reserved. Map<String, Long> names = contacts.getValuesAs(JsonObject.class).stream() .filter(x -> "female".equals(x.getString("gender"))) .map(x -> (x.getString("name"))) .collect( Collectors.groupingBy( Function.identity(), Collectors.counting() ) );
  12. 12. Date/Time API • Significant improvement over current Java date types • Date, Calendar • Unified, comprehensive, modern model • Builder pattern, fluent API • Manipulating temporal values • Better internationalization Copyright © 2015 CapTech Ventures, Inc. All rights reserved.
  13. 13. Date/Time API Copyright © 2015 CapTech Ventures, Inc. All rights reserved. Key Artifacts • LocalTime • LocalDate • LocalDateTime • ZonedDateTime • Instant • Duration • Period
  14. 14. Date/Time API Examples // Get the current date and time LocalDateTime now = LocalDateTime.now(); // Returns formatted date and time // “2013-10-21T20:25:15:16.256” now.toString(); // Add 5 hours LocalDateTime later = now.plus(5, HOURS); // Subtract 2 days LocalDateTime earlier = now.minus(2, DAYS); Copyright © 2015 CapTech Ventures, Inc. All rights reserved.
  15. 15. The Date/Time API with JPA • JPA does not yet support the Date/Time API • This is a high priority item to fix in Java EE 8 • It is possible to use JPA converters as a workaround • Latest versions of Hibernate does support the Date/Time API Copyright © 2015 CapTech Ventures, Inc. All rights reserved.
  16. 16. Date/Time API with JPA Copyright © 2015 CapTech Ventures, Inc. All rights reserved. Using JPA Converters @Entity public class Accident { @Convert(converter=InstantConverter.class) @Temporal(TemporalType.TIME) private Instant when; }
  17. 17. Date/Time API with JPA Copyright © 2015 CapTech Ventures, Inc. All rights reserved. Using JPA Converters @Converter public class InstantConverter implements AttributeConverter<Instant, Date> { public Date convertToDatabaseColumn(Instant instant) { return Date.from(instant); } public Instant convertToEntityAttribute(Date date) { return date.toInstant(); } }
  18. 18. The Date/Time API with JSF • JSF does not yet support the Date/Time API • This is fixed in JSF 2.3/Java EE 8 • JSF converters can be used as workaround Copyright © 2015 CapTech Ventures, Inc. All rights reserved.
  19. 19. Date/Time API with JSF Copyright © 2015 CapTech Ventures, Inc. All rights reserved. Using JSF Converters @FacesConverter(“InstantConverter”) public class InstantConverter implements Converter { @Override public Object getAsObject(FacesContext ctx, ..., String value) { return Instant.parse(value); } ...
  20. 20. Date/Time API with JSF Copyright © 2015 CapTech Ventures, Inc. All rights reserved. Using JSF Converters ... @Override public String getAsString(FacesContext ctx, ..., Object value) { DateTimeFormatter formatter = DateTimeFormatter .ofLocalizedDateTime(FormatStyle.SHORT) .withLocale(Locale.US) .withZone(ZoneId.systemDefault()); return formatter.format((TemporalAccessor) value); } }
  21. 21. Date/Time API with JSF Copyright © 2015 CapTech Ventures, Inc. All rights reserved. Using JSF Converters <h:form> <h:inputText id = “date” value = “#{registerAccident.when}” size = “20” required=“true” label = “when” converter = “instantConverter” /> ... @Named @ViewScoped public class RegisterAccident { Instant when; ...
  22. 22. Repeatable Annotations • In Java SE 8, annotations can now be repeated • A lot of applicability in Java EE • @DataSourceDefinition • @NamedQuery • @JMSDestinationDefinition • @JMSConnectionFactoryDefinition • @MailSessionDefinition • @Schedule Copyright © 2015 CapTech Ventures, Inc. All rights reserved.
  23. 23. Repeatable Annotations in Java EE Copyright © 2015 CapTech Ventures, Inc. All rights reserved. @NamedQueries({ @NamedQuery(name=SELECT_ALL, query="..."), @NamedQuery(name=COUNT_ALL, query="...") }) public class Customer { ... @NamedQuery(name=SELECT_ALL, query="...") @NamedQuery(name=COUNT_ALL, query="...") public class Customer { ...
  24. 24. Completable Future • Futures and callbacks both have serious flaws • Especially when it comes to significantly “reactive” code • CompletableFuture significantly better • Non-blocking, event-driven, composable and functional (via lambdas) Copyright © 2015 CapTech Ventures, Inc. All rights reserved.
  25. 25. Looks are Deceiving… Person p = ... Assets assets = getAssets(p); Liabilities liabilities = getLiabilities(p); Credit credit = calculateCreditScore(assets, liabilities); History history = getHealthHistory(p); Health health = calculateHeathScore(history); Coverage coverage = underwrite(credit, health); Copyright © 2015 CapTech Ventures, Inc. All rights reserved.
  26. 26. The Problem with Futures (and Callbacks) Person p = ... Future<Assets> f1 = executor.submit(() -> getAssets(p)); Future<Liabilities> f2 = executor.submit( () -> getLiabilities(p)); Future<Credit> f3 = executor.submit( () -> calculateCreditScore(f1.get(), f2.get())); // The unrelated calls below are now blocked for no reason Future<History> f4 = executor.submit(() -> getHealthHistory(p)); Future<Health> f5 = executor.submit( () -> calculateHeathScore(f4.get())); // Unrelated paths join below Future<Coverage> f6 = executor.submit( () -> underwrite(f3.get(), f5.get())); Copyright © 2015 CapTech Ventures, Inc. All rights reserved. Callbacks don’t block, but introduce callback hell… https://github.com/m-reza-rahman/reactive_javaee/blob/master/CallbackHell.java
  27. 27. CompletableFuture Basics public CompletableFuture<Confirmation> processPayment( Order order) { CompletableFuture<Confirmation> future = new CompletableFuture<>(); executor.execute(() -> { Confirmation status = ... future.complete(status); }); return future; } Copyright © 2015 CapTech Ventures, Inc. All rights reserved. paymentService .processPayment(order) .thenAccept( confirmation -> System.out.println(confirmation));
  28. 28. Functional Reactive to the Rescue? CompletableFuture<Assets> getAssets = CompletableFuture.supplyAsync(() -> getAssets(person)); CompletableFuture<Liabilities> getLiabilities = CompletableFuture.supplyAsync(() -> getLiabilities(person)); CompletableFuture<Credit> calculateCreditScore = getAssets.thenCombineAsync(getLiabilities, (assets, liabilities) -> calculateCreditScore(assets, liabilities)); CompletableFuture<Health> calculateHeathScore = CompletableFuture.supplyAsync(() -> getHealthHistory(person)) .thenApplyAsync(history -> calculateHeathScore(history)); Coverage coverage = calculateCreditScore.thenCombineAsync(calculateHeathScore, (credit, health) -> underwrite(credit, health)).join(); Copyright © 2015 CapTech Ventures, Inc. All rights reserved.
  29. 29. CompletableFuture with JAX-RS Copyright © 2015 CapTech Ventures, Inc. All rights reserved. CompletionStage<String> cs1 = client.target("http://partner.us/api") .request() .rx() .get(String.class); CompletionStage<String> cs2 = client.target("http://supplier.be/api") .request() .rx() .get(String.class); // Get both responses in a List (when they are available) CompletionStage<List<String>> listCompletionStage = cs1.thenCombine(cs2, Arrays::asList);
  30. 30. Summary • Java SE 8 is one of the most significant releases in years • Most Java EE 7 runtimes support Java SE 8 • Java SE 8 can already be used well with Java EE • There are gaps that are being met in Java EE 8 and beyond Copyright © 2015 CapTech Ventures, Inc. All rights reserved.
  31. 31. Resources • Java EE Tutorials • http://docs.oracle.com/javaee/7/tutorial/doc/home.htm • Java SE Tutorials • http://docs.oracle.com/javase/tutorial/ • What's New in JDK 8 • http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html • Digging Deeper • http://docs.oracle.com/javaee/7/firstcup/doc/home.htm • https://glassfish.java.net/hol/ • http://cargotracker.java.net Copyright © 2015 CapTech Ventures, Inc. All rights reserved.
  32. 32. Copyright©2015CapTechVentures,Inc.Allrightsreserved.

×