Thursday, November 02, 2006

JCA Connector for SSH and SFTP

By Sandrick Melbouci

The Enterprise Architecture Integration (EAI) provides a common framework for integrating incompatible systems running on different platforms. Many legacy applications and custom databases are still being used and run well that there is no need to re-invent the wheel. The aim of EAI is to reduce the complexity of the IT infrastructure and improve reliability, scalability and flexibility.

This article provide a brief description of a technology that is a key in integrating the databases and legacy systems with J2EE technology. Java 1.4 came with JCA 1.5 (Java Connector Architecture) that provide the standard mechanism to store, retrieve data from EIS (Enterprise Information System). To understand how JCA fits into EAI, refer to Connect the Enterprise with JCA.

Why JCA?
J2EE container is responsible for managing the security, threading, resource pooling and so on. In order to ensure the control over their functions, the container put some restrictions on components it manages such as EJB and servlets.
One of the restrictions is on EJB and IOs in general. An EJB should not manage a file descriptors (Sockets or Files). The communication with EIS is done through Sockets. Sockets are the standard low level communication primitives that appeared in early 1970's for Unix systems. The Sockets are not serializable therefore, EJB cannot passivate them neither the servlet can put them in session. In distributed environment, EJB are distributed at runtime running on separate JVM or machines. More information about EJB restrictions may be found at EJB Restrictions .
But EJB should find a way to communicate with databases and other EIS system. JCA provides the solution where the JCA handles the low level connections with EIS and return a Handle for the connection to the J2EE middle tier components.

Before we start the implementation of a Resource Adapter to provide SSH and Secure FTP functionalities, let's list the main JCA components:
  • System contracts
  • Client API
  • Resource adapter module
System contracts
System contracts define the connection between the application server and the EIS. The EIS side of the system contract is implemented by a resource adapter
-- a system-level software driver specific to the EIS. The application server and the resource adapter collaborate by means of the system contract to provide secure, robust, scalable access to the EIS.
Three types of system contracts are defined:
The connection management contract enables physical connections to the EIS and provides a mechanism for the application server to pool those connections.

The transaction management contract supports access to an EIS in a transactional context. Transactions can be managed by the application server, providing transactions that incorporate other resources besides the EIS, or they can be internal to the EIS resource manager, in which case no transaction manager is required.

The security contract supports secure access to the EIS. How system contracts are implemented on each side (application server and resource adapter) is not specified by JCA; they can be implemented as each vendor sees fit.

Client API
The second element of JCA is the client API. The API can be specific to the resource adapter or it can be the standard Common Client Interface (CCI) as defined by JCA. The CCI is meant to be used by vendors to provide integration tools and frameworks, making it easier for developers to access enterprise systems. It is recommended (but not mandated) that the resource adapter make use of the CCI.
Resource adapter module
The resource adapter module contains all of the elements necessary to provide EIS connectivity to applications. Specifically, the resource adapter module includes the following components:
- The Java classes and interfaces that implement the resource adapter
- Any utility Java classes required by the resource adapter
- Any EIS-specific platform-dependent native libraries
- The deployment descriptor
Application servers make use of the deployment descriptor supplied with a resource adapter to configure it to a specific operational environment.

Handling of Connections
An application component accesses the resource adapter through ConnectionFactory and Connection interfaces, which are provided by the resource adapter implementer. These interfaces can be CCI interfaces (javax.resource.cci.ConnectionFactory and javax.resource.cci.Connection) or they can be specific to the resource adapter. The classes that implement these interfaces are also provided with the resource adapter.
The connection factory is obtained through the Java Naming and Directory Interface (JNDI) so that the application need have no knowledge of the underlying implementation class. Once the connection factory is retrieved, a connection is obtained from the connection factory through the getConnection() method. At least one getConnection() method must be provided by the connection factory, though more may be provided. It is important to note that a Connection is an application-level handle to an underlying physical connection to the EIS, represented by a ManagedConnection. Once the application component is finished with the connection, it calls the close() method on the connection. A resource adapter is required to provide a method on the connection to close the connection. This method must delegate the close to the ManagedConnect ion that created the connection handle. Closing a connection handle should not close the physical connection to the EIS.

