You are on page 1of 147

Clase 8 Ingeniería del Software

Definición del
3 4
Software 4/sept 11/sept
ITIL
14/ago Principios Métodos

Operación,
Soporte y COBIT DevOps
DevOps Qué es ? Diseño
Mantenimiento •Maven

27/nov
14 ISO Estrategias 6 Modelos 5
Ingeniería de 25/sept
Software 18/sept
Web

DevOps Cómo se valida ?


Paradigmas de
Programación 1 Plataformas
7
•Dockers Nube 21/Ago 9/oct
Instalación
•Kubernites
20/nov 11 Verificación
Procesos
genéricos
Procesos
específicos 2
•UP
21,28/
Escritorio 13 Móvil 6/nov •CMMI
•ISO
10
Producción
•Agiles
•DevOps ago
23/oct •GIT
Prueba •Jira
4/sept – Taller 1
2/oct – Taller 2
DevOps
•Selenium Tecnologías 8 •TFS

30/oct – Taller 3
Dr. Alfonso Miguel Reyes
Validación
12 16/oct
4/dic – Taller 4 13/nov
Tecnologías

Dr. Alfonso Miguel Reyes


Glassfish, JAVA EE, Servlets, JSP, EJB
Java platform
• A Java platform comprises the JVM together with supporting class
libraries.

Java 2 Standard Edition (J2SE)


• (1999) provides core libraries for data structures, xml parsing,
security, internationalization, db connectivity, RMI

Java 2 Platform, Enterprise Edition (J2EE)


• provides more class libraries for servlets, JSPs, Enterprise Java
Beans, advanced XML

Java Platform, Enterprise Edition (Java EE)


• When Java Platform 5.0 was released (2004) the ‘2’ was
dropped from these titles.
Java platform
• A Java platform comprises the JVM together with supporting
class libraries.

Java Micro Edition (Java ME)


• comprises the necessary core libraries and tools for writing
Java for embedded systems and other small footprint
platforms, along with some specialised libraries for specific
types of device such as mobile phones.
Java Web Application
A Java web application generates interactive web pages
containing various types of markup language (HTML, XML,
and so on) and dynamic content.

It is typically comprised of web components such as:

• JavaServer Pages (JSP)


• Servlets
• JavaBeans

to modify and temporarily store data, interact with


databases and web services, and render content in
response to client requests.
https://grizzly.dev.java.net/
Java EE (Enterprise Edition)
Java EE (Enterprise Edition) is a widely used platform
containing a set of coordinated technologies that
significantly reduce the cost and complexity of:

• developing
Java EE 6 is supported
• deploying and only by the GlassFish
• managing server v3.x.

multitier, server-centric applications.


Java EE builds upon the Java SE platform and provides a set
of APIs (application programming interfaces) for developing
and running portable, robust, scalable, reliable and secure
server-side applications.

http://netbeans.org/kb/trails/java-ee.html
Java EE 6 Platform
• The Java EE platform uses a simplified programming model. XML
deployment descriptors are optional. Instead, a developer can simply
enter the information as an annotation directly into a Java source file,
and the Java EE server will configure the component at deployment and
runtime
• With annotations, you put the specification information in your code
next to the program element affected.

http://download.oracle.com/javaee/6/tutorial/doc/bnaaw.html
Java EE application model
• an architecture for implementing services as
multitier applications that deliver the scalability,
accessibility, and manageability needed by enterprise-
level applications.
• With this structure you can more easily change one of
the tiers without compromising your entire
application.
• Business and presentation logic - to be implemented
by the developer
• Standard system services – to be provided by the Java
EE platform

http://download.oracle.com/javaee/6/tutorial/doc/bnaaw.html
Java Servlets
• Servlets are Java classes that dynamically process requests and
construct responses.
• Server side replacement for CGI
• Extensions to Java enabled web-servers
• Inherently multi-threaded.
• One thread per request.
• Very efficient.
• Platform independent.
How do Servlets work?
• Servlets run inside a Web Container - the component of the web server
that runs and interacts with Servlets
• Servlet is running on the server listening for requests
• When a request comes in, a new thread is generated by the web
container.
Java EE Containers
Java EE containers
• are the interface between a Java component
and the low-level platform-specific functionality
(i.e. transaction and state management,
multithreading, resource pooling, etc.) that
supports the component.
• provide for the separation of business logic from
resource and lifecycle management.
• this allows developers to focus on writing business logic
rather than writing enterprise infrastructure.
The Java EE platform uses "containers" to simplify development.
http://download.oracle.com/javaee/6/tutorial/doc/bnabo.html
http://www.oracle.com/technetwork/java/javaee/javaee-faq-jsp-135209.html#diff
Java EE Containers
When a request comes in:
• a Servlet needs to be instantiated and create a new thread to
handle the request.
• call the Servlet’s doPost()or doGet() method and pass the
HTTP request and HTTP response objects
• get the request and the response to the Servlet
• manage the life, death and resources of the Servlet
* All of the above are the tasks of the web container.
Java EE Containers

Java EE SERVER

From Bodoff et. al. 2005


Recall: (PHP-MySQL) Server: response

• Webserver supports HTTP.

Server

Web
server My codes
PHP
HTTP HTML MySQL
interpreter
Client
Operating System
Web
TCP/IP
browser
Operating
System

Internet
Historically (Java Web App)
Server: response
• Webserver supports HTTP.
Server
<html>
<head>

GET... GET...
</head>
<body>
...

Web server <body>


</html>

Web
Container Servlet
Application (Java code)
HTTP <html> (Java code)
Client <head>
</head>
<body>
...
<body> Operating System
</html>

Web
TCP/IP
browser
Operating
System
It’s the Container that gives
the Servlet the HTTP request
and response, and it’s the
Internet Container that calls the Servlet’s
methods (e.g. doPost() or doGet())
Historically (Java Web App)
Server: response
• Webserver supports HTTP.
Server
<html>
<head>

GET... GET...
</head>
<body>
...

Web server <body>


</html>

Servlet
HTTP (Java code)
<html>

Client <head>
</head>
<body>
...
<body> Operating System
</html>

Web
TCP/IP
browser
Operating
System
It’s the Container that gives
the Servlet the HTTP request
and response, and it’s the
Internet Container that calls the Servlet’s
methods (e.g. doPost() or doGet())
(Java Web App) Server: response
• Webserver supports HTTP.
Server
GET...
Grizzly is now the Web server + <html>
<head>
</head>

HTTP front end of Container <body>


...
<body>
</html>
the application
server
Servlet
(Java code)
HTTP
Client
Operating System
Web
TCP/IP
browser
Operating
System
It’s the Container that gives
the Servlet the HTTP request
and response, and it’s the
Internet Container that calls the Servlet’s
methods (e.g. doPost() or doGet())
Java Servlets
Java Servlets simplify web development by providing
infrastructure for component, communication, and session
management in a web container that is integrated with a web
server.
• Writing Servlets is like writing Java codes that place an HTML
page inside a Java class (this is the worst part of Servlets!)

• (Historically!) requires a deployment descriptor (DD). This is


in the form of an XML file.

• Servlets do not have a main() method.


• Servlets are under the control of another Java application
called a Container

http://www.oracle.com/technetwork/java/javaee/javaee-faq-jsp-135209.html#diff
JavaBeans
• manage the data flow between the following:

Client/Database Server
application client or applet components running on the
Java EE server

database Server components

• JavaBeans components are not considered Java EE components


by the Java EE specification.

• JavaBeans components have properties and have get and set


methods for accessing the properties.
Enterprise JavaBeans (EJB)
Enterprise JavaBeans container handles:
• distributed communication
• threading
• scaling
• transaction management, etc.

has a new packaging! (see figure)

New EJB 3.1 Packaging

Older EJB Packaging http://www.oracle.com/technetwork/java/deepdivejavaee6glassfishv3-jsp-138230.html


• create a simple web application using NetBeans IDE
• deploy it to a server, and
• view its presentation in a browser
NetBeans
• A 3rd party Java Integrated Development Environment (IDE)
Class libraries for Servlets,
• Comes with Java EE class libraries JSPs, Enterprise Java
• bundled with GlassFish Sever Open Source Beans, advanced XML
Edition
• Can deploy servlets, JSPs, and web services
A Quick Tour of the IDE (v.6.9)

JSP, Java Bean, User-defined Java Class & Package,


Get Method, User Interface
Sample Project

Index.jsp Main interface, Html with form


Invokes response.jsp through
form action.

NameHandler.java

Class NameHandler
containing user data

response.jsp Generates the server’s response


Defines a JavaBean to connect the class NameHandler to
the user’s input via a form text field (name).
Creating a new Web Application

New Project / Java Web


Creating a new Web Application

Specify Project Name


Creating a new Web Application

GlassFish Server

Web profile
Java Application Server: Glassfish

GlassFish
is an open source application server project led by Sun
Microsystems for the Java EE platform. The proprietary
version is called Oracle GlassFish Enterprise Server.
GlassFish is free software
Sun is the original creator
of Tomcat
It uses a derivative of Apache Tomcat as the servlet
container for serving Web content, with an added
component called Grizzly which uses Java NIO for scalability
and speed.
https://grizzly.dev.java.net/ http://java.dzone.com/articles/glassfish-and-tomcat-whats-the

Before the advent of the Java New I/O API (NIO), thread
management issues made it impossible for a server to
scale to thousands of users
Java Application Server: Glassfish
GlassFish is an open source (full) application server project led by Sun
Microsystems for the Java EE platform. The proprietary version is
called Oracle GlassFish Enterprise Server. GlassFish is free software.

It uses a derivative of Apache Tomcat as the servlet container for


serving Web content, with an added component called Grizzly which
uses Java NIO for scalability and speed.

On 25 March 2010, soon after the acquisition of


Sun Microsystems, Oracle issued a Roadmap for
versions 3.0.1, 3.1, 3.2 and 4.0 with themes
revolving around clustering, virtualization and
integration with Coherence and other Oracle
technologies.
http://en.wikipedia.org/wiki/GlassFish
Glassfish vs. Tomcat
Not a full-
application
server Sun is the original creator
of Tomcat

Historically, if you wanted to get good HTTP performance from


Tomcat you really needed to have an Apache web server to sit in
front of Tomcat which involved more setting up and extra
administrative work.

Since GlassFish v1 (May 2006), Grizzly is the HTTP frontend of


the application server.

It's a 100% Java NIO framework that provides the same


performance as Apache, only it's written in Java and integrated
straight into the application server.
http://java.dzone.com/articles/glassfish-and-tomcat-whats-the
Other Java web application-capable Servers

 Blazix from Desiderata Software (1.5 Megabytes, JSP, Servlets and


EJBs)
 TomCat from Apache (Approx 6 Megabytes)
 WebLogic from BEA Systems (Approx 40 Megabytes, JSP, Servlets and
EJBs)
 WebSphere from IBM (Approx 100 Megabytes, JSP, Servlets and EJBs)

http://www.jsptut.com/Getfamiliar.jsp
Commercial Deployment
Oracle provides software support only
• Oracle GlassFish Server for Oracle GlassFish Server, not for
GlassFish Server Open Source Edition
–delivers a flexible, lightweight and extensible Java EE 6
platform. It provides a small footprint, fully featured
Java EE application server that is completely supported
for commercial deployment and is available as a
standalone offering.
• Oracle WebLogic Server
–designed to run the broader portfolio of Oracle Fusion
Middleware and large-scale enterprise applications.
–industry's most comprehensive Java platform for
developing, deploying, and integrating enterprise
applications.

http://docs.sun.com/app/docs/doc/821-1751/gkbtb?l=en&a=view
Creating a new Web Application

JSP File
Creating a new Web Application

Sample Run
Project: HelloWeb
HelloWeb: Directories and Files
NameHandler.java
Java Package
Right-click Source Packages

http://en.wikipedia.org/wiki/GlassFish
Java Package
Add a Java Class, specify Package name

Java Package
• a mechanism for organizing Java classes into namespaces
• can be stored in compressed files called JAR files, allowing classes to
download faster as a group rather than one at a time.

http://en.wikipedia.org/wiki/GlassFish
Java Package
Add a Java Class

http://en.wikipedia.org/wiki/GlassFish
Java Package
Edit the Java Class

• Declare a String variable inside the


class declaration.
String name;

• Add a constructor to the class:


public NameHandler()

• Add the following line in the


NameHandler() constructor:
name = null;

http://en.wikipedia.org/wiki/GlassFish
Generating Getter and Setter Methods
Right-click name field in the Source editor

Selection: Name Field / Refactor / Encapsulate Fields


Generating Getter and Setter Methods

Notice that Fields' Visibility is by default set to private, and Accessors' Visibility to
public, indicating that the access modifier for class variable declaration will be
specified as private, whereas getter and setter methods will be generated with
public and private modifiers, respectively.
Generating Getter and Setter Methods

Select the Refactor button.


Results of Refactoring

Notice that the variable


declaration has changed.
• set to private

Get and set functions with


implementation have been
added as well.
• access modifier: public
Adding and Customising
a Form, input text field,
submit button
Inserting a Form
Invoke the palette: from the menu, select (Window/Palette): or press
Ctrl+Shift+8

expand HTML Forms


Inserting a Form

expand HTML Forms and drag a Form item to a point after the <h1> tags in
the Source Editor.

The Insert Form dialog box displays.


Specifying an action

Specify the following values:

Click OK.
Source Generated

An HTML form is automatically added to the index.jsp file.


Adding an Input Text Field

Drag a Text Input item to a point just before the </form> tag, then specify
the following values:

• Name: name
• Type: text
Source Generated

Input Text Field


Adding a Submit Button

Drag a Button item to a point just before the </form> tag. Specify the
following values:
• Label: OK
• Type: submit

Click OK. An HTML button is added between the <form> tags.


