java se 8 for java ee developers
TRANSCRIPT
Others Talk, We Listen.
Java SE 8 for Java EE DevelopersReza RahmanSenior [email protected]@reza_rahman
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.
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
• There are gaps that need to be met in Java EE 8
Copyright © 2015 CapTech Ventures, Inc. All rights reserved.
Lambdas
• Introducing functional programming without breaking Java• Imperative to Declarative• 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?• Parameterized business logic as data
Copyright © 2015 CapTech Ventures, Inc. All rights reserved.
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; } }
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();
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();
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(); }); }}
Streams
• Applying lambdas to the Collections API• Bulk operations• Sequence (“stream”) of data• Filter, map, reduce
• Performance, performance, performance• Lazy processing• Parallel processing
Copyright © 2015 CapTech Ventures, Inc. All rights reserved.
Streams
Copyright © 2015 CapTech Ventures, Inc. All rights reserved.
Pipeline
• A stream pipeline consists of three parts• A source• Zero or more intermediate operations• A terminal operation
int sum = transactions.stream(). filter(t -> t.getBuyer().getCity().equals(“Philly”)). mapToInt(Transaction::getPrice). sum();
Source
Intermediate operation
Terminal operation
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(...
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() ) );
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.
Date/Time API
Copyright © 2015 CapTech Ventures, Inc. All rights reserved.
Key Artifacts
• LocalTime• LocalDate• LocalDateTime• ZonedDateTime
• Instant• Duration• Period
Date/Time API Examples
// Get the current date and timeLocalDateTime now = LocalDateTime.now();
// Returns formatted date and time // “2013-10-21T20:25:15:16.256”now.toString();
// Add 5 hoursLocalDateTime later = now.plus(5, HOURS);
// Subtract 2 daysLocalDateTime earlier = now.minus(2, DAYS);
Copyright © 2015 CapTech Ventures, Inc. All rights reserved.
More Date/Time API Examples
LocalDate today = LocalDate.now();LocalDate bday = LocalDate.of(1979, 3, 10);Period timeAlive = Period.between(bday, today);int age = timeAlive.getYears();
// Periods can also be used as arguments in the .plus() // and .minus() methodsLocalDate calculatedBday = today.minus(timeAlive);
Copyright © 2015 CapTech Ventures, Inc. All rights reserved.
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.
Date/Time API with JPA
Copyright © 2015 CapTech Ventures, Inc. All rights reserved.
Using JPA Converters
@Entitypublic class Accident {
@Convert(converter=InstantConverter.class) @Temporal(TemporalType.TIME) private Instant when;}
Date/Time API with JPA
Copyright © 2015 CapTech Ventures, Inc. All rights reserved.
Using JPA Converters
@Converterpublic class InstantConverter implements AttributeConverter<Instant, Date> {
public Date convertToDatabaseColumn(Instant instant) { return Date.from(instant); }
public Instant convertToEntityAttribute(Date date) { return date.toInstant(); }}
The Date/Time API with JSF
• JSF does not yet support the Date/Time API• This is a high priority item to fix in Java EE 8• Code to introduce change has already been contributed to JSF 2.3 by
community• JSF converters can be used as workaround
Copyright © 2015 CapTech Ventures, Inc. All rights reserved.
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); } ...
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); }}
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 @ViewScopedpublic class RegisterAccident { Instant when; ...
Repeatable Annotations
• In Java SE 8, annotations can now be repeated• A lot of applicability in Java EE
• @DataSourceDefinition• @NamedQuery• @JMSDestinationDefinition• @JMSConnectionFactoryDefinition• @MailSessionDefinition• @Schedule
• Few cases have been addressed, many remain
Copyright © 2015 CapTech Ventures, Inc. All rights reserved.
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 { ...
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.
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.
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 reasonFuture<History> f4 = executor.submit(() -> getHealthHistory(p));Future<Health> f5 = executor.submit( () -> calculateHeathScore(f4.get()));
// Unrelated paths join belowFuture<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
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));
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.
@Asynchronous + CompletableFuture
Copyright © 2015 CapTech Ventures, Inc. All rights reserved.
@Asynchronouspublic Future<Confirmation> processPayment(Order order) { ... Confirmation status = ...; return new AsyncResult(status);
}
@Asynchronouspublic CompletableFuture<Confirmation> processPayment( Order order) { ... Confirmation status = ...; return CompletableFuture<Confirmation>.completedFuture(status);}
Java EE Guardians
http://javaee-guardians.io@javaee_guardian
Copyright © 2015 CapTech Ventures, Inc. All rights reserved.
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 need to be met in Java EE 8
Copyright © 2015 CapTech Ventures, Inc. All rights reserved.
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.
Copyright © 2015 CapTech Ventures, Inc. All rights reserved.