JavaOne 2016
This session provides 50 best practices for Java EE 7, with examples. The best practices covered focus primarily on JPA, CDI, JAX-WS, and JAX-RS. In addition, topics involving testing and deployment are covered. This presentation points out where best practices have changed, common misconceptions, and antipatterns that should be avoided. This is a fast-paced presentation with many code samples.
1. TOP 50 JAVA EE 7 BEST
PRACTICES
Ryan Cuprak
Michael Remijan
2. About Us
Ryan
⢠@ctjava
⢠rcuprak@gmail.com
⢠http://www.cuprak.info
⢠https://www.linkedin.com/in/rcuprak
Michael
⢠@mjremijan
⢠mjremijan@yahoo.com
⢠http://mjremijan.blogspot.com
⢠http://linkedin.com/in/mjremijan
3. EJB 3 In Action 2nd Edition
Updated For
⢠EE 7
⢠EJB 3.2
4. Java EE 7
Concurrency
Utilities
Batch
Applications
Java
API for
JSON
Java API for
WebSocket
JSF 2.2
JSX-WS
2.2
JAX-RS
2
EL 3
Servlet 3.1
Common
Annotations 1.2
Interceptors 1.2 CDI 1.1
Managed Beans 1.0 EJB 3.2
Connector
1.7
JPA 2.1 JTA 1.2 JMS 2
JSP 2.3
JAXB
5. #1 JAX-RS: API Versioning
Version your JAX-RS with one of two approaches:
1. URL
http://ctjava.org/v2/meetings
http://ctjava.org/v1/meetngs
2. Media Content or Header Param
curl -H "Content-Type:application/srv-v4+jsonâ âŚ
Return HTTP Status Codes for services moved/changed:
⢠301 Moved Permanently
⢠302 Found
6. #1 JAX-RS: API Versioning (ContinuedâŚ)
Approach 1: URL
Approach 2: Media Types
7. #1 JAX-RS: API Versioning (ContinuedâŚ)
Service Moved Permanently
8. #2 JAX-RS: Error Handling
Provide ExceptionMappers to handle and process errors.
9. #2 JAX-RS: Error Handling (ContinuedâŚ)
HTML content is hardly a friendly response for an API!
27. #14 JPA: hashcode() & equals()
The equals and hashcode are required for:
⢠Entity is added to a collection
⢠When re-attaching entities to a new persistence context.
Important points:
⢠Do not use generated identifiers
⢠Use business key equality
32. #17 JPA: Mapping Inheritance
⢠Inheritance can have a big impact upon performance.
⢠Three approaches:
⢠Single table
⢠Joined-tables
⢠Table-per-class
⢠Denormalize for better performance
33. #18 JPA L2 Cache
JPA 2 introduced the L2 Cache, use this cache for:
⢠Entities that are frequently read
⢠Entities that are modified infrequently
⢠Not critical if stale
⢠L2 cache can consume large amounts of memory
⢠ALL
⢠NONE
⢠ENABLE_SELECTIVE
⢠DISABLE_SELECTIVE
Are you using a default setting?
34. #18 JPA L2 Cache (ContinuedâŚ)
Mark entity for L2 cache
Bypass L2 cache
35. #19 JPA: Persisting ENUM
⢠ENUM is a good case of converting data types
⢠Use a @Converter
36. #19 JPA: Persisting ENUM (ContinuedâŚ)
⢠@Converter
⢠AttributeConverter<X,Y>
⢠X is my application, Y is the database
37. #20 EJB: Transaction Handling
⢠EJBs exist to handle transactions. Keep them at the right layer
⢠Donât ignore transactions. Default: REQUIRED
⢠JAX-RS endpoints, database reads & performance
38. #21 EJB: Stateless Thread Safety
⢠Stateless beans are a pooled, managed resource
⢠Pools configurable by the application server
39. #22 EJB: Asynchronous
⢠@Asynchronous runs in container-managed thread
⢠Return Future<> to get results later
⢠Ideal for wrapping JAX-RS calls
⢠Good way to avoid any of your own threading
40. #23 EJB: Security
⢠Use declarative security and let the container handle it
⢠Avoid programmatic security
⢠EE servers trust principal/roles passed between
containers.
41. #23 EJB: Security (ContinuedâŚ)
⢠EE Configuration
⢠web.xml
⢠@DeclaredRoles
⢠@RolesAllowed
⢠Custom Configuration
⢠EE Server Realm
⢠glassfish-web.xml
42. #24 EJB: Avoid Lengthy Initialization
Donât abuse startup â @PostConconstruct delays
You delay initialization of the container!
44. #25 CDI: Observers
⢠In-memory event processing
⢠Very âreactiveâ
⢠Decouple work to be done, avoids unnecessary
dependencies
⢠Create an event to fire
45. #25 CDI: Observers (ContinuedâŚ)
⢠Fire the event
⢠Observers process the event
46. #26 CDI: Producer + Cache
⢠Use a producer to customize creation of an object
⢠Producer method is always called, so cache the instance
47. #27 CDI: Interceptors
⢠Limit to cross-cutting concerns
⢠Do not use to change business logic
⢠Create an annotation
52. #29 CDI: Transactions
Java EE introduced @Transactional for non-EJBs.
Pro: Easier to utilize transactions outside of EJB.
Con: Mixes layers â transactions & rest etc.
53. #30 CDI: Bean Discovery
⢠Java EE 7 CDI is enabled by default.
⢠beans.xml is no longer required as in EE 6
⢠Bean discovery mode:
⢠Annotated â only annotated classes
⢠All â includes beans that are not annotated
⢠None â CDI disabled
⢠Default mode is âannotatedâ
54. #31 Batch: Java EE not SE
⢠Think Java EE for batch, not SE
⢠Batch API
⢠Cron like schedule on EJB methods
⢠META-INF/batch-jobs/processInvoices.xml
55. #32: Batch Best Practices
⢠Package/deploy batch jobs separately
⢠Implement logic to cleanup old jobs
⢠Implement logic for auto-restart
⢠Test restart and checkpoint logic
⢠Configure database to store jobs
⢠Configure thread pool for batch jobs
⢠Only invoke batch jobs from logic that is secured (@Role
etc.)
56. #33 JAXB Primitive Data Types
anySimpleType
decimal
integer
long
int
short
byte
float double
nonPositiveInteger
negativeInteger
nonNegativeInteger
unsigneLong positiveInteger
unsignedInt
unsignedInt
unsignedByte
57. #34 JAXB: Date & Time Representation
⢠Use XMLGregorianCalendar for dates
⢠Avoid java.util.Date and java.util.Calendar
⢠XMLGregorianCalendar
⢠Handles long fractions of seconds â important to .NET
interoperability
59. #36 JAX-WS: RPC vs. Document
⢠Four different possibilities:
⢠RPC/Literal
⢠RPC/Encoded
⢠Document/Literal
⢠Document/Encoded
⢠Encoded is not supported by WS-I
⢠Default and most commonly used is Document/Literal
⢠Use Document/Literal
⢠RPC/Literal:
⢠Limited to basic XSD types
⢠WSDL will not include types section to constrain parameters
60. #37 JAX-WS: JAXB Gotcha
⢠JAXB will serialize an entire object graph.
Oops!
Use either:
⢠DTO â Data Transfer Object
⢠@XmlTransient
61. #38 JAX-WS Interoperable Services
⢠Design service starting with the WSDL
⢠Create data types using XSD
⢠Keep data types SIMPLE
⢠Avoid xsd:anyType
⢠Avoid sending Null values
⢠Use byte[] instead of String when character encoding is
unknown
62. #39 SOAP Faults
⢠Types of SOAP faults:
⢠Modeled â exception explicitly thrown by business logic.
⢠Mapped to wsdl:fault in WSDL file
⢠Unmodeled â RuntimeException, represented as generic
SOAPFaultException
63. #40 JAX-WS Input/Output Processing
Use SOAP message handlers to pre/post process
messages and handle SOAP faults.
66. #42 JAX-WS Large Files
Use W3C Message Transmission Optimization Mechanism
(MTOM) to handle large files.
67. #43 Deployment Classpath
⢠Are you pulling in third-party JAR files?
⢠Do these JAR files include Java EE annotated classes?
⢠Are you accidently deploying web services, MDBs etc.?
⢠Are you including container dependencies?
BAD!
70. #45 Distributed Caches
⢠Donât treat @Singleton as a âglobalâ singleton!
⢠Use JCache implementation (ex. HazelCast)
Java EE Server #1
app.war
SingletonBean
Java EE Server #2
app.war
SingletonBean
71. #46 Testing: Load
Load testing always at 100%?
Scenario:
⢠Message Driven Bean with a connection to a remote
resource.
⢠Standing pool size: 3
Oops!
72. #46 Testing Load (ContinuedâŚ)
Oops, resource only leak as bean instances fluctuate!
0
5
10
15
20
25
30
35
1 2 3 4 5 6 7 8 9
Leak
Bean
Returning to standing pool size leaks resources.
74. #48 Java EE Tutorial Table of Contents
⢠Whatâs in Java EE?
⢠918 pages
⢠TOC is a great summary
⢠30+ pages
⢠Highlights just how much is
in EE
75. #49 There are no âsmallâ applications
⢠Donât fall into these traps:
⢠âItâs just a simple applicationâ
⢠âIt only needs to doâŚâ
⢠âCode it up real quickâŚâ
⢠EE Specification exists for a reason
⢠Multiple users
⢠Concurrency
⢠Multi-threading
⢠Transaction management
⢠External resources
⢠Messaging
76. #50 Start with an EE Server
⢠Because there are no âsmallâ applications
⢠Start with an EE Server
Avoid filling yourWAR with
âEE Featuresâ
because you are not using an EE server
⢠But Servers are âheavy-weightâ?
⢠Payara
⢠WildFly
⢠TomEE
⢠Benefits
⢠âLight-weightâ
⢠Regular updates
⢠Great online community support