Managing Connections
The getConnection() method in the connection factory does not actually create a connection;
it calls the allocateConnection() method on its associated ConnectionManager.
The ConnectionManager interface is implemented by the application server.
It is associated with a connection factory in an implementation-specific manner when the
connection factory is instantiated. The call to the ConnectionManager allows the application
server to "hook in" to the resource adapter functionality to provide pooling, transaction,
and security services. A ConnectionRequestInfo object may be passed to allocateConnection()
to pass connection request-specific information.

The ConnectionManager, in turn, calls on a ManagedConnection to obtain the connection
handle. The connection handle is passed back through the ConnectionManager to the connection
factory and on to the application component.

Connection Pooling

The resource adapter provides a class that implements the ManagedConnectionFactory interface. The ManagedConnectionFactory class acts as a factory for both connection factory instances and ManagedConnection instances. When the application server needs to create a connection factory, it calls the createConnectionFactory() method, passing in an instance of ConnectionManager; this is the instance that is called when the application component calls getConnection() on the connection factory, as discussed previously.

The application server uses one of two ManagedConnectionFactory methods to create or request managed connections. When the server requires a new instance of ManagedConnection, it calls the createManagedConnection() method. When the server wants to re-use an existing ManagedConnection, it calls the matchManagedConnections() method. To find the right match, the server passes in a set of ManagedConnections that could possibly meet the criteria of the requested connection, along with information about the desired connection type. Internally, the matchManagedConnection() method compares this information with the candidate set to determine if a match can be made. If so, it returns the matching ManagedConnection; if not, it returns null.

So far we have talked about the outbound. JCA also supports the inflow and is implemented using ActivationSpec and Inbound Message Driven Bean.

The following depicts the design of the SSH adapter.


The code can be found at http://txconnect.sf.net


By Sadi Melbouci

References:
Connect the Enterprise with JCA: http://www.javaworld.com/javaworld/jw-11-2001/jw-1121-jca.html

Wednesday, October 18, 2006

JBOSS LDAP Integration

By Sandrick Melbouci

This article provide a prototype of integration of J2EE applications such as Servlets/JSPs, EJBs, MDBs with LDAP (Lightweight Directory Access Protocol) for application authorization and authentication. This article identifies some key interfaces within JBoss and any J2EE container compliant application server that can be configured to provide a secured access. We will provide a declarative LDAP security model in such a way you can configure it at runtime.

Few things to take in consideration:
- J2EE uses the same authorization model for both web-based components (servlets and JSPs) and enterprise components (EJBs). The specification requires transparent propagation of security credentials within the J2EE environment, so that once a user has authenticated to any J2EE component, the same security information is used by all other components.
- J2EE application programming model insulates developers from mechanism-specific implementation details of application security. J2EE provides this insulation in a way that enhances the portability of applications, allowing them to be deployed in diverse security environments.
- In order to integrate authorization into an unknown authentication mechanism, J2EE specifications define a simple role-based security model for EJBs and Web components. the specification defines a number of terms about security:
- A realm is the J2EE term for the security policy domain that is a definition of the way in which a user is authenticated. In its simplest form, a realm is a list of users and a mechanism for authenticating those users. Basic HTTP authentication is known as the HTTP realm; a public key certificate (PKC) authentication such as SSL is a different realm.
- A principal is the name of a user within the authentication realm. Although the J2EE specification does not require the principal name to be the same as the user's login name, most (if not all) J2EE implementations use the username as the principal name.
- A role is a definition of the way a user will use the system. Typical roles will be user, administrator, manager, developer, researcher, and so on. Outside the J2EE domain, a role is usually implemented by assigning users to one or more authentication groups or granting privileges to user accounts.
- A role reference is the name of a role used within the code of a J2EE application. As part of the J2EE application environment definition (known as the deployment descriptor), every role reference must be mapped onto a real role. The decoupling of the coded role reference from the actual role helps improve portability of a J2EE component.