Adding some extra labels, tidying up your code

Type Enter your name: just before the first <input> tag, then change
the default Hello World! text between the <h1> tags to Entry Form.

Right-click within the Source Editor and choose Format


(Alt-Shift-F) to tidy the format of your code.
index.jsp: Source Generated

We would like to
pass this to our
server
response.jsp
Adding a JSP File
In the Projects window, right-click the HelloWeb project node and choose
New > JSP. The New JSP File wizard opens.

Name the file response, and click Finish.

Notice that a response.jsp file node displays in the Projects window beneath
index.jsp, and the new file opens in the Source Editor.
JSP Source File Generated: response.jsp
Adding a Use Bean item
In the Palette to the right of the Source Editor, expand JSP and drag a Use
Bean item to a point just below the <body> tag in the Source Editor.

The Insert Use Bean dialog opens.

Specify the values shown in the following figure.

The class NameHandler


belongs to the package
we have set earlier
JSP Source File Generated: response.jsp

Notice that the <jsp:useBean> tag is added beneath the <body> tag.
Adding a Set Bean property item
Drag a Set Bean Property item from the Palette to a point just before the
<h1> tag and click OK.

In the <jsp:setProperty> tag that appears, delete the empty value attribute
and edit as follows. Delete the value = "" attribute if the IDE created it!
Otherwise, it overwrites the value for name that you pass in index.jsp.
Adding a Set Bean property item
Drag a Set Bean Property item from the Palette to a point just before the
<h1> tag and click OK.

In the <jsp:setProperty> tag that appears, delete the empty value attribute
and edit as follows. Delete the value = "" attribute if the IDE created it!
Otherwise, it overwrites the value for name that you pass in index.jsp.
Adding a Get Bean property item
Drag a Get Bean Property item from the Palette and drop it after the comma
between the <h1> tags.
Specify the following values in the Insert Get Bean Property dialog:
• Bean Name: mybean
• Property Name: name

Insert a Get Bean Property


item here!
JSP Source Code Generated
the user input coming from index.jsp becomes a name/value pair that is
passed to the request object.
When you set a property using the <jsp:setProperty> tag, you can specify the
value according to the name of a property contained in the request object.

Therefore, by setting property to name, you can retrieve the value specified by
user input.
Sample Run

User input

Response from
the JSP file
Sample Run

Index.jsp Main interface, Html with form


Invokes response.jsp through
form action.

User input Response from


the JSP file

NameHandler.java Class NameHandler containing


user data, get and set methods

response.jsp Generates the server’s response


Defines a JavaBean to connect the class NameHandler to
the user’s input via a form text field (name).
Project

Index.jsp Main interface, Html with form


Invokes response.jsp through
form action.

NameHandler.java

Class NameHandler
containing user data, get
and set methods

http://java.sun.com/blueprints/code/projectconventions.html

response.jsp Generates the server’s response


Defines a JavaBean to connect the class NameHandler to
the user’s input via a form text field (name).
Packaging Web Applications

The Java EE specification defines how the web


application can be archived into a web application
archive (WAR)

• WAR files are


– Java archives with a .war extension
– Packaged using the same specification as zip files
– Understood by all Java EE compliant application
servers

• WAR files can be directly deployed in servlet


containers such as Tomcat
NetBeans WAR files

• To make a WAR for your NetBeans project, right click on


the project node and select Build Project.

• The WAR file will be placed in the “dist” sub-directory


of your project folder
Project
Java EE 6
http://download.oracle.com/javaee/6/tutorial/doc/

Recommended Directory Structure for Projects

http://java.sun.com/blueprints/code/projectconventions.html

NetBeans

http://netbeans.org/kb/docs/web/quickstart-webapps.html
http://www.oracle.com/technetwork/java/javaee/documentation/index.html
Simple Database Example
http://netbeans.org/kb/docs/web/mysql-webapp.html

E-Commerce Example

http://netbeans.org/kb/docs/javaee/ecommerce/design.html
http://netbeans.org/kb/docs/javaee/ecommerce/data-model.html#createERDiagram
http://dot.netbeans.org:8080/AffableBean/
Model-View-Controller Paradigm
V. Tecnologías
Java EE
V. Tecnologías Java EE
 Tecnologías Vista: JSF
 Estándar SUN: Existen muchas alternativas.
 Comunidad de desarrollo amplia.
 Apoyo tecnológico de las principales compañías.
 Adaptación de las mejores ideas de otros.
 Lentitud en asimilar nuevas tecnologías.
 Modificaciones o mejoras lentas.
 Dependencia de implementaciones de terceros.
V. Tecnologías Java EE
 Tecnologías Vista: JSF
 Componentes de JSF:
 API + Implementación de Referencia.
 Representan componentes UI y manejan su estado, eventos,
validaciones, navegación, etc…
 Librería de Etiquetas.
 Etiquetas personalizadas de JSP para dibujar los componentes UI dentro
de las páginas JSP.
V. Tecnologías Java EE
 Ciclo de Vida JSF
 Las peticiones Faces no se limitan a petición-respuesta,
disponen de un ciclo de vida.
 El ciclo de vida depende del tipo de petición.
 Respuesta No-Faces: Respuesta generada al margen de la fase de
renderizar respuesta de faces.
 Respuesta Faces: Respuesta generada en la fase de renderizar
respuesta de faces.
 Petición No-Faces: Petición enviada a un componente no faces.
 Petición Faces: Petición enviada desde una respuesta faces
previamente generada.
 El escenario normal Peticion faces/Respuesta faces.
V. Tecnologías Java EE
 Ciclo de Vida JSF
V. Tecnologías Java EE
 Ciclo de Vida JSF
 Reconstruir el árbol de componentes.
 Se construye el árbol de componentes faces.
 Aplicar valores a la petición.
 Se asocian a los componentes los nuevos valores desde los
parámetros de la petición.
 Procesar validaciones.
 Se procesan las validaciones para los componentes.
 Actualizar los valores del modelo.
 Una vez es válido se actualizan los valores del modelo.
 Invocar aplicación.
 En este punto se manejan los eventos a nivel de aplicación.
 Renderizar respuesta.
 Por último se dibujan los componentes del árbol.
V. Tecnologías Java EE
 Componentes JSF
 Conjunto de clases UIComponent.
 Representan los componentes.
 Modelo de renderizado.
 Forma de visualizar el componente.
 Modelo de eventos.
 Forma de manejar los eventos lanzados.
 Modelo de conversión.
 Conectar conversores de datos al componente.
 Modelo de validación.
 Forma de registrar validadores para el componente.
 Se emplean las etiquetas.
 RichFaces, ICEFaces: Librerías de etiquetas.
V. Tecnologías Java EE
 Componentes JSF
<h:dataTable id="noticias" value="#{Noticias.listadoCategoria}" var="noti">
<h:column>
<f:facet name="header"><h:outputText value="Titular"/></f:facet>
<h:outputText value="#{noti.titulo}" />
</h:column>
<h:column>
<f:facet name="header"><h:outputText value="Contenido"/></f:facet>
<h:outputText value="#{noti.contenido}" />
</h:column>
http://java.sun.com/javaee/javaserverfaces/reference/docs/
</h:dataTable>
---------------------------------------------------------------------------------------------------------------------------------------------------------------
http://java.sun.com/javaee/javaserverfaces/1.2/docs/tlddocs/
<h:form id=“NoticiaForm”>
<h:outputText value="Código:"/>
<h:inputText id="codigo" value="#{GestorNoticias.noticia.codigo}" required="true" /><br/>
http://java.sun.com/javaee/javaserverfaces/1.2_MR1/docs/api/index.html
<h:outputText value="Titulo:"/>
<h:inputText id="titulo" value="#{GestorNoticias.noticia.titulo}" required="true" /><br/>
<h:outputText value="Contenido:"/>
<h:inputText id="contenido" value="#{GestorNoticias.noticia.contenido}" required="true" /><br/>
<h:outputText value="Fecha:"/>
<h:inputText id="fecha" value="#{GestorNoticias.noticia.fecha}" required="true">
<f:convertDateTime pattern="dd/MM/yyyy"/>
</h:inputText><br/>
<h:outputText value="Portada:"/>
<h:selectBooleanCheckbox id="portada" value="#{GestorNoticias.noticia.portada}" required="true" /><br/>
<h:outputText value="Categoria:"/>
<h:selectOneMenu id="categoria" value="#{GestorNoticias.categoriaId}">
<f:selectItems value="#{GestorNoticias.selectCategorias}" />
</h:selectOneMenu><br/>
<h:commandButton value="Guardar" action="#{GestorNoticias.saveNoticia}" />
</h:form>
V. Tecnologías Java EE
 Faces-Config.xml
 Archivo de configuración principal.
 Describe los bean manejados.
<managed-bean>
<description>Noticiero</description>
<managed-bean-name>GestorNoticias</managed-bean-name>
<managed-bean-class>web.GestorNoticias</managed-bean-class>
<managed-bean-scope>application/session/request/none</managed-bean-scope>
<context-param>
 Describe
</managed-bean>
las reglas de navegación.
<param-name>javax.faces.CONFIG_FILES</param-name>
<param-value>/WEB-INF/faces-config.xml,/WEB-INF/faces-beans.xml</param-value>
</context-param>
<navigation-rule>
<from-view-id>/editar/editar.xhtml</from-view-id>
<navigation-case>
<from-outcome>nuevaCategoria</from-outcome>
<to-view-id>/editar/new/categoria.xhtml</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>nuevaNoticia</from-outcome>
<to-view-id>/editar/new/noticia.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
V. Tecnologías Java EE
 JSF Paso a Paso
 Ciclo de Vida
 Podemos crear un Listener.
 Escucha la fase indicada en getPhaseId.

public class PhaseListener implements javax.faces.event.PhaseListener {


public void afterPhase(PhaseEvent event) { System.out.println("AFTER - "+event.getPhaseId()); }
public void beforePhase(PhaseEvent event) { System.out.println("BEFORE - "+event.getPhaseId()); }
public PhaseId getPhaseId() { return PhaseId.ANY_PHASE; }
}

/WEB-INF/faces-config.xml
<lifecycle>
<phase-listener>lst.PhaseListener</phase-listener>
</lifecycle>
V. Tecnologías Java EE
 JSF Paso a Paso
 Mapear Componentes Con Objetos
 Mapear Valores Fijos
 <h:outputText value=“Hola Mundo !!"/>
 Mapear Propiedades del Sistema
 <h:outputText value=“#{initParam.version}"/>
 <h:outputText value=“#{param[‘nombre’]}"/>
 Mapear Propiedades de un Bean Manejado
 Siguen convenciones JavaBean.
 <h:outputText value="#{managedBeans.propiedad}"/>
<managed-bean>
<managed-bean-name>managedBeans</managed-bean-name>
<managed-bean-class>mbeans.ManagedBeans</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>propiedad</property-name>
<value>Hola Mundo !!</value>
</managed-property>
</managed-bean>
V. Tecnologías Java EE
 JSF Paso a Paso
 Mapear Componentes
 Mapear Componentes Completos Backing Beans
 <h:outputText binding="#{managedBeans.component}"/>
package mbeans;
import javax.faces.component.UIOutput;
public class ManagedBeans {
private UIOutput component;
public void setComponent(UIOutput ui) {
component = ui;
component.setValue("Hola Mundito !!");
}
public UIOutput getComponent() { return component; }
}
V. Tecnologías Java EE
 JSF Paso a Paso
 Invocar Métodos
 Métodos de Validación
 Utilizados sólo en UIInput.
 Reciben el FacesContext y el componente a validar y su valor.
<h:messages/>
<h:inputText validator="#{managedBeans.validateEmail}"/>
public void validateEmail(FacesContext ctx, UIComponent cmp, Object obj) {
String email = (String)obj;
if (email.indexOf("@")<0) {
((UIInput)cmp).setValid(false);
ctx.addMessage(cmp.getClientId(ctx),
new FacesMessage("Mail Incorrecto", ""));
} else ((UIInput)cmp).setValid(true);
}
V. Tecnologías Java EE
 JSF Paso a Paso
 Invocar Métodos
 Manejadores de Acciones
 Se utiliza en UICommand y UIButton.
 Reciben el evento.

<h:commandButton value="Pulsa" actionListener="#{managedBeans.ejecutaAccion}“/>

public void ejecutaAccion(ActionEvent ev) {


System.out.println("Se ejecuta la acción !!");
}
V. Tecnologías Java EE
 JSF Paso a Paso
 Invocar Métodos
 Manejadores de Navegación
 Se utiliza en UICommand y UIButton.
 Retornan una cadena de navegación.

<h:commandLink value="Pincha" action="#{managedBeans.onlyAction}“/>

public String onlyAction() {


return “success";
}
V. Tecnologías Java EE
 JSF Paso a Paso
 Invocar Métodos
 Manejadores de Cambios
 Capturar cambios sobre componentes UIInput.

<h:selectBooleanCheckbox
valueChangeListener="#{managedBeans.changeColor}"
onchange="submit()"/>

public void changeColor(ValueChangeEvent event) {


boolean flag = ((Boolean)event.getNewValue()).booleanValue();
System.out.println("Check: "+flag);
}
V. Tecnologías Java EE
 JSF Paso a Paso
 Controlar Navegación
 Conjunto de reglas para seleccionar la siguiente página a la que moverse.
 La selección depende de:
 Página actual.
 Action ejecutado por el componente que navega.
 Cadena retornada por el action (outcome).
 Admite patrones en from-view-id.

<navigation-rule>
<from-view-id>/logon.jsp</from-view-id>
<navigation-case>
<from-action>#{LogonForm.logon}</from-action>
<from-outcome>success</from-outcome>
<to-view-id>/continue.jsp</to-view-id>
</navigation-case>
</navigation-rule>
V. Tecnologías Java EE
 JSF Paso a Paso
 Controlar Navegación. Ejemplos.

<navigation-rule>
<from-view-id>/pages/logon.jsp</from-view-id> Enlace en /pages/logon.jsp Destino
<navigation-case>
<from-outcome>success</from-outcome> <h:commandButton action=“success" value="Submit" /> continue1.jsp
<to-view-id>/continue1.jsp</to-view-id> <h:commandButton action=“#{m.acc}" value="Submit" /> continue2.jsp
</navigation-case>
<navigation-case> <h:commandButton action=“error" value="Submit" /> error.jsp
<from-action>#{m.acc}</from-action>
<from-outcome>success</from-outcome>
Enlace en /pages/otra.jsp Destino
<to-view-id>/continue2.jsp</to-view-id>
</navigation-case>
<h:commandButton action=“success" value="Submit" /> continue3.jsp
</navigation-rule>
<h:commandButton action=“#{m.acc}" value="Submit" /> continue3.jsp
<navigation-rule>
<from-view-id>/pages/*</from-view-id> <h:commandButton action=“error" value="Submit" /> error.jsp
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/continue3.jsp</to-view-id>
</navigation-case>
</navigation-rule>

<navigation-rule>
<navigation-case>
<from-outcome>error</from-outcome>
<to-view-id>/error.jsp</to-view-id>
</navigation-case>
</navigation-rule>
V. Tecnologías Java EE
 JSF Paso a Paso
 Crear el adivinador de números JSF.
 Crear un bean para calcular el número aleatorio.
 El mismo bean puede recoger el número introducido.
 Crea el JSP para solicitar el número, valida la entrada con validateLongRange.
 Configura la navegación adecuada.
V. Tecnologías Java EE
 Crea un Hola Mundo JSF.
V. Tecnologías Java EE
 Crea un Hola Mundo JSF.
V. Tecnologías Java EE
 JSF Paso a Paso
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@
Crear
taglibel adivinador
prefix="f"
Internacionalizar de números JSF.
uri="http://java.sun.com/jsf/core"%>
i18n
<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<application>
<html> <locale-config>
<managed-bean>
<head>
public class<default-locale>es</default-locale>
Adivina {
<%@ <managed-bean-name>adivina</managed-bean-name>
<metapage language="java"
http-equiv="Content-Type" contentType="text/html;
content="text/html;charset=ISO-8859-1"
<supported-locale>en</supported-locale> charset=ISO-8859-1">pageEncoding="ISO-8859-1"%>
<%@ <managed-bean-class>mbeans.Adivina</managed-bean-class>
taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<title>Insert title here</title>
private
</locale-config> long numeroPensado;
<%@ <managed-bean-scope>session</managed-bean-scope>
taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
</head> private int numero;
<message-bundle>msg.mensajes</message-bundle>
<!DOCTYPE <managed-property>
html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<body> private int minimo;
<resource-bundle>
<html> <property-name>minimo</property-name>
<f:view> private int maximo;
<base-name>msg.mensajes</base-name>
<head> <value>1</value>
<h:outputText
<var>msg</var> rendered="#{adivina.intentado}" value="Lo siento, vuelve a probar !!"/>
</managed-property>content="text/html; charset=ISO-8859-1">
<meta http-equiv="Content-Type"
He pensado un número entre <h:outputText
public Adivina() { numeroPensado
</resource-bundle> value="#{adivina.minimo}"/>
= Math.round(Math.random()*10); } y
<managed-property>
<title>Insertpublic
title here</title>
</application> int getNumero() <h:outputText
{ return numero; } value="#{adivina.maximo}"/>, adivina !!
</head> <property-name>maximo</property-name>
<h:form>public void setNumero(int n) { numero = n; }
<body> <value>10</value>
<f:loadBundle <h:messages
public int showDetail="true"/>
basename="msg.mensajes"
getMinimo() { return var="msg"/>
minimo;}
<f:view> </managed-property>
<h:messages <h:selectOneMenu
showDetail=“true”
public void setMinimo(int onchange="submit()"
showSummary=“true”/>
minimo) { this.minimo = minimo; }
</managed-bean> Has acertado, era el <h:outputText value="#{adivina.numero}"/> !!
<h:outputText valueChangeListener="#{adivina.cambiaIdioma}"
value="#{msg.titulo}"/>
public int getMaximo() { return maximo; } immediate="true">
<navigation-rule>
</f:view> public void setMaximo(int <f:selectItem itemLabel="#{msg.castellano}"
maximo) {this.maximo = maximo; }itemValue="es"/>
</body> <from-view-id>/index.jsp</from-view-id>
Archivo de Propiedades:
public <f:selectItem
String adivinar() { returnitemLabel="#{msg.ingles}"
msg/mensajes.properties, itemValue="en"/>
msg/mensajes_en.properties,
(numeroPensado==numero)? "success“:"fail"; } …
</html> <navigation-case>
</h:selectOneMenu>
public boolean<from-outcome>success</from-outcome>
isIntentado() { return numero!=0; }
<h:inputText
publicenvoid value="#{adivina.numero}">
titulo=Pienso un cambiaIdioma(ValueChangeEvent
número event) {
entre minimum="#{adivina.minimo}"
<to-view-id>/next.jsp</to-view-id>
<f:validateDoubleRange maximum="#{adivina.maximo}"/>
FacesContext.getCurrentInstance().getViewRoot().setLocale(new
</navigation-case>
javax.faces.validator.DoubleRangeValidator.NOT_IN_RANGE=Sumario Locale((String)event.getNewValue()));
</h:inputText>
// Cortocircuito !!
<navigation-case>
javax.faces.validator.DoubleRangeValidator.NOT_IN_RANGE_detail=Valor fuera de rango {0} - {1}.
<h:commandButton value="Prueba" action="#{adivina.adivinar}"/>
FacesContext.getCurrentInstance().renderResponse();
<from-outcome>fail</from-outcome>
</h:form>
} <to-view-id>/index.jsp</to-view-id>
} </f:view>
</navigation-case>
</body>
</navigation-rule>
</html>
V. Tecnologías Java EE
 Facelets
 Complemento ideal para JSF.
 Definir una plantilla para tu portal y emplearla en todas tus páginas.

<ui:include src=“cabecera.xhtml”/>

<ui:insert name=“body”/>

/pagina.xhtml
<ui:composition template=“/plantilla.xhtml”>
<ui:include <ui:define name=“body”>
src=“menu.xhtml”/>

</ui:define>
</ui:composition>

<ui:include src=“pie.xhtml”/>
V. Tecnologías Java EE
 Crea una plantilla facelets.
Añadir la librería Facelets:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html jsf-facelets-1.1.15.B1.jar
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
Debemos
Nota: web.xml cambiar
y faces-config.xml los las vistas
modifica y las!!reglas del faces-
eclipse
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets"
config.xml los id de
xmlns:h="http://java.sun.com/jsf/html" las vistas pasan de .jsp a
xmlns:f="http://java.sun.com/jsf/core">
.xhtml.
<f:view contentType="text/html"/>
<head>
<meta http-equiv="Content-Type" content="text/xhtml+xml; charset=UTF-8" />
<title>Simple JSF</title>
<link href="stylesheet/theme.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="content">
<div id="header"><ui:include src="header.xhtml" /></div>
<div id="menu" style="float:left;width:200px;"><ui:include src="menu.xhtml" /></div>
<div id="body" style="float:left;"><ui:insert name="body" >Default Content</ui:insert></div>
<div id="footer"><ui:include src="footer.xhtml" /></div>
</div>
</body>
</html>
V. Tecnologías Java EE
 Usar RichFaces.
<!-- RichFaces en web.xml -->
<context-param>
<param-name>org.richfaces.SKIN</param-name>
Para Usar RichFaces Añadir Librerías:
<param-value>blueSky</param-value>
</context-param>
<!-- RichFaces + Facelets -->
commons-beanutils-1.7.0.jar
<context-param>
<?xml version="1.0" encoding="UTF-8"?>
commons-digester-1.8.jar <param-name>org.ajax4jsf.VIEW_HANDLERS</param-name>
<html … xmlns:a4j="http://richfaces.org/a4j" xmlns:rich="http://richfaces.org/rich">
<param-value>com.sun.facelets.FaceletViewHandler</param-value>
<body bgcolor="white">
</context-param>
commons-logging-1.1.1.jar

<filter>
<rich:panel id="panelRoot" >
<display-name>RichFaces Filter</display-name>
richfaces-api-3.3.1.GA.jar
<rich:spacer height="5" title="Here is a spacer..."/><br />
<filter-name>richfaces</filter-name>
<rich:separator lineType="beveled" height="8" width="100%" align="center"/>
<filter-class>org.ajax4jsf.Filter</filter-class>
richfaces-impl-3.3.1.GA.jar
<rich:separator height="2" lineType="dotted"/><br />
</filter>
</rich:panel>
<filter-mapping>
richfaces-ui-3.3.1.GA.jar

<filter-name>richfaces</filter-name>
</body>
Nota: Hay que configurar a <servlet-name>Faces
</html> mano !! Servlet</servlet-name>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
Y muchos componentes más: RichFaces Live Demo.
<dispatcher>INCLUDE</dispatcher>
</filter-mapping>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>

<!-- Ya no es necesario modificar faces-config.xml -->


<!-- application>
<view-handler>com.sun.facelets.FaceletViewHandler</view-handler>
</application -->
V. Tecnologías Java EE
 Tecnologías Control: EJB
 Dar más servicios a los objetos empleados en las aplicaciones web.
 Contenedor específico para desplegar y ejecutar este tipo de objetos.
 Posibilidad de compartir lógica a través de estos objetos.
 Necesario un Contenedor de EJB. Servidor JEE.
V. Tecnologías Java EE
 Tecnologías Control: EJB
 Tipos de EJB
 Session Beans: Sitos en la lógica de negocio.
 Stateless: Sin información de estado.
 Stateful: Mantienen el estado entre peticiones.
 Message Driven Beans: Utilizados para invocar métodos de forma asíncrona.
 Entity Beans: Empleados en la capa de persistencia para representar datos
del modelo.
V. Tecnologías Java EE
 Tecnologías Control: EJB
 Ciclo de Vida
 Creación, Destrucción, Pasivación (Stateful).
V. Tecnologías Java EE
 Tecnologías Control: EJB
 Callbacks
 Siempre que tenemos un ciclo de vida.
 Posibilidad de emplear AOP.
 @PostConstruct
 @PreDestroy
 @PreActivate
 @PostActivate
 Interceptores
 Siempre que empleamos contenedores IoC y Ciclos de Vida.
 Posibilidad de emplear AOP.
 Default
 Clase
 Método
V. Tecnologías Java EE
 Tecnologías Control: EJB
 Anotaciones.
 Forma de simplificar la definición del EJB.
 @Stateful
 @Stateless

@Stateless
public class PlaceBidBean implements PlaceBid {
@Interceptors(ActionBazaarLogger.class)
public void addBid(Bid bid) {
...
}
}

public class ActionBazaarLogger {


@AroundInvoke
public Object logMethodEntry(InvocationContext invocationContext) throws Exception {
System.out.println(”Entering: ”+ invocationContext.getMethod().getName());
return invocationContext.proceed();
}
}
V. Tecnologías Java EE
 Prácticas II
 Crea un proyecto EJB.
 Liga tu proyecto EJB a una aplicación Web.
 Emplea los EJB’s creados desde la aplicación Web.
 Crea los EJB necesarios para Diario Digital.
V. Tecnologías Java EE
 Crea un proyecto EJB.
V. Tecnologías Java EE
 Crea un EJB.
@Stateless
public class Ejemplo implements EjemploLocal { @Stateful
double numero; public class EjemploB implements EjemploBLocal {
public Ejemplo() { double numero;
System.out.println("Stateless!!!"); public EjemploB() {
numero = Math.floor(Math.random()*10+1); System.out.println("Stateful!!!");
} numero = Math.floor(Math.random()*10+1);
@Override }
public String getMensaje() { @Override
numero++; public String getMensaje() {
return "Mensaje ["+numero+"]"; numero++;
} return "MensajeB ["+numero+"]";
} }
}
public class JSFBean {
@EJB Faces-config.xml
public EjemploBLocal ejemplo; --------------------------------------------------------------------------------------
public String getMensaje() { return ejemplo.getMensaje(); } <managed-bean>
} <managed-bean-name>jSFBean</managed-bean-name>
<managed-bean-class>mb.JSFBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>

Página
--------------------------------------------------------------------------------------
<h:outputText value="#{jSFBean.mensaje}" />
V. Tecnologías Java EE
 Crea un EJB.
V. Tecnologías Java EE
 Tecnologías Modelo: JPA
 Muchos proyectos diferentes ORM.
 IBatis, Hibernate, JDO, TopLink,…
 Necesario unificar: JPA.
V. Tecnologías Java EE
 Tecnologías Modelo: JPA
 Contextos de Persistencia

<?xml version="1.0" encoding="UTF-8"?>


<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
Transacciones JTA: Empleada en Servidores de Aplicaciones JavaEE
version="1.0">
<persistence-unit name="defaultPU" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
Transacciones RESOURCE_LOCAL: Empleada en Aplicaciones C/S.
<jta-data-source>jdbc/NombreDataSource</jta-data-source>
<properties>
<property name="hibernate.hbm2ddl.auto" value="validate"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.default_shema" value="NOMBRE"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
<property name="hibernate.transaction.manager_lookup_class“
value="org.hibernate.transaction.OC4JTransactionManagerLookup"/>
<property name="hibernate.query.factory_class“ value="org.hibernate.hql.classic.ClassicQueryTranslatorFactory" />
<property name="hibernate.transaction.flush_before_completion" value="true"/>
<property name="hibernate.cache.provider_class“ value="org.hibernate.cache.HashtableCacheProvider"/>
</properties>
</persistence-unit>
</persistence>
V. Tecnologías Java EE
 Tecnologías Modelo: JPA
 Empleo de Persistencia
 Declarar un EntityManager ligado a la Unidad que necesites.

public @Stateful class NoticiasBean implements Noticias,Serializable {


@PersistenceContext(unitName="diarioPU")
protected EntityManager entityManager;
private List<Noticia> listado;

public List<Noticia> getListado() {


listado = entityManager.createQuery("from noticias.Noticia noti").getResultList();
return listado;
}
public void nuevaNoticia(Noticia not) { entityManager.persist(not); }
}
V. Tecnologías Java EE
 Tecnologías Modelo: JPA
 Ciclo de Vida: Entity Beans
V. Tecnologías Java EE
 Tecnologías Modelo: JPA
 Anotaciones Básicas: Entidades y Claves
@Entity Clave Simple
public class Entidad {
@EmbeddedId @Entity
@AttributeOverrides({ @Table(name="USUARIOS")
@AttributeOverride(name = "id", column = @Column(name = "ID", public class Usuario {
nullable = false, precision = 5, scale = 0)), @Id
@AttributeOverride(name = "nombre", column = @Column(name = private String nick;
"NOMBRE", nullable = false, length = 50)), ...
}) public Usuario() { }
private EntidadId id; // Getters y Setters
public Entidad() { } }
// Getters y Setters
}
@Embedded
public class EntidadId {
int id;
String nombre;
public EntidadId() { }
public boolean equals(Object o) { /* Comprueba si son iguales */ }
public int hashCode() { /* Buenas practicas equals() -> hashCode() */ }
} Clave Compuesta
V. Tecnologías Java EE
 Tecnologías Modelo: JPA
 Anotaciones Básicas: Atributos
