0% found this document useful (0 votes)
5 views32 pages

Javase8 Javaee

Java SE 8 introduces significant enhancements, including support for functional programming with lambdas, a new Date/Time API, and improved asynchronous processing with CompletableFuture. Most Java EE 7 runtimes are compatible with Java SE 8, and further improvements are expected in Java EE 8. The document also highlights practical applications of these features and provides resources for further learning.

Uploaded by

vickysonofraja
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views32 pages

Javase8 Javaee

Java SE 8 introduces significant enhancements, including support for functional programming with lambdas, a new Date/Time API, and improved asynchronous processing with CompletableFuture. Most Java EE 7 runtimes are compatible with Java SE 8, and further improvements are expected in Java EE 8. The document also highlights practical applications of these features and provides resources for further learning.

Uploaded by

vickysonofraja
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java SE 8 for Java

EE Developers
Reza Rahman
Senior Architect
rrahman@[Link]
@reza_rahman

Others Talk,
We Listen.
CapTech

Full-service US national IT consulting firm that focuses on client best interests,


trust, servant leadership, culture, professionalism and technical excellence.

#1 in Meeting Client’s Needs Ranked for the #28 in Vault's Consulting Top 50
#7 Best Firm to Work For 7th Consecutive Year #3 Best Consulting Internship
#1 in Career Development #9 Best Overall Internship

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
• Further alignment being done in Java EE 8 and beyond

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


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.


Lambdas
The Problem

List<Student> students = ...


double highestScore = 0.0;
for (Student s : students) {
if ([Link] == 2011) {
if ([Link] > highestScore) {
highestScore = [Link];
}
}

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


Lambdas
An Inelegant Solution

List<Student> students = ...


double highestScore = students.
filter(new Predicate<Student>() {
public boolean op(Student s) {
return [Link]() == 2011;
}
}).
map(new Mapper<Student,Double>() {
public Double extract(Student s) {
return [Link]();
}
}).
max();

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


Lambdas
The Elegant Solution

SomeList<Student> students = ...


double highestScore = students.
filter(Student s -> [Link]() == 2011).
map(Student s -> [Link]()).
max();

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


Asynchronous Servlet and Lambdas

@WebServlet(urlPatterns={"/report"}, asyncSupported=true)
public class AsyncServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) {
...
final AsyncContext asyncContext = [Link]();
[Link](() -> {
ReportParameters parameters =
parseReportParameters([Link]());
Report report = generateReport(parameters);
printReport(report, asyncContext);
[Link]();
});
}
}

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


Streams

• Applying lambdas to the Collections API


• Bulk operations
• Sequence (“stream”) of data

Source
int sum = [Link]().
filter(t -> [Link]().getCity().equals(“Philly”)).
mapToInt(Transaction::getPrice).
sum();
Intermediate operation

Terminal operation

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


JSON-P Stream

[
{
"name":"Duke",
"gender":"male",
"phones":[
"home":"650‐123-‐4567",
"mobile":"650-‐111-‐2222"
]
},
{
"name":"Jane", ...
]

JsonArray contacts =
[Link]()
.add(...

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


JSON-P Stream

Map<String, Long> names =


[Link]([Link]).stream()
.filter(x -> "female".equals([Link]("gender")))
.map(x -> ([Link]("name")))
.collect(
[Link](
[Link](),
[Link]()
)
);

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


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
Key Artifacts

• LocalTime • Instant
• LocalDate • Duration
• LocalDateTime • Period
• ZonedDateTime

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


Date/Time API Examples

// Get the current date and time


LocalDateTime now = [Link]();

// Returns formatted date and time


// “2013-10-21T20:25:15:16.256”
[Link]();

// Add 5 hours
LocalDateTime later = [Link](5, HOURS);

// Subtract 2 days
LocalDateTime earlier = [Link](2, DAYS);

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
Using JPA Converters

@Entity
public class Accident {

@Convert(converter=[Link])
@Temporal([Link])
private Instant when;
}

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


Date/Time API with JPA
Using JPA Converters

@Converter
public class InstantConverter
implements AttributeConverter<Instant, Date> {

public Date convertToDatabaseColumn(Instant instant) {


return [Link](instant);
}

public Instant convertToEntityAttribute(Date date) {


return [Link]();
}
}

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


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.


Date/Time API with JSF
Using JSF Converters

@FacesConverter(“InstantConverter”)
public class InstantConverter implements Converter {

@Override
public Object getAsObject(FacesContext ctx, ...,
String value) {
return [Link](value);
}
...

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


Date/Time API with JSF
Using JSF Converters

...
@Override
public String getAsString(FacesContext ctx, ...,
Object value) {
DateTimeFormatter formatter = DateTimeFormatter
.ofLocalizedDateTime([Link])
.withLocale([Link])
.withZone([Link]());

return [Link]((TemporalAccessor) value);


}
}

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


Date/Time API with JSF
Using JSF Converters

<h:form>
<h:inputText id = “date”
value = “#{[Link]}”
size = “20” required=“true”
label = “when”
converter = “instantConverter” />
...

@Named @ViewScoped
public class RegisterAccident {
Instant when;
...

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


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.


Repeatable Annotations in Java EE

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

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


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 = [Link](() -> getAssets(p));
Future<Liabilities> f2 = [Link](
() -> getLiabilities(p));
Future<Credit> f3 = [Link](
() -> calculateCreditScore([Link](), [Link]()));

// The unrelated calls below are now blocked for no reason


Future<History> f4 = [Link](() -> getHealthHistory(p));
Future<Health> f5 = [Link](
() -> calculateHeathScore([Link]()));

// Unrelated paths join below


Future<Coverage> f6 = [Link](
() -> underwrite([Link](), [Link]()));

Callbacks don’t block, but introduce callback hell…


[Link]

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


CompletableFuture Basics

public CompletableFuture<Confirmation> processPayment(


Order order) {
CompletableFuture<Confirmation> future =
new CompletableFuture<>();
[Link](() -> {
Confirmation status = ...
[Link](status);
});
return future;
}

paymentService
.processPayment(order)
.thenAccept(
confirmation -> [Link](confirmation));

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


Functional Reactive to the Rescue?

CompletableFuture<Assets> getAssets =
[Link](() -> getAssets(person));
CompletableFuture<Liabilities> getLiabilities =
[Link](() -> getLiabilities(person));
CompletableFuture<Credit> calculateCreditScore =
[Link](getLiabilities,
(assets, liabilities) ->
calculateCreditScore(assets, liabilities));

CompletableFuture<Health> calculateHeathScore =
[Link](() -> getHealthHistory(person))
.thenApplyAsync(history -> calculateHeathScore(history));

Coverage coverage =
[Link](calculateHeathScore,
(credit, health) -> underwrite(credit, health)).join();

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


CompletableFuture with JAX-RS

CompletionStage<String> cs1 = [Link]("[Link]


.request()
.rx()
.get([Link]);

CompletionStage<String> cs2 = [Link]("[Link]


.request()
.rx()
.get([Link]);

// Get both responses in a List (when they are available)


CompletionStage<List<String>> listCompletionStage =
[Link](cs2, Arrays::asList);

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 are being met in Java EE 8 and beyond

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


Resources

• Java EE Tutorials

[Link]
• Java SE Tutorials

[Link]
• What's New in JDK 8

[Link]
[Link]
• Digging Deeper
• [Link]
• [Link]
• [Link]

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


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

You might also like