Before we define the LDAP schema (LDIF file), the following are the LDAP common terms you need to know in order to understand this configuration.
To configure LDAP, refer to LDAP Admin guide

DN: Distinguished Name
A distinguished name uniquely identifies an entry in the directory. A DN is made up of “relative” distinguished names of the entry and each of the entry's parent entries, up to the root of the directory tree. These names are usually separated by commas and optional spaces. For example: 'uid=JohnDoe, ou=People, dc=company, dc=com'.
ObjectClass
An objectclass is a formal definition of a specific kind of objects that can be stored in the directory. An objectclass is a distinct, named set of attributes that represents something concrete, such as a user, a computer, or an application.
LDAP URL
LDAP URL is a string that specifies the location of an LDAP resource. An LDAP URL consists of server host and port, search scope, baseDN, filter, attributes and extensions.
Schema
An LDAP schema defines a set or rules that specifies the types of objects that a directory may contain and the required and optional attributes that entries of different types should have.

More details can be found in LDAP Admin guide.

Now, Let's define our LDAP schema to support the J2EE role-based security. Below is the LDAP structure that defines our LDAP tree:

com
---company
------------People
-------------------admin
-------------------demo
------------Roles
------------------Administrator
------------------Users


This structure is orgonized into 2 main structures, People and Roles. People contain the users and Roles groups the users into group of roles. A role is defined above, it provides the permission level for a user.

The following is the LDIF schema that also defines our LDAP entries.


dn: dc=company,dc=com
dc: company
objectClass: top
objectClass: dcObject
objectClass: domain

dn: ou=Roles,dc=company,dc=com
ou: Roles
objectClass: top
objectClass: organizationalUnit

dn: ou=People,dc=company,dc=com
ou: People
objectClass: top
objectClass: organizationalUnit

dn: uid=demo,ou=People,dc=conpany,dc=com
uid: demo
objectclass: person
objectclass: inetOrgPerson
cn: demo
sn: demo

dn: uid=admin,ou=People,dc=company,dc=com
uid: admin
objectClass: person
objectClass: inetOrgPerson
cn: Admin
sn: admin

dn: cn=Administrator,ou=Roles,dc=company,dc=com
cn: Admin
objectClass: top
objectClass: groupOfNames
member: uid=admin,ou=People,dc=company,dc=com

dn: cn=Users,ou=Roles,dc=company,dc=com
cn:Users
objectClass: top
objectClass: groupOfNames
member: uid=demo,ou=People,dc=company,dc=com
member: uid=admin,ou=People,dc=company,dc=com


Save this schema into a file called entries.ldif

You can load this file by running the command :
ldapadd -f entries.ldif -x -D "cn=Manager,dc=company,dc=com" -w secret

Manager is administrator of the LDAP

Check that your entries are loaded by executing the following command:
ldapsearch -x -b 'dc=company,dc=com' '(objectclass=*)'

We are done with LDAP.

This example has been tested with OpenLDAP. It should work with any other LDAP provider.

Now, we need to tell JBoss how to authorize and authenticate against the LDAP entries we have created.
For our example, we will secure the JBoss jmx-console. Similar thing can be applied to any web application.

We need to modify web.xml and add the security constraint.

web.xml

<security-constraint>
<web-resource-collection>
<web-resource-name>HtmlAdaptor</web-resource-name>
<description>An example security config that only allows users with the
role Admin to access the HTML JMX console web application
</description>
<url-pattern>/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>Administrator</role-name>
</auth-constraint>
</security-constraint>