@Entity Atributo Simple
@Table(name="USUARIOS")
public class Usuario { @Entity
@Id @Table(name="USUARIOS")
private String nick; public class Usuario {
@Embedded @Id
@AttributeOverrides({ private String nick;
@AttributeOverride(name="codigoPostal",column=@Column(name="COD_POS")), @Column(name="PASSWORD", nullable=false)
@AttributeOverride(name="direccionPostal",column=@Column(name="DIR_POS")) private String pass;
}) @Column(name="E-MAIL", nullable=false)
private Direccion direccion; private String mail;
public Usuario() { } @Lob
// Getters y Setters @Basic(fetch=FetchType.LAZY)
} private byte[] imagen;
@Embeddable ...
public class Direccion implements Serializable { public Usuario() { }
private String direccionPostal; // Getters y Setters
private String ciudad; }
private int codigoPostal;
private String pais;
public Direccion() { }
public boolean equals(Object o) { /* Comprueba si las dos entidades son iguales */ }
public int hashCode() { /* Buenas practicas equals() -> hashCode() */ }
// Getters y Setters
} Atributo Compuesto
V. Tecnologías Java EE
 Tecnologías Modelo: JPA
 Anotaciones Básicas: Relaciones OneToOne @Entity
@Table(name="PERFILES")
@Entity public class Perfil {
@Table(name="USUARIOS") @Id
public class Usuario { @Column(name="PERFIL_ID")
@Id private int id;
CascadeType.PERSIST:
private String nick;
Cuando persistamos la entidad todas las entidades ... que contenga esta
variable serán persistidas
@Column(name="PASSWORD", también.
nullable=false) }
CascadeType.REMOVE:
private String pass; Cuando borremos la entidad todas las entidades que contenga esta
@OneToOnevariable se borrarán del mismo modo.
@JoinColumn(name="PERFIL_USUARIO_ID",referencedColumnName="PERFIL_ID",
CascadeType.REFRESH: Cuando actualicemos la entidad todas updatable=false)
las entidades que contenga
private Perfilesta
perfil;
variable se actualizarán.
private Set<Noticia> noticias = new HashSet<Noticia>(0);
CascadeType.MERGE: Cuando hagamos un "merge" de la entidad todas las entidades que
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY,mappedBy = "usuario")
contenga
public Set<Noticia> esta variable
getNoticias() { realizarán la misma operación.
CascadeType.ALL:
return this.noticias; Todas las operaciones citadas anteriormente.
@Entity
} @Table(name = "NOTICIA")
public void setNoticias(Set<Noticia> noticias) { public class Noticia implements java.io.Serializable {
this.noticias = noticias; ...
} private Usuario usuario;
... @ManyToOne(fetch = FetchType.LAZY)
} @JoinColumn(name = "USUARIO", nullable = false)
@NotNull
ManyToMany: Muy similar a ManyToOne pero public Usuario getUsuario() { return this.usuario; }
simétrica en ambas clases. public void setUsuario(Usuario usuario) { this.usuario = usuario; }
...
ManyToOne }
V. Tecnologías Java EE
 Tecnologías Modelo: JPA
 Anotaciones Avanzadas: Querys Personalizadas

@NamedNativeQuery (
name="nativeResult",
query="SELECT USUARIO_ID,NOMBRE,APELLIDOS FROM USUARIOS WHERE USUARIO_ID= 123",
resultSetMapping = "usuarioNamedMapping")

@SqlResultSetMapping (
name="usuarioNamedMapping",
entities = { @EntityResult (
entityClass = mi.clase.Usuario.class,
fields = {@FieldResult (
name="usuarioId",
column="USUARIO_ID"),
@FieldResult (
name="nombre",
column="NOMBRE"),
@FieldResult (
name="apellidos",
column="APELLIDOS")
})
})
V. Tecnologías Java EE
 Tecnologías Modelo: JPA
 Anotaciones Avanzadas: Procedimientos Almacenados

create or replace procedure findUsersLike(res out sys_refcursor, str in string) as


begin
open res for select u.* from users u where u.username like concat(str, '%');
end findUsersLike;

@NamedNativeQuery (name = "User.findLike",


resultClass = User.class,
query = "{call findUsersLike(?,:VAR)}",
hints = {
@QueryHint(name = "org.hibernate.callable", value = "true"),
@QueryHint(name = "org.hibernate.readOnly", value = "true")
}
)
@org.hibernate.annotations.NamedNativeQuery (name=“User.findLike”,
resultClass = User.class,
query = "{call findUsersLike(?,:VAR)}",
callable = true, readOnly = true)

Query query = em.createNamedQuery("User.findLike");


query.setParameter("VAR","lt");
List users = query.getResultList();
V. Tecnologías Java EE
 Aplicación Completa: JSF+EJB3+JPA
 Emplear EJB Session Bean Facade.
V. Tecnologías Java EE
 Prácticas III
 Crea un ejemplo de Bean de Entidad.
 Incluye atributos de diferentes tipos.
 Relaciona varias entidades.
 Convierte los objetos del Diario Digital en entidades JPA para dotarlas de
persistencia.
V. Tecnologías Java EE
 Crea un ejemplo de Bean de Entidad.
V. Tecnologías Java EE
 Crea un ejemplo de Bean de Entidad.
V. Tecnologías Java EE
 Crea un ejemplo de Bean de Entidad.
V. Tecnologías Java EE
 Crea un ejemplo de Bean de Entidad.

<?xml version="1.0" encoding="UTF-8"?>


<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="DiarioJPA" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>DiarioDataSource</jta-data-source>
<non-jta-data-source>DiarioDataSource</non-jta-data-source>
<class>data.Categoria</class>
<class>data.Noticia</class>
<properties>
<property name="eclipselink.target-server" value="WebLogic_10"/>
<property name="eclipselink.logging.level" value="FINEST"/>
</properties>
</persistence-unit>
</persistence>
VI. Tecnologías
Avanzadas
VI. Tecnologías Avanzadas
 Servicios WEB
 Forma de interactuar.
VI. Tecnologías Avanzadas
 Servicios WEB
 Buscar servicios Web: UDDI.
 Catálogo de Servicios.
 Invocar Servicios Web: WSDL.
 Descriptor del Servicio.
 Intercambio de Información: SOAP.
 Documentos XML.
 Las herramientas nos simplifican el trabajo.
 A partir de un método podemos crear un servicio.
 A partir de un WSDL podemos crear un cliente.
VI. Tecnologías Avanzadas
 Servicios WEB
 Implementaciones Diversas: Tratan de automatizar la creación de servicios y
clientes.
 Axis2
 JAXWS
 CXF
 Usaremos JAXWS.
 En FundeWeb se usará CXF, pero el curso se centra en la interacción y no en las
implementaciones.
VI. Tecnologías Avanzadas
 Prácticas I
 Crea un Sencillo Servicio Web.
 Pruébalo con el “Web Service Explorer”
 Genera un cliente a partir del WSDL.
 Crea el Servicio Web “Teletipo”.
 Incluye en el Diario Digital las noticias del “Teletipo”.
VI. Tecnologías Avanzadas
 Crea un Sencillo Servicio Web.
VI. Tecnologías Avanzadas
 Crea un Sencillo Servicio Web.
http://localhost:7001/DiarioWS/TitularesService?WSDL
@WebService
public class Titulares {
http://localhost:7001/wls_utc/?wsdlUrl=http://localhost:7001/DiarioWS/TitularesService?WSDL
@EJB
private NoticiasLocal misNoticias;
@WebMethod
public List<Titular> listTitulares() {
ArrayList<Titular> lista = new ArrayList<Titular>();
for (Noticia n:misNoticias.getListadoPortada()) {
Titular t = new Titular();
t.setTitulo(n.getTitulo()); t.setFecha(n.getDia());
lista.add(t);
}
return lista; public class Titular implements Serializable {
} private String titulo;
} private Date fecha;
public String getTitulo() { return titulo; }
public void setTitulo(String titulo) { this.titulo = titulo; }
public Date getFecha() { return fecha; }
public void setFecha(Date fecha) { this.fecha = fecha; }
}
VI. Tecnologías Avanzadas
 Crea un Sencillo Servicio Web.

public List<Titular> getTitulares() {


TitularesService ts = new TitularesService();
return ts.getTitularesPort().listTitulares();
}
VI. Tecnologías Avanzadas
 Autenticación JAAS
 Java EE permite emplear roles para securizar recursos de una aplicación.

<security-role>
<role-name>administrador</role-name>
</security-role>
<security-role>
<role-name>usuario</role-name>
</security-role>

<orion-application …>
...
<jazn provider="XML" location="./jazn-data.xml" default-realm="example.com">
<property name="jaas.username.simple" value="false"/>
</jazn>
</orion-application>

<jazn-data
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://xmlns.oracle.com/oracleas/schema/jazn-data-10_0.xsd" filepath="" OC4J_INSTANCE_ID="">
<jazn-realm>
<realm>
<name>example.com</name>
<users><user><name>admin</name><credentials>!admin</credentials></user></users>
<roles>
<role><name>administrador</name><members><member><type>user</type><name>admin</name></member></members></role>
</roles>
</realm>
</jazn-realm>
</jazn-data>
VI. Tecnologías Avanzadas
 Autenticación JAAS
 Java EE permite emplear roles para securizar recursos de una aplicación.

@DeclareRoles({"administrador", "usuario"})
public class Ejemplo extends HttpServlet {
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
if (req.isUserInRole("administrador")) {
// El usuario Autenticado tiene el rol administrador
}
}
}

<security-constraint>
<web-resource-collection>
<web-resource-name>Permiso Ejemplo</web-resource-name>
<url-pattern>/Ejemplo</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>administrador</role-name>
</auth-constraint>
<user-data-constraint>
<transport-guarantee>NONE</transport-guarantee>
</user-data-constraint>
</security-constraint>
<!-- LOGIN CONFIGURATION-->
<login-config>
<auth-method>BASIC</auth-method>
</login-config>
VI. Tecnologías Avanzadas
 Prácticas II
 Crea roles en una aplicación.
 Añade seguridad a diferentes recursos.
 Securiza la creación de noticias en el Diario Digital.
VI. Tecnologías Avanzadas
 Crea roles en una aplicación.
<!-- ROLES DE SEGURIDAD -->
<security-role>
<role-name>redactor</role-name> <wls:security-role-assignment>
</security-role> <wls:role-name>redactor</wls:role-name>
<security-role>
<wls:principal-name>Administrators</wls:principal-name>
<role-name>usuario</role-name>
</security-role> </wls:security-role-assignment>
<security-constraint> <wls:security-role-assignment>
<web-resource-collection> <wls:role-name>usuario</wls:role-name>
<wls:principal-name>AppTesters</wls:principal-name>
<web-resource-name>Redaccion del Diario</web-resource-name>
<url-pattern>/editar/*</url-pattern> </wls:security-role-assignment>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>redactor</role-name>
</auth-constraint>
<user-data-constraint>
<transport-guarantee>NONE</transport-guarantee>
</user-data-constraint>
</security-constraint>
<!-- LOGIN CONFIGURATION-->
<login-config>
<auth-method>BASIC</auth-method>
</login-config>
VI. Tecnologías Avanzadas
 Portales y Portlets
 Idea similar a la de los servlets.
 Componentes configurables y reubicables.
 Pensados para su uso en portales.
 Especificación JSR 168.
VI. Tecnologías Avanzadas
 Portales y Portlets
 Ventajas
 Desarrollo independiente y reutilizable.
 Personalización dinámica.
 Seguridad ante fallos. El fallo de un portlet no afecta al resto del portal.
 Adoptado por otras tecnologías. PHP Portlet.
 Inconvenientes
 Tecnología relativamente nueva.
 Genera portales con poca personalidad.
A. Diario Digital
A. Diario Digital
 Práctica Global
 Muestra las noticias de un diario y un teletipo.

EAR Application

WEB Module WEB Module

JSF Application Web Service JSF Application

EJB Module
Database
¡ Gracias !

You might also like