java se 8 for java ee developers

35
Others Talk, We Listen. Java SE 8 for Java EE Developers Reza Rahman Senior Architect [email protected] @reza_rahman

Upload: reza-rahman

Post on 11-Jan-2017

12.951 views

Category:

Technology


1 download

TRANSCRIPT

Page 1: Java SE 8 for Java EE Developers

Others Talk, We Listen.

Java SE 8 for Java EE DevelopersReza RahmanSenior [email protected]@reza_rahman

Page 2: Java SE 8 for Java EE Developers

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.

Page 3: Java SE 8 for Java EE Developers

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.

Page 4: Java SE 8 for Java EE Developers

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.

Page 5: Java SE 8 for Java EE Developers

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; } }

Page 6: Java SE 8 for Java EE Developers

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();

Page 7: Java SE 8 for Java EE Developers

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();

Page 8: Java SE 8 for Java EE Developers

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(); }); }}

Page 9: Java SE 8 for Java EE Developers

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.

Page 10: Java SE 8 for Java EE Developers

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

Page 11: Java SE 8 for Java EE Developers

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(...

Page 12: Java SE 8 for Java EE Developers

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() ) );

Page 13: Java SE 8 for Java EE Developers

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.

Page 14: Java SE 8 for Java EE Developers

Date/Time API

Copyright © 2015 CapTech Ventures, Inc. All rights reserved.

Key Artifacts

• LocalTime• LocalDate• LocalDateTime• ZonedDateTime

• Instant• Duration• Period

Page 15: Java SE 8 for Java EE Developers

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.

Page 16: Java SE 8 for Java EE Developers

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.

Page 17: Java SE 8 for Java EE Developers

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.

Page 18: Java SE 8 for Java EE Developers

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;}

Page 19: Java SE 8 for Java EE Developers

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(); }}

Page 20: Java SE 8 for Java EE Developers

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.

Page 21: Java SE 8 for Java EE Developers

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); } ...

Page 22: Java SE 8 for Java EE Developers

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); }}

Page 23: Java SE 8 for Java EE Developers

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; ...

Page 24: Java SE 8 for Java EE Developers

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.

Page 25: Java SE 8 for Java EE Developers

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 { ...

Page 26: Java SE 8 for Java EE Developers

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.

Page 27: Java SE 8 for Java EE Developers

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.

Page 28: Java SE 8 for Java EE Developers

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

Page 29: Java SE 8 for Java EE Developers

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));

Page 30: Java SE 8 for Java EE Developers

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.

Page 31: Java SE 8 for Java EE Developers

@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);}

Page 32: Java SE 8 for Java EE Developers

Java EE Guardians

http://javaee-guardians.io@javaee_guardian

Copyright © 2015 CapTech Ventures, Inc. All rights reserved.

Page 33: Java SE 8 for Java EE Developers

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.

Page 34: Java SE 8 for Java EE Developers

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.

Page 35: Java SE 8 for Java EE Developers

Copyright © 2015 CapTech Ventures, Inc. All rights reserved.