DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

  1. DZone
  2. Refcards
  3. Core Seam
refcard cover
Refcard #31

Core Seam

Seam in Practice

Covers commonly used annotations and XML elements as of Seam 2.1. and points you to examples of how the configuration options can be used in practice.

Download Refcard
Free PDF for Easy Reference
refcard cover

Written By

author avatar
,
Table of Contents
► About SEAM ► Dependency Injection in a Nutshell ► Contextual Components ► Rapid Application Development ► Conversation Management
Section 1

About SEAM

By Jacob Orshalick

Seam is a next generation web framework that integrates standard Java EE technologies with a wide variety of nonstandard technologies into a consistent, unified, programming model. Seam drove the development of the Web Beans specification (JSR-299) and continues to develop innovations that are changing the face of web development as well as Java EE technologies. If you haven't taken a look at Seam, I suggest you do.

As you develop Seam applications, you'll find this quick reference

a handy guide for understanding core concepts, configuration, and tool usage. This quick reference is not intended to cover all of what Seam provides, but will cover the most commonly used annotations and XML elements as of Seam 2.1. In addition, this guide will point you to examples distributed with Seam to see real examples of how the configuration options can be used in practice.

Section 2

Dependency Injection in a Nutshell

Dependency injection is an inversion of control technique that forms the core of modern-day frameworks. Traditionally objects have held the responsibility for obtaining references to the objects they collaborate with. These objects are extroverted as they reach out to get their dependencies. This leads to tight coupling and hard to test code.

Dependency injection allows us to create introverted objects. The objects dependencies are injected by a container or by some external object (e.g. a test class). Bijection is described by the following formula:

dependency injection + context = bijection

With bijection, when dependencies are injected context counts! Dependencies are injected prior to each component method invocation. In addition, components can contribute to the context by outjecting values

Diagram

As you can see the HotelBookingAction is scoped to and executes within a context. This behavior allows us to quit worrying about shuffling values into and out of contexts like the HttpSession, allows components to hold state, and unifies the component model across application tiers.

Section 3

Contextual Components

When a method is invoked on a component, its dependencies are injected from the current context. Seam performs a context lookup in the following order of precedence: Event Scope, Page Scope, Conversation Scope, Session Scope, Business Scope, Application Scope.

Component Annotations

Component Definition Annotations

In order for your Seam components to take advantage of bijection, you must register them with the Seam container. Registering your component with Seam is as simple as annotating it with @Name. The following annotations will register your component and define its lifecycle.

AnnotationUseDescription@NameTypeDeclares a Seam component by name. The component is registered with Seam and can be referenced by name through Expression Language (EL), injection, or a context lookup.@ScopeTypeDefines the scope (or context) the Seam component will be placed into by the container when created.@AutoCreateTypeSpecifies that a component should be created when being injected if not available in the current context.@StartupTypeIndicates that an application scoped component should be created when the application is initialized or that a session component should be created when a session is started. Not valid for any other contexts.@InstallTypeDeclares whether a Seam component should be installed based on availability of dependencies or precedence.@RoleTypeDefines an additional name and scope associated with the component. The @Roles annotation allows definition of multiple roles.

Component Bijection Annotations: Once you have defined a component, you can specify the dependencies of your component and what the component contributes back to the context.

AnnotationUseDescription@InField, MethodDeclares a dependency that will be injected from the context, according to context precedence, prior to a method invocation. Note that these attributes will be disinjected (or set to null) after the invocation completes.@OutField, MethodDeclares a value that will be outjected after a method invocation to the context of the component (implicit) or a specified context (explicit).

Component Lifecycle Annotations: The following annotations allow you to control the lifecycle of a component either by reacting to events or wrapping the component entirely.

AnnotationUseDescription@CreateMethodDeclares that a method should be called after component instantiation.@DestroyMethodDeclares that a method should be called just before component destruction.@FactoryMethodMarks a method as a factory method for a context variable. A factory method is called whenever no value is bound to the named context variable and either initializes and outjects the value or simply returns the value to the context.@UnwrapMethodDeclares that the object returned by the annotated getter method is to be injected instead of the component itself. Referred to as the "manager component" pattern.

Component Events Annotations: Through Seam's event model, components can raise events or listen for events raised by other components through simple annotation. In addition, Seam defines a number of built-in events that the application can use to perform special kinds of framework integration (see http://seamframework.org/Documentation, Contextual Events).

AnnotationUseDescription@RaiseEventMethodDeclares that a named event should be raised after the method returns a non-null result without exception.@ObserverMethodDeclares that a method should be invoked on occurrence of a named event or multiple named events.

The Components Namespace

Schema URI

http://jboss.com/products/seam/components

Schema XSD

http://jboss.com/products/seam/components-2.1.xsd

So far we've seen how components can be declared using annotations. In most cases this is the preferred approach, but there are some situations when component definition through annotations is not an option:

  • when a class from a library outside of your control is to be exposed as a component
  • when the same class is being configured as multiple components

In addition, you may want to configure values into a component that could change by environment, e.g. ip-addresses, ports, etc. In any of these cases, we can use XML to configure the component through the components namespace.

Seam XML Diagram Key

The Seam XML diagrams use the following notations to indicate required elements, cardinality, and containment:

XML diagrams

Components Namespace Diagram

Components Namespace Diagram

Components Namespace Elements

ElementDescription<component>Defines a component in the Seam container.<event>Specifies an event type and the actions to execute on occurrence of the event.<factory>Lets you specify a value or method binding expression that will be evaluated to initialize the value of a context variable when it is first referenced. Generally used for aliasing.<import>Specifies component namespaces that should be imported globally which allows referencing by unqualified component names. Specified by package.<action>Specifies an action to execute through a method binding expression.<property>Injects a value or reference into a Seam component. Can use a value or method binding expression to inject components.<key>Defines the key for the following value when defining a map.<value>For list values, the value to be added. For map values, the value for the preceding key.

Component Element Attributes: The attributes of the component element are synonymous with component definition through annotations.

ElementDescriptionnameDeclares a component by name; synonymous with @Name.classReferences the Java class of the component implementation.scopeDefines the scope (or context) the Seam component will be placed into by the container when created.precedencePrecedence is used when a name-clash is found between two components (higher precedence wins).installedBoolean indicating whether the component should be installed.auto-createSpecifies that a component should be created when being injected if not available in the current context.startupIndicates that an application scoped component should be created when the application is initialized or that a session component should be created when a session is started. Not valid for any other contexts.startupDependsA list of other application scope components that should be started before this one, if they are installed.jndi-nameEJB components only. The JNDI name used to lookup the component. Only used with EJB components that don't follow the global JNDI pattern.Components Namespace ExampleThe following examples demonstrate how component configuration is possible with Seam. The hotelBooking component is configured for injection of a paymentService instance.

​x
1
​
2
<?xml version="1.0" encoding="UTF-8"?>
3
<components
4
xmlns="http://jboss.com/products/seam/components"
5
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
6
xsi:schemaLocation=
7
"http://jboss.com/products/seam/components
8
http://jboss.com/products/seam/components-2.1.xsd">
9
        <component name="hotelBooking">
10
                <property name="paymentService">
11
                #{paymentService}
12
                </property>
13
        </component>
14
        <component name="paymentService" scope="APPLICATION"
15
        class="com.othercompany.PaymentServiceClient">
16
                <property name="ipAddress">127.0.0.1
17
                <property name="port">9998
18
        </component>
19
</components>

Note that we specified a name and class for the PaymentServiceClient instances. This is required as the PaymentServiceClient is a library implementation. The name is always required, but the class can be omitted if you are simply configuring the values of a component with an @Name annotation as shown with the hotelBooking. The scope is restricted to the scopes provided by Seam; here we use APPLICATION.Simplify your component configuration through use of namespaces.

Seam makes this quite simple through use of the @Namespace annotation. Just create a file named package-info.java in the package where your components live:

5
1
​
2
@Namespace(value="http://solutionsfit.com/example/booking")
3
package com.solutionsfit.example.booking;
4
import org.jboss.seam.annotations.Namespace;
5
​

Now we can reference the namespace in our components.xml:

8
1
​
2
<components xmlns=
3
        "http://jboss.com/products/seam/components"
4
        xmlns:payment="http://solutionsfit.com/example/booking">
5
        ... ...
6
        <payment:hotel-booking
7
                payment-service="#{paymentService}">
8
​

Note that component names and attribute names are specified in hyphenated form when using namespaces. To gain the benefits of auto-completion and validation, a schema can also be created to represent your components. A custom schema can import the components namespace to reuse the defined component types.

Section 4

Rapid Application Development

Seam-gen is a rapid application generator shipped with the Seam distribution. With a few command line commands, seam-gen generates an array of artifacts for Seam projects to help you get started. In particular, seam-gen is useful for the following.

  • Automatically generate an empty Seam project with common configuration files, a build script, and directories for Java code and JSF view pages.
  • Automatically generate complete Eclipse and NetBeans project files for the Seam project.
  • Reverse-engineer entity bean objects from relational database tables.
  • Generate template files for common Seam components.

Seam-gen Commands

Seam-gen command should be executed in the directory of your Seam distribution. To get started execute the seam setup command. Each command provides useful prompts that will guide you through the configuration specifics.

CommandDescriptionseam setupConfigures seam-gen for your environment: JBoss AS installation directory, Eclipse workspace, and database connection.seam new-projectCreates a new deployable Seam project based on the configuration settings provided in the setup.seam -D[profile] deployDeploys the new project you've created with the configuration specific to the [profile] specified, i.e. dev, test, or prod.seam new-actionCreates a simple web page with a stateless action method. Generates a facelets page and component for your project.seam new-formCreates a form with an action.seam generate-entitiesGenerates an application from an existing database. Simply ensure that your setup points to the appropriate database.seam generate-uiGenerates an application from existing JPA/EJB3 entities placed into the src/model folderseam restartRestarts the application on the server instance

Seam-gen Source Directories

The source directories created by seam-gen are each dedicated to holding certain types of source files. This enables seam-gen to determine what tests need to be executed as well as selectively hot-deploy your Seam components.

/src/mainClasses to include in the main (static) classpath./src/hotClasses to include in the hot deployable classpath when running in development mode (see the Hot Tip below)./src/testTest classes should be placed in this source folder. These classes will not be deployed but will be executed as part of the test target.

Seam-gen Profiles

Seam-gen supports the concept of "profile". The idea is that the application probably needs different settings (e.g. database settings, etc) in the development, test, and production phases. So, the project provides alternative configuration files for each of the three scenarios. In the resources directory, you will find the following configuration files:

/META-INF/persistence-*.xmlProvides configuration of a JPA persistence-unit for each environment.import-*.sqlImports data into a generated schema based on deployment environment. Generally useful for testing purposescomponents-*.propertiesAllows wild-card replacement of Seam component properties based on environment (see Hot Tip in the Core Namespace for more information).

Hot Tip

Don't restart your application, use incremental hot deployment. Seam-gen provides support for exploded deployment of your application. Exploded deployment allows changes to any XHTML file or the pages.xml file to be redeployed without an application restart. In order to enable incremental hot deployment, you must set Seam and Facelets into debug mode. By default, a seamgen'd application is debug enabled in the dev profile. If you are using JavaBean action components, they are also deployable without an application restart. Just ensure they are placed in your /src/hot folder and debug mode is turned on.

Section 5

Conversation Management

The Conversation Model in a Nutshell

The conversation model is the core of Seam. It provides the basis of context management in Seam applications. A session holds potentially many concurrent conversations with a user, each tied to its own unit of work with its own context.

Conversation Model

On every user request a temporary conversation is created or a long-running conversation is resumed. A conversation is resumed when a valid conversation-id (cid) is sent with the request.

Conversation Model

* Note that the filled circle indicates the initial state, while the hollow circle containing a smaller filled circle indicates an end state.

Temporary ConversationsA temporary conversation is started on every request unless an existing long-running conversation is being resumed. Even if your application does not explicitly specify conversation handling a conversation will be initialized for the request. A temporary conversation survives a rediLong-running ConversationsA temporary conversation is promoted to longrunning if you tell Seam to begin a long-running conversation. Promoting a conversation to long-running informs Seam to maintain the conversation between requests. The conversation is demoted to temporary if you tell Seam to end a long-running conversation.

Conversation Management Annotations

These annotations provide declarative conversation management through Seam components.

AnnotationUseDescription@ConversationalType, MethodA component or method annotated as @Conversational can only be accessed in the context of a long-running conversation.@BeginMethodMarks a method as beginning a long-running conversation. The long-running conversation will only end upon method return if: the method is void return-type or the method returns a non-null outcome.@EndMethodMarks a method as ending a long-running conversation. The long-running conversation will only begin upon method return if: the method is void return-type or the method returns a non-null outcome.

Conversation Management Usage

Some example usage patterns for conversation propagation.

1. Begin a conversation when the selectHotel method is invoked:

6
1
​
2
@Begin
3
public void selectHotel(Hotel selectedHotel)
4
{
5
        hotel = em.merge(selectedHotel);
6
}

2. End a conversation when the booking is confirmed:

6
1
​
2
@End(beforeRedirect="true")
3
        public void confirm()
4
        {
5
                em.persist(booking);
6
                ...
Note the use of the beforeRedirect parameter. Recall that a conversation is really only demoted to temporary when ended and survives a redirect. Here the conversation is destroyed before the redirect.3. Begin a conversation with manual flushing enabled:
7
1
​
2
@In private EntityManager em;
3
@Begin(flushMode=FlushModeType.MANUAL)
4
public void editBooking(int selectedId)
5
{
6
        booking = em.find(Booking.class, selectedId);
7
}
This ensures that the booking would not be persisted until an EntityManager.flush() is invoked manually. This is only usable with an SMPC and Hibernate as the persistence provider.
4. Begin or join the conversation when the hotel page is accessed:
7
1
​
2
<page view-id="/hotel.xhtml"
3
        login-required="true">
4
        <description>
5
        View hotel: #{hotel.name}
6
        </description>
7
        <begin-conversation join="true">
This example demonstrates conversation management through the pages.xml file. The pages.xml file provides a navigation-centric approach to conversation management directly relating the boundaries of a conversation to page navigation.5. Leave the scope of an existing conversation to return to the main page:
3
1
​
2
<s:link view-id="/main.xhtml" value="Return to main"
3
        propagation="none" />
Use of the <s:link> and <s:button> tags in your view are common to either propagate a conversation across a GET request or to leave the scope of an existing conversation.

Seam Distribution Conversation Management Examples

The following examples are distributed with Seam and provide great resources for configuring your application.

ExampleDirectoryDescriptionSeam Bookingexamples/bookingDemonstrates the most basic conversation management through use of annotations.Nested Bookingexamples/nestedbookingDemonstrates the use of nested conversations through annotations.Seam Spaceexamples/seamspaceDemonstrates conversation management through pages.xml as well as use of natural conversations.

Hot Tip

Let your conversations time-out! It is a common misconception that conversations should always be ended when navigating elsewhere in an application. Seam ensures that these abandoned, or background conversations are cleaned up after a period of time (the conversation-timeout setting). The conversation that the user last interacted, the foreground conversation, will only timeout when the session times out. See the Core Namespace to learn how to configure the conversation-timeout setting.

Common Application Configuration

The Core Namespace

Schema URI

http://jboss.com/products/seam/core

Schema XSD

http://jboss.com/products/seam/core-2.1.xsd

The core namespace includes support for configuration of Seam components found in org.jboss.seam.core. This includes the JNDI pattern used to lookup EJB components, debug mode settings, conversation management, inclusion of custom resource bundles, and POJO cache settings.

Core Namespace Diagram

Core Namespace Diagram

Core Namespace Elements

ElementDescription<core:init>Initialization parameters including debug settings and configuration of the jndiPattern for EJB users.<core:resource-loader>Allows configuration of custom resource bundle-names for loading messages.<core:bundle-names>Custom bundle names can be specified which are searched depth-first for messages. This overrides the standard messages.properties.<core:manager>Configures conversation management settings such as timeouts, parameter names, uri-encoding, and the default-flush-mode.<core:interceptors>Configures the list of interceptors that should be enabled for all components. All built-in interceptors must be specified with any additional interceptors.Core Namespace Example

The following example demonstrates use of the core namespace:

17
1
​
2
<?xml version="1.0" encoding="UTF-8"?>
3
<components
4
        xmlns="http://jboss.com/products/seam/components"
5
        xmlns:core="http://jboss.com/products/seam/core"
6
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
7
        xsi:schemaLocation=
8
                "http://jboss.com/products/seam/core
9
                http://jboss.com/products/seam/core-2.1.xsd
10
                http://jboss.com/products/seam/components
11
                http://jboss.com/products/seam/components-2.1.xsd">
12
        <core:init jndi-pattern="@jndiPattern@" debug="@debug@"/>
13
​
14
        <core:manager conversation-timeout="600000"
15
                        conversation-id-parameter="cid"
16
                        default-flush-mode="MANUAL" />
17
​
The above configuration tells Seam how to find EJB components in the JNDI registry and whether to operate in debug mode allowing features such as incremental deployment. The manager configuration ensures that background conversations timeout after 10 minutes through the conversation-timeout setting. Note the setting is configured in milliseconds. The cid parameter simply specifies how our conversation ID should be represented in a query string, e.g. /book.seam?cid=20.

Note the use of the default-flush-mode setting. If you are using a Seam-managed Persistence Context (SMPC), which will be discussed shortly, this setting will save constant repetition of the flush-mode setting when beginning conversations.

Hot Tip

It is generally a good idea to keep some application configuration in properties files. This makes it simple for administrators to easily tweak deployment- specific settings (e.g. database settings).

Seam lets you place wildcards of the form @propertyName@ in your components.xml file. Seam uses the components.properties file in the classpath to replace the properties by name. Seam-gen projects use this approach by default to dynamically replace the jndiPattern and debug settings.

The Transaction Namespace

Transaction Namespace URI

http://jboss.com/products/seam/transaction

Transaction Namespace XSD

http://jboss.com/products/seam/transaction-2.1.xsd

Transactions are an essential feature for database-driven web applications. In each conversation, we typically need to update multiple database tables. If an error occurs in the database operation (e.g. a database server crashes), the application needs to inform the user, and all the updates this conversation has written into the database must be rolled back to avoid partially updated records. In other words, all database updates in the conversation must happen inside an atomic operation. Seam-managed transactions along with Seam-managed persistence enables you to do just that.

Transaction Namespace Diagram

Transaction Namespace Diagram

ElementDescription<transaction:ejb-transaction>Configures the EJB transaction synchronization component which should be installed if you are working in a Java EE 5 environment.<transaction:entity-transaction>Configures JPA RESOURCE_LOCAL transaction management where the the managedpersistence-context is injected as an Expression Language (EL) attribute. This attribute is not required if your EntityManager is named entityManager. <transaction:hibernate-transaction>Configures Hibernate managed transactions where the persistence:managed-hibernatesession is injected as an Expression Language (EL) attribute. This attribute is not required if your Session is named session.<transaction:no-transaction>Disables Seam-managed transactions.Transaction Namespace Example

The following example configures the EJB transaction

22
1
​
2
<components
3
        xmlns="http://jboss.com/products/seam/components"
4
        xmlns:persistence=
5
        "http://jboss.com/products/seam/persistence"
6
        xmlns:transaction=
7
        "http://jboss.com/products/seam/transaction"
8
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
9
        xsi:schemaLocation=
10
                "http://jboss.com/products/seam/persistence
11
                http://jboss.com/products/seam/persistence-2.1.xsd
12
                http://jboss.com/products/seam/transaction
13
                http://jboss.com/products/seam/transaction-2.1.xsd
14
                http://jboss.com/products/seam/components
15
                http://jboss.com/products/seam/components-2.1.xsd">
16
​
17
        <persistence:managed-persistence-context name="em"
18
                auto-create="true" persistence-unit-jndi-name=
19
                        "java:/EMFactories/bookingEntityManagerFactory"/>
20
        <transaction:ejb-transaction/>
21
... ...
22
​

Note that this indicates the application is being deployed to a JEE 5 environment.

The Persistence Namespace

Persistence Namespace URI

http://jboss.com/products/seam/persistence

Persistence Namespace XSD

http://jboss.com/products/seam/persistence-2.1.xsd

When JPA is used within an EJB environment, an extended persistence context can be associated with a stateful session bean. An extended persistence context lives between requests and is scoped to the stateful component allowing entities to remain managed. The EJB3 approach has several shortcomings:

  • What if my application does not operate in an EJB environment?
  • It can be tricky to ensure that the persistence context is shared between loosely coupled components.
  • EJB3 does not include the concept of manual flushing.

A Seam-managed persistence context (or SMPC) is available for use in both environments and alleviates these issues altogether. An SMPC is just a built-in Seam component that manages an instance of EntityManager or Hibernate Session in the conversation context. You can inject it with @In.

Note that many of the options for configuring a HibernateSessionFactory have been omitted due to space constraints. For more options on configuring your HibernateSessionFactory, see the Seam Reference Documentation (http://seamframework.org/Documentation).

Persistence Namespace Diagram

Persistence Namespace Diagram

Persistence Namespace Elements

ElementDescription <persistence:entity-manager-factory>Informs Seam to bootstrap a JPA EntityManagerFactory from your persistence.xml file. <persistence:managed-persistence-context>Configures a Seam managed JPA EntityManager to be available via injection.<persistence-unit-jndi-name>Allows the persistence unit’s JNDI name to be embedded as an element rather than an attribute. <persistence:hibernate-session-factory>If you choose to use Hibernate directly, informs Seam to bootstrap a HibernateSessionFactory. Allows your Hibernate configuration to be specified through a variety of approaches with the sub-elements shown in the namespace diagram. <persistence:managed-hibernate-session>Configures a Seam-managed Hibernate Session to be available via injection.<persistence:filters>Defines a set of Hibernate filters. Can only be used with Hibernate.<persistence:filter>Defines a Hibernate filter that is enabled whenever an EntityManager or Hibernate Session is first created. Can only be used with Hibernate.<persistence:name>Provides the name of the Hibernate filter.<persistence:parameters>Specifies key-value pairs setting the parameter values as Expression Language (EL) expressions for the Hibernate filter.Persistence Namespace Example

The following example demonstrates use of the persistence namespace:

17
1
​
2
<components
3
        xmlns="http://jboss.com/products/seam/components"
4
        xmlns:persistence=
5
        "http://jboss.com/products/seam/persistence"
6
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
7
        xsi:schemaLocation=
8
                "http://jboss.com/products/seam/persistence
9
                http://jboss.com/products/seam/persistence-2.1.xsd
10
                http://jboss.com/products/seam/components
11
                http://jboss.com/products/seam/components-2.1.xsd">
12
        <persistence:managed-persistence-context name="em"
13
                auto-create="true" persistence-unit-jndi-name=
14
                        "java:/EMFactories/bookingEntityManagerFactory"/>
15
... ...
16
</components>
17
​

As configured above, a Seam-managed EntityManager can be injected as:

3
1
​
2
@In EntityManager em;
3
​

The EntityManagerFactory is looked up by the configured JNDI name so this name must be consistent with your persistence.xml configuration. If you are using JBoss this can be configured with the following in the properties of your persistence-unit definition:

4
1
​
2
<property name="jboss.entity.manager.factory.jndi.name"
3
        value="java:/EMFactories/bookingEntityManagerFactory"/>
4
​

Seam Distribution Persistence Configuration Examples

The following examples are distributed with Seam and provide great resources for configuring your application.

ExampleDirectoryDescriptionBookingexamples/bookingDemonstrates configuration of using a basic EJB PersistenceContext managed by the EJB container.Hibernate Bookingexamples/hibernateDemonstrates configuration of using direct Hibernate persistence with a Seam-managed Hibernate Session.JPA Bookingexamples/jpaDemonstrates use of an SMPC with JPA RESOURCE_LOCAL transaction management usable in non-EJB containers like Tomcat.

Seam Security

Security is arguably one of the most important aspects of application development. Unfortunately due to its complexity security is often an afterthought which can lead to gaping holes in an application for malicious users to take advantage of. Fortunately, when using Seam this complexity is hidden making it simple to ensure that your next application is secure.

Seam security provides extensive configuration options making it useful in a wide array of implementations but also making it worthy of its own reference card. The basics of Seam security will be covered here which will address most use-cases and will allow you to get up-and-running quickly.

The Security Namespace

Security Namespace URI

http://jboss.com/products/seam/security

Security Namespace XSD

http://jboss.com/products/seam/security-2.1.xsd

The security namespace provides the hooks necessary to customize Seam security to fit your application needs whether you intend to use LDAP, a relational database, or any other custom authentication/authorization scheme.

Security Namespace Elements

Security Namespace Diagram

Security Namespace Diagram

ElementDescription<security:identity>Configures the application-specific authentication implementation for the Seam Identity component. The IdentityManager is used for authentication by default.<security:identity-manager>Configures the management of a Seam application’s users and roles for a type of identity store (database, LDAP, etc). The JpaIdentityStore is the default.<security:ldap-identity-store>Declares an identity store that allows users and roles to be stored inside an LDAP directory.<security:jpa-identity-store>Declares an identity store that allows users and roles to be stored inside a relational database.<security:permission-manager>Configures a PermissionManager instance for management of persistent permissions which requires a PermissionStore instance. <security:persistent-permission-resolver>Allows configuration of a custom permission store. A permission store can be implemented by implementing the PermissionStore interface. <security:rule-based-permission-resolver>Allows the Drools rule base name to be specified when rule-based permissions are in use.<security:jpa-permission-store>PermissionStore implementation allowing user and role permissions to be stored and retrieved as JPA entities.Security Namespace Example

The JpaIdentityStore component provided by Seam 2.1 makes it simple to store users and roles inside a relational database.

18
1
​
2
<components
3
        xmlns="http://jboss.com/products/seam/components"
4
        xmlns:drools="http://jboss.com/products/seam/drools"
5
        xmlns:security="http://jboss.com/products/seam/security"
6
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
7
        xsi:schemaLocation=
8
                "http://jboss.com/products/seam/security
9
                http://jboss.com/products/seam/security-2.1.xsd
10
                http://jboss.com/products/seam/drools
11
                http://jboss.com/products/seam/drools-2.0.xsd
12
                http://jboss.com/products/seam/components
13
                http://jboss.com/products/seam/components-2.1.xsd">
14
<security:jpa-identity-store
15
user-class="org.jboss.seam.example.booking.MemberAccount"
16
role-class="org.jboss.seam.example.booking.MemberRole" />
17
... ...
18
​
Above we need not configure the IdentityManager as the JpaIdentityStore is assumed by default.

Securing your Application

Seam makes it easy to declare access constraints on web pages, UI components, and Java methods via tags, annotations, and JSF Expression Language (EL) expressions. Through this declarative approach Seam provides you with the ability to easily achieve a layered approach to security.

Security Annotations

AnnotationUseDescription@RestrictType, MethodAllows a component to be secured either at the method or the class level through evaluation of an Expression Language (EL) expression.@ReadMethod, ParameterDeclares a type-safe permission check to determine whether the current user has read permission for the specified class.@UpdateMethod, ParameterDeclares a type-safe permission check to determine whether the current user has update permission for the specified class.@InsertMethod, ParameterDeclares a type-safe permission check to determine whether the current user has insert permission for the specified class.@DeleteMethod, ParameterDeclares a type-safe permission check to determine whether the current user has delete permission for the specified class.@PermissionCheckAnnotationDeclares a custom security annotation for performing type-safe permission checks where the required permission is the lowercase representation of the annotation name.@RoleCheckAnnotationDeclares a custom security annotation for performing type-safe role checks where the required role is the lower-case representation of the annotation name.

Security Expression Language (EL) Functions

These functions provide convenience for invoking role or permission checks through Expression Language (EL). This can be useful in your Facelets pages, in pages.xml, or in using the @Restrict annotation to provide security restrictions.

FunctionDescription#{s:hasRole(roleName)}Expression Language (EL) function that invokes the hasRole method on the Identity component. Returns true if the current user has the specified role.#{s:hasPermission(target, action)}Expression Language (EL) function that invokes the hasPermission method on the Identity component. Delegates the call to the configured PermissionResolver.

Seam Distribution Security Examples

The following examples are distributed with Seam and provide great resources for configuring your application.

ExampleDirectoryDescriptionSeam Bookingexamples/bookingDemonstrates the most basic authentication through use of an authenticate-method.Seam Spaceexamples/seamspaceDemonstrates use of rule-based-permission-resolver, jpa-identity-store, and jpa-permission-store.

Application Framework

The Seam CRUD application framework essentially provides prepackaged Data Access Objects (DAOs). DAOs are highly repetitive as the DAOs for each entity class are largely the same. They are ideal for code reuse. Seam provides an application framework with built-in generic DAO components. You can develop simple CRUD web applications in Seam without writing a single line of Java "business logic" code.

The Framework Namespace

Framework Namespace URI

http://jboss.com/products/seam/framework

Framework Namespace XSD

http://jboss.com/products/seam/framework-2.1.xsd

The framework namespace configures components found in the org.jboss.seam.framework package.

Framework Namespace Diagram

Framework Namespace Diagram

Framework Namespace Elements

ElementDescription<framework:entity-query>Configures an EntityQuery controller instance for executing JPA queries.<framework:entity-home>Configures an EntityHome controller instance for managing JPA entities. <framework:hibernate-entity-query>Configures a HibernateQuery controller instance for executing Hibernate queries.<framework:hibernate-entity-home>Configures a HibernateEntityHome controller instance for managing Hibernate entities.<framework:new-instance>Declares the new instance managed by a home controller.<framework:ejbql>Declares the new instance managed by a home controller.<framework:order>Defines the order-by property for a Query instance.<framework:restrictions>Defines the where clause of a Query instance.<framework:group-by>Defines the group-by clause for a Query instance.<framework:created-message>A status message added when a Home controller creates a new entity instance.<framework:updated-message>A status message added when the Home controller updates an entity instance.<framework:deleted-message>A status message added when the Home controller deletes an entity instance.Framework Namespace Example

In the booking example we could use an EntityHome instance to manage retrieval of the Hotel entity. The configuration below achieves this:

29
1
​
2
<?xml version="1.0" encoding="UTF-8"?>
3
<components xmlns=
4
        "http://jboss.com/products/seam/components"
5
        xmlns:persistence=
6
        "http://jboss.com/products/seam/persistence"
7
        xmlns:framework="http://jboss.com/products/seam/framework"
8
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
9
        xsi:schemaLocation=
10
        "http://jboss.com/product s/seam/framework
11
        http://jboss.com/products/seam/framework-2.1.xsd
12
        http://jboss.com/products/seam/components
13
        http://jboss.com/products/seam/components-2.1.xsd">
14
... ...
15
<persistence:managed-persistence-context name="em"
16
        auto-create="true"persistence-unit-jndi-name=
17
                "java:/EMFactories/bookingEntityManagerFactory"/>
18
<factory name="hotel"
19
        value="#{hotelHome.instance}"
20
        scope="stateless"
21
        auto-create="true"/>
22
<framework:entity-home name="hotelHome"
23
        entity-class="com.jboss.seam.booking.Hotel"
24
        scope="conversation" entity-manager="#{em}"
25
        auto-create="true">
26
        <framework:id>#{hotelId}</framework:id>
27
</framework:entity-home>
28
... ...
29
​
When a hotel is requested for injection or through Expression Language (EL) the hotelHome will be invoked to retrieve the hotel based on the current hotelId. This of course requires that the requested hotelId be made available in the current context. This can easily be achieved through use of a request parameter or outjection.

Seam Distribution Framework Examples

The following examples are distributed with Seam and provide great resources for configuring your application.

ExampleDirectoryDescriptionSeam Payexamples/seampayDemonstrates use of entity-query and entityhome elements.DVD Storeexamples/dvdstoreDemonstrates use of entity-query and entityhome elements.Contact Listexamples/contactlistDemonstrates use of entity-query and entityhome with embedded namespace elements. Also demonstrates use of restrictions.

Like This Refcard? Read More From DZone

related article thumbnail

DZone Article

Flex for J2EE Developers: The Case for Granite Data Services
related article thumbnail

DZone Article

Cassandra Indexing: The Good, the Bad and the Ugly
related article thumbnail

DZone Article

Enhancing Business Decision-Making Through Advanced Data Visualization Techniques
related article thumbnail

DZone Article

Event Driven Architecture (EDA) - Optimizer or Complicator
related refcard thumbnail

Free DZone Refcard

Java Application Containerization and Deployment
related refcard thumbnail

Free DZone Refcard

Introduction to Cloud-Native Java
related refcard thumbnail

Free DZone Refcard

Java 15
related refcard thumbnail

Free DZone Refcard

Java 14

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: