Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Guida galattica per JEE6
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
Profiles
Java EE 6
Ease of
Development
Web Services
Robust
Scalable
Enterprise
Application
Java EE 5
Pruning
Embeddable
Container
JAX-RS
Bean Validation
J2EE 1.4
J2EE 1.3
J2EE 1.2
Project JPE
Maggio 1998
Servlet
JSP
EJB
JMS
RMI/IIOP
EJB CMP
JCA
Web Services
Management
Deployment
Servlet
Annotation
Injection
JPA
WS-*
JSF
Web Profile
Dicembre 1999
Settembre 2001
Novembre 2003
Maggio 2006
EoF 2009
10 spec.
13 spec.
20 spec.
23 spec.
28 spec.
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
Extensibility
This mechanism provides a way to include additional technologies and
frameworks that are not part of the standard platform.
Profiles
For building small- to medium-sized enterprise applications, the entire stack
of Java EE APIs may be overkill. Like in Java ME, where profiles are
applied to specific device .
Pruning
Technologies that are outdated and have been replaced by new.
Technologies that are not well supported.
Technologies that are not widely deployed.
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
Web Profile
JSR
Version
Java Platform Enterprise Edition
316
6
Managed Beans
316
1.0
Java API RESTful Web Services
311
1.1
Servlet
315
3.0
x
Java Server Faces
314
2.0
x
Java Context & Dependency Injection
299
1.0
x
Bean Validation
303
1.0
x
Enteprise Java Bean
318
3.1
3.1lite
Java Persistence API
317
2.0
2.0
Java EE Connector Architecture
322
1.6
Java API for XML-Based Web Services
224
2.2
x
And many more........
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
Dependency injection
●
What's Dependency injection?
●
Mechanism to resolve Class dependencies
●
Aims at a major flexibility through loose coupling to
the dependence types
●
Already in place in Java environment through the JSR
330 specification (with annotations @Inject,
@Qualifier,@Named and @ScopeType)
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
Context and dependency injection
In the following examples you see a Pojo that retrieves
dependencies (a list of username/passwords) the “usual”
way (by depenedency look up) being injected to a
window to handle login logic
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
An example a pojo
@Singleton
public class FileLogin implements Login
{
private static Properties properties = null;
static
{
properties = new Properties();
try
{
properties.load(FileLogin.class.getResourceAsStream("/login.properties"));
}
catch (IOException e)
{
e.printStackTrace();
}
}
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
A client using the pojo
public class LoginPanel extends JPanel
{
private static final long serialVersionUID = 1234567890L;
@Inject @FileLoginBinding Login loginManager;
private JLabel myUserName;
private JLabel myPassword;
private JTextField myUserName;
private JPasswordField myPassword;
private JButton btnLogin;
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
Client code exam
By means of the JSR-330 annotations we define Injection
point lists by using the keyword @Inject that let specify
constructor, fields, or method inside a class. The injected
instance is always a type and its definition is always
checked by the compiler
• Not string-based (as in an xml file)!
• Extensible!
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
Multiple qualifiers and qualifiers with arguments
●
I want to make sure that the appropriate Bean is
being injected
●
Define a qualifier
FileLoginBinding
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target(
{
ElementType.FIELD,
ElementType.METHOD, ElementType.TYPE,
ElementType.PARAMETER })
public @interface FileLoginBinding
{
}
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
How Qualifier works
●
The specific type of the qualifier enforeces the
correct injection
LoginWindow
@Inject @FileLoginBinding Login
loginManager;
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
Qualifiers are meta-annotations
Define your own annotation types and annotate them with @Qualifier
• E.g.
@Qualifier
@Retention(RUNTIME)
@Target({FIELD,TYPE})
public @interface FileLoginBinding { }
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
So far the annotation mechanism
●
Where CDI fits in the whole mechanism
CDI defines an annotation to identify a
“bean” whose lifecycle is managed by the
container.You can consider this as an
implicit dependency of the container
•EJB beans are already managed
•POJO are now with @ManagedBean
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
ManagedBean
@Reliable
@SecuredBy(LDAP_MODULE)
@ManagedBean
public class ReliableLogin
implements LoginProcessor {
@Override
public boolean login(String username,char[] password)
throws LoginException {
...
}
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
A stateless bean is already managed
@Reliable
@SecuredBy(LDAP_MODULE)
@Stateless
public class ReliableLogin
implements LoginProcessor {
@Override
public boolean login(String username,char[] password)
throws LoginException {
...
}
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
Beans can be declared in a
scope
The CDI runtime will make sure the right bean is created
at the right time
• Extends the @Singleton annotation from the JSR-330
with more annotations
• Introduces @Dependent pseudo-scope as default to set
the context of dependency to the caller's lifecycle
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
Managed Bean can be scoped
@Reliable
@SecuredBy(LDAP_MODULE)
@RequestScoped
@ManagedBean
public class ReliableLogin
implements LoginProcessor {
@Override
public boolean login(String username,char[] password)
throws LoginException {
...
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
Built in Scopes
You can use the
• @ApplicationScoped
Everywhere in a JEE application
In a web app: @SessionScoped ,@RequestScoped
With JSF:
• @ConversationScoped
• Pseudo-scope: @Dependent
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
Benefits of a ManagedBean
Annotation-based event model
• A bean @Observes an event
void onLogin(@Observes
LoginEvent event) { … }
• Another bean fires an event
using the Event.fire(T event)
method
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
OTHER CDI benefits
Producer methods and fields
• Alternatives
• Interceptors
• Decorators
• Stereotypes
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
Known CDI Containers
1Weld, the JBoss reference implementation for JSR 299:
http://seamframework.org/Weld.
2. CanDI, the JSR 299 implementation for Caucho Resin,
http://caucho.com/projects/candi/.
3 OpenWebBeans, Apache implementation of JSR 299,
http://apache.org/openwebbeans/.
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
Version 3.0 of the Servlet API
●
web-fragment.xml
Web framework pluggability
–
Web Fragments
●
–
Frameworks such Struts and JavaServer Faces
can have their own piece of information added
in the JAR file
Dinamic Registration
TestServletContextListener.java
public void contextInitialized(ServletContextEvent sce) {
<web-fragment version="3.0">
<name>A</name>
<filter>
<icon/>
<filter-name>testFilter</filter-name>
<filter-class>it.javac.TestFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>testFilter</filter-name>
<url-pattern>/</url-pattern>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
</web-fragment>
ServletContext sc = sce.getServletContext();
ServletRegistration sr = sc.addServlet("DynaServlet","it.javac.TestServlet");
sr.setInitParameter("servletInitName", "servletInitValue");
sr.addMapping("/*");
FilterRegistration fr = sc.addFilter("DynaFilter","it.javac.TestFilter");
sc.addListener("it.javac.TestRequestListener");
.....
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
Version 3.0 of the Servlet API
●
Web framework pluggability
●
Improve support for annotations and generics (optional web.xml)
@WebServlet(name="testServlet", urlPatterns={"/"},
initParams={ @WebInitParam(name="simpleParam", value="paramValue") } )
public class TestServlet extends HttpServlet { ............
SimpleServlet.java
SimpleFilter.java
@WebFilter(urlPatterns={"/"},
initParams={ @WebInitParam(name="simpleParam", value="paramValue") })
public class TestFilter implements Filter {............
SimpleListener.java
@javax.servlet.annotation.WebListener
public class TestServletContextListener implements ServletContextListener {............
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
Version 3.0 of the Servlet API
●
Web framework pluggability
●
Improve annotations and generics (web.xml)
●
Asynchronous support (Comet) non-blocking Input/Output
AsyncServlet.java
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
final AsyncContext ac = req.startAsync();
ac.setTimeout(10 * 60 * 1000);
ac.addListener(new AsyncListener() {
public void onComplete(AsyncEvent event) throws IOException {
queue.remove(ac);
}
public void onTimeout(AsyncEvent event) throws IOException {
queue.remove(ac);
}
.....................
});
queue.add(ac);
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
Version 3.0 of the Servlet API
●
Web framework pluggability
●
Improve annotations and generics (web.xml)
●
Asynchronous support (Comet) non-blocking Input/Output
●
Security capabilities login/logout servlet self-registration
SampleLoginServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userName = request.getParameter("txtUserName");
String password = request.getParameter("txtPassword");
try {
request.login(userName, password);
// request.authenticate(response)
// request.logout();
.....
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
Enterprise JavaBeans 3.1
●
Optional local business interface
–
developers can write session beans
without business interfaces
●
War Packaging
●
EJB Lite profile
–
●
provides vendors the option to
implement a subset of the EJB APIs
within their products
SimpleStatelessSessionBean.java
@Stateless
public class SimpleStatelessSessionBean implements
StatelessSession {
@Schedule(second="*/3", minute="*/15", hour="*", ,
dayOfMonth="", dayOfWeek="Mon-Fri", month="",
timezone="", year="2009,2010", info="Test Automatic
Timer")
public void callback_timer(Timer t) {
t.getSchedule();
t.getInfo();
......
Automatic Timer Creation
–
timer service uses calendar-based
syntax
–
calendar syntax is used also for
programmatic timer creation using
the ScheduleExpression
Every other hour within the day starting at noon
on the second Tuesday of every month
hour="12/2", dayOfMonth="2nd Tue"
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
Enterprise JavaBeans 3.1
●
Optional local business interface
●
War Packaging
●
EJB Lite profile
●
Automatic Timer Creation
●
Singleton
–
Singleton beans are transactional and thread safe by default
SimpleSingletonEJB.java
@Singleton
public class SimpleSingletonEJB implements SimpleSingletonEJBLocal {
private static int x=0;
public int getUniqueCounter() {
x++;
return x;
}
.....
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
Enterprise JavaBeans 3.1
@Stateless
@Asynchronous
public class AsyncTestEJB {
●
Optional local business interface
●
War Packaging
●
EJB Lite profile
●
Automatic Timer Creation
●
Singleton
●
Asynchronous Session Bean
–
Bean methods annotated with
@Asynchronous are invoked
asynchronously
–
Future objects allow you to obtain a
return value from a method executed
in a separate thread.
private Future<Integer> sendOrderToWorkflow(Order order)
{
Integer status = 0;
if (ctx.wasCancelCalled()) {
return new AsyncResult<Integer>(2);
....;
AsyncTestEJB.java
SimpleEjbAsyncClient.java
Future<Integer> status =
orderEJB.sendOrderToWorkflow (order);
Integer statusValue = status.get();
....;
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
Enterprise JavaBeans 3.1
●
Optional local business interface
●
War Packaging
●
EJB Lite profile
●
Automatic Timer Creation
●
Singleton
●
Asynchronous Session Bean
●
EJB Embedded Container
public static void main(String args[]) {
try {
Map<String, Object> p = new HashMap<String, Object>();
p.put(EJBContainer.APP_NAME, "sample");
EJBContainer c = EJBContainer.createEJBContainer(p);
Context ic = c.getContext();
SimpleEjb ejb = (SimpleEjb)
ic.lookup("java:global/sample/SimpleEjb");
ejb.insert(5);
int res = ejb.verify();
c.close();
System.out.println("finished embedded test");
} catch (Exception e) {
.....
MainTestClass.java
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
Java Persistence API: Version 2.0
●
Expanding the object/relational mapping
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
–
@OrderColumn (Maintaining a persistent
ordering)
private String title;
–
Map with key and value:
@ElementCollection(fetch = FetchType.LAZY)
–
●
Basic Type
●
Entities
●
Embeddables
@CollectionTable(name = "Tag")
@Column(name = "Value")
private ArrayList<String> tags;
Entity: Book.java
Collection of basic type and embeddable javax.persistence.Cache implemented by Persistence Providers
objects can now be mapped in separate tables
●
Pessimistic locking
●
Support Caching
public interface Cache {
// Whether the cache contains data for the given entity.
public boolean contains(Class cls, Object primaryKey);
// Remove the data for the given entity from the cache.
public void evict(Class cls, Object primaryKey);
// Remove the data for entities of the specified class from the cache.
public void evict(Class cls);
// Clear the
cache.
Davide.DelVecchio@it.ibm.com
Nino.Guarnacci@oracle.com
public void evictAll();
Javaday IV – Roma – 30 gennaio 2010
JavaServer Faces 2.0
●
Annotations support against faces XML config
●
Automatic generation of JSP tag handlers
●
Additional scope “View” e “Component”
●
Improve AJAX support
–
changing the request processing life cycle and allowing partial updates of views
@ManagedBean
@RequestScoped
public class BookController {
@EJB
private BookEJB book;
@Inject
Private MyPojo myPojo;
public String doNew() {
return "newBook.xhtml";
BookController.java
FormJSF.xhtml
<tr>
<td>
<h:outputLabel value="Price : "/>
</td>
<td>
<h:inputText
value="#{bookController.myPojo.price}"/>
</td>
...
<h:commandButton value="Create a book"
action="#{bookController.doNew}"/>
</h:form>
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
JEE Specifications Benefits
●
Enterprise Systems diversification
●
Facilitate Cloud Computing Infra:
SaaS
– PaaS
Improve Time to Prod.
–
●
–
–
Raw Application-Generation
Available Skills
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
JAX-RS 1.1: JEE RESTful Services
<?xml version="1.0" encoding="UTF-8"?>
<application
xmlns:xsi="https://wadl.dev.java.net/wadl20061109.xsd">
@GET
<grammars/>
@Path(value = "person/view/
<resources{pid}")
public String getPersonByPath(@PathParam(value
= "pid") String
base="http://localhost:32989/TestRest/resources/res">
pid) {
<resource path="person">
return "Hello " + pid;
<param name="pid" type="xsd:string" style="query"
default=""
}
@Path("res") fixed=""/>
<method id="view" name="GET">
@Produces("application/json")
<request/>
@GET
@Singleton
<response>
@Path(value = "person/view")
public class SimpleRestService
{ mediaType="application/xml"/
<representation
public String getPersonByQuery(@QueryParam(value
= "pid") String
>
pid) {
@Context
</response>
return "Hello " + pid;
private UriInfo</method>
context;
}
</resource>
TestRest.WADL
</resources>
public SimpleRestService()
{}
@POST
</application>
●
Owned Definition Language “WADL”
●
POJOs or EJB that have at least one
method annotated with
@javax.ws.rs.Path
●
Native support for:
●
–
text/html text/plain
–
image/gif image/jpg image/png
–
text/xml application/xml
–
application/json
Annotation supports:
–
Header Values
–
Query & Form Params
–
Path Params
@Consumes("application/x-www-form-urlencoded")
@GET
@Path(value = "person/form")
@Path(value="person/view")
public String getPersonByPost(@FormParam("pid") String pid) {
("application/xml")
return@Produces
"Hello " + pid;
public String getPerson(){
}
..........
SimpleRestService.java
@GET
@Path(value = "person/view")
public String getPersonByHeaders(@Context HttpHeaders hh) {
MultivaluedMap<String, String> headerParams =
Davide.DelVecchio@it.ibm.com
Nino.Guarnacci@oracle.com
hh.getRequestHeaders();
Map<String, Cookie> pathParams
= hh.getCookies();
Javaday
IV – Roma – 30 gennaio 2010
......
JAX-RS 1.1: JEE RESTful Services
●
Fully integrated “J”CDI & JAXB
●
Mashup Enabler
●
@Inject
SimplePojo mySimplePojo;
@GET
@Path("image")
@Produces("image/*")
public Response getImage(@QueryParam("image") String image)
@ Fully HTTP Method Supports:
–
POST=NEW
–
GET=FIND
–
PUT=UPDATE
–
DELETE=REMOVE
–
OPTIONS=RFI
–
TRACE=ECHO
–
HEAD=CHECK VALID GET
{
File f = new File(image);
String mt = new MimetypesFileTypeMap().getContentType(f);
return Response.ok(f, mt).build();
}
SimpleImageRestService.java
http://localhost:32989/TestRest/resources/res/image?image=/speaker.jpg
Connection Server INFO
Application and Rest Service Name
Simple REST Url
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010
www.JavaPortal.it
Thanks
Davide.DelVecchio@it.ibm.com Nino.Guarnacci@oracle.com
Javaday IV – Roma – 30 gennaio 2010