<security-role>
Administrator
</security-role>


As you can see, we wanted only the users having a role "admin"to access the console.


Now we will tell JBoss what security scheme to use. To do so, we need to add security-domain element into jboss-web.xml. We have called our security scheme "AuthPolicy".

jboss-web.xml
<jboss-web>
<security-domain>java:/jaas/AuthPolicy</security-domain>
</jboss-web>


The "AuthPolicy" security policy shall be defined in login-config.xml located in :
$JBOSS_HOME/server/{config}/conf .
{config} can be one minimal, all, default or you can define your own.


Now let's define an entry in the login-config.xml. Remember, we will to define the LDAP URL defined above.

login-config.xml

<application-policy name="AuthPolicy">
<authentication>
<login-module code="org.jboss.security.auth.spi.LdapExtLoginModule" flag="required" >
<module-option name="java.naming.factory.initial">com.sun.jndi.ldap.LdapCtxFactory</module-option>
<module-option name="java.naming.provider.url">ldap://localhost:389/</module-option>
<module-option name="java.naming.security.authentication">simple</module-option>
<module-option name="baseCtxDN">ou=People,dc=company,dc=com</module-option>
<module-option name="baseFilter">(uid={0})</module-option>
<module-option name="roleFilter">(member={1})</module-option>
<module-option name="rolesCtxDN">ou=Roles,dc=company,dc=com</module-option>
<module-option name="roleAttributeID">cn</module-option>
<module-option name="roleAttributeIsDN">false</module-option>
</login-module>
</authentication>
</application-policy>


I highlighted some attribute in red. These attribute should be mapped to your LDAP schema definition.

See it in action. Fire up JBoss, and then go to: http://localhost:8080/jmx-console.

References:
Security Trail in the Java tutorial, http://java.sun.com/docs/books/tutorial/security/index.html
Core Security Patterns, http://www.informit.com/bookstore/product.asp?isbn=0131463071&rl=1
JBoss Security Model, http://www.huihoo.com/jboss/online_manual/3.0/ch13s78.html
JBoss Login Module, http://wiki.jboss.org/wiki/Wiki.jsp?page=LdapLoginModule

Saturday, October 07, 2006

JAXB and xmlBeans. Pros ad cons

By Sandrick Melbouci

I would like to address some differences between JAXB and xmlBeans in processing of XML documents.
JAXB is a part of JavaEE standards and provides a convenient way to bind an XML schema to a set of Java classes. This allowsh an easy way to process data in java technology without having to understand all the ins and outs of te XML technology.
JAXB 2.0, available in in the open-source Java EE 5-compliant application server at Glassfish project is part of the new integrated stack for Web services development. This new version of JAXB includes all the data binding functionality in a single package, while the previous Web services development stack (in Java Web Services Developer Pack 1.6 and previous versions) carried out some data binding in the JAX-RPC 1.x package and some in the JAXB 1.x package. With the integrated stack comprising JAX-WS 2.0, JAXB 2.0, and SAAJ 1.3, the Web services description, data binding, and SOAP attachment processing functionality are more logically architected, enabling you to develop Web services, middle tier and Web applications more easily.

XmlBeans was originally developed by BEA Systems, it is now an open source project. xmlBeans provide similar functionality then JAXB but may require some good knowledge of XML technology.
Prior to this technologies, one way to proccess an XML document, perhaps the most typical way, is through parsers Simple API for XML (SAX) or the Document Object Model (DOM). Both of these parsers are provided by
Java API for XML Processing (JAXP). The developer writes code to invoke a SAX or DOM parser through the JAXP API to parse an XML document -- that is, scan the document and logically break it up into discrete pieces. The parsed content is then made available to the application. In the SAX approach, the parser starts at the beginning of the document and passes each piece of the document to the application in the sequence it finds it. Nothing is saved in memory. The application can take action on the data as it gets it from the parser, but it can't do any in-memory manipulation of the data. For example, it can't update the data in memory and return the updated data to the XML file.
In the DOM approach, the parser creates a tree of objects that represents the content and organization of data in the document. In this case, the tree exists in memory. The application can then navigate through the tree to access the data it needs, and if appropriate, manipulate it.

Now we have 2 technologies that do convert the XML document into java classes. You manipulate the Java object instead. However, JAXB and XmlBeans accomplish the marshalling and unmarshalling of XML document quite differently.

XMLBeans processes an XML document without going through a conversion into Java where integrity of the document can be lost. XMLBeans creates a cursor that can move through the XML document. You can access any element of the document, including comments and schema information because the document is kept in full fidelity. It also creates the opportunity to execute an XQuery on the document. XMLBeans also gives a strongly typed access to the document and a more generic type of access, similar to a reflection API. However, it doesn't always work the way you want it. Many time an error like "Invalid XML character 0x0" by processing the same document where the processing was previously successful.
More importantly, like I previously mentioned it, Using Xml Beans requires you to know XML very well and also SAX and DOM.

JAXB is binded to the XML schema, the first release of JAXB did not answer the development community, mainly because it did not support all XML schema features and only supported DTDs. The first JAXB version suffered mainly of 3 major issues: it prevented support of type substitution and related features, it prevented support for extensibility and versioning, it failed to provide readable bindings in many cases.
JAXB 2.0 was enhanced to fill up the gaps and provides full XML schema support, Java to XML Schema mapping, schema evolution and portability. For ease of development, JAXB has leveraged J2SE 5.0 features: generics for type safe collections enum type for binding of simple type with enumeration facets better support for XML schema types using datatypes in JAXP 1.3 leveraging JAXP 1.3 validation for smaller footprint more compact binding based on constraining facets defined in schema.
JAXB architecture was re-designed to assist with schema evolution and invalid XML content. JAXB has introduced a flexible unmarshalling mode that allows for unmarshalling of invalid XML content. Optional unmarshal time validation can be used by an application to detect invalid XML content and decide whether to terminate unmarshalling.

Let's take an example to illustrate the basic usage of both technologies:

Let say we have a schema:

<xs:complextype name="promotion">
<xs:sequence>
<xs:element name="discount" type="xs:string">
<xs:element name="None" type="xs:string">
</xs:sequence>
</xs:complextype>



With XmlBeans:
PromotionDocument pdoc =
PromotionDocument.Factory.parse(new File (xmlFile));

// Get and print pieces of the XML instance.
Promotion p = pdoc.getPromotion;
with JAXB:
JAXBContext jc = JAXBContext.newInstance("test.jaxb");
Unmarshaller unmarshaller = jc.createUnmarshaller();
Promotion p = (Promotion) unmarshaller(new File(xmlFile) );


The choice between these technology depends on the performance you want to get
and the use of XML features. I will go with XML Beans if:
I would like to access the XML document itself and use XQueries ...etc.
I would like Native DOM representation at the expense of performance and memory management.
Access schema metadata
Use it older JDK versions. 1.4 or older.


If you are looking for simplicity to convert an XML document <--> Java classes,
JAXB is your choice.
If you want binding customization, JAXB allows these declarations to be made "inline" -- that is, in the schema, or in a separate document.
JAXB uses memory efficiently: The tree of content objects produced through JAXB tends
can be more efficient in terms of memory use than DOM-based trees.
JAXB allows you to access XML data without having to unmarshal it. Once a schema is bound you can use the ObjectFactory methods to create the objects and then use set methods in the generated objects to create content.

References:
JAXB Architecture, http://java.sun.com/webservices/jaxb
JSR 31, JAXB specs, http://jcp.org/en/jsr/detail?id=031
XMLBeans, http://xmlbeans.apache.org/
XMLBeans Architecture, http://dev2dev.bea.com/xml/xmlbeans.html