The Source for Java Technology Collaboration
User: Password:



Masoud Kalali's Blog

Community: Java Enterprise Archives


How to Secure GlassFish installation, Part II

Posted by kalali on February 17, 2008 at 12:34 PM | Permalink | Comments (0)

In order to secure the application server you need to secure its communication ways with outside world, It means you will need to secure all ports and listeners.

There are 3 kind of listeners in Glassfish application server that you will need to take care of them

First of all make sure that you secured the administration listener, make sure that you have enabled Security for administrator listener and set an specific IP address for it to listen on. Usually we are not going to use administration console from outside of the internal network, so let it listen only on interfaces that you need it to listen perhaps the interface that connect the server to your LAN. In order to do this, open administration console and navigate to:


Configuration> HTTP Service> HTTP Listeners> admin-listener

Change the Network Address as appropriated, check the Security check box, and in the SSL Tab enable Client Authentication, in order to find out how you should use Client Certificate, take a look at my previous posts about SSL and securing GlassFish Application Server. You have two other Http listeners to take care of, so make sure that you change their Network Address and enable the Security facilities if required

There is another listener which you need to take care of, It is your IIOP listener. IIOP listener let you create a context to lookup into your JNDI, etc. In order to configure the IIOP listeners you should navigate to:


Configuration> ORB> IIOP Listeners

Here you can see that there are 3 different listeners already created and configure for different purposes. You should not allow the first non-secure listener (orb-listener-1) to listen over a public network as there is no authentication or transfer layer security for this listener, but the second one (SSL) have transport layer security and the third one (SSL_MUTUALAUTH) has mutual authentication which guarantee that listener will only process request come after a client cert authentication. make sure that you configure the listeners to listen on correct Network address and remove or disable the listeners those that you do not need. You can disable a listener by looking at listener details page which provides a check box for it.

Another listener which you need to take care of is your JMX connector listener, You can view and edit its configuration by navigating to:


Configuration> Admin Service> system

Here you are able to change the realm that this listener use to authenticate the users that are trying to connect to JMX listener, you can change the realm to an specific realm which you have made only for JMX users or let it use you administration realm. You can change the Network Address that this listener is using along with enabling the SSL and Client Cert Authentication in order to secure the data transfer and guarantee that only users with correct digital certification can use your JMX connector to control the application server

PS: All of the listeners that you can configure in your administration console allows you to have Mutual Authentication (Client Cert Authentication) which ensure that both parties have verify-able certifications. This certifications can come from well known providers like VeriSign or your own CA. on the other hand all listeners allows you to specify an specific alias for them, which means that each listener mutual authentication can be configured completely independent from other listeners, for example you can have two alias one for administration console and one for JMX connector in order to prevent JMX users to connect to administration console.

For more information you can take a look at my older posts related to this matter:






Four open source Java application servers compared

Posted by kalali on December 11, 2007 at 01:11 PM | Permalink | Comments (7)

I was looking at feeds that my email client fetched during the day and I find am interesting one which lead me to an article written by Jonathan Campbell. Article can be found at http://www.javaworld.com/javaworld/jw-12-2007/jw-12-appservers.html

Jonathan compared 3 different application server/ servlet container by thier support of Java EE 5 and some other factors. article explained about each feature that he compared application servers based on it. Jonathan did not included GlassFish in his review of "open source Java application servers" and only included 3 application servers/ Servlet containers including Tomcat, Jboss and Geronimo. :-), So I thought I should include some facts here in order to make the comparison fair to all parties.

Including Glassfish into Jonathan matrix will give us the following table: *Notice*

Feature JBoss 4.2 Geronimo 2 Tomcat 6 GlassFish 2
Java EE 5 compliance Partial Yes No Yes
EJB 3.0 capable Yes Yes Available Yes
JSP 2.1 and 2.5 capable Yes Yes Yes Yes
JavaServer Faces 1.2 support Yes Yes Available Yes
Custom plug-in support Yes Yes No ?
Business-rules engine support Available Available Available Available
Hibernate 3.x support Yes Available Available Yes, based on below description
JBoss Seam support Yes Yes Available Yes
Clustering support Yes Yes Partial Yes
Eclipse IDE connector support Yes Yes Yes Yes

Following descriptions further explain some of what Glassfish can provides in relation of the above table

  • GlassFish fully support Java EE 5 with all its related JSRs like JSP 2.1 (JSR 245), Servlet 2.5(154), EJB 3.0(JSR 245), etc.
  • GlassFish support clustering and cluster management out of the box, a cluster can be configured from both CLI and Administration console.
  • GlassFish administration console allows you to configure your load balancer :-), for example you can configure a Sun Java Web Server which works as load balancer to add or add/ remove an instance from its list of servers, either manually or automatically if a new node joined the cluster or removed from the cluster
  • GlassFish allows you to manage resources for entire cluster at once instead of applying them for each instance, for example you can deploy a web application into a cluster of 10 instances instead of deploying it seperately for each instance.
  • GlassFish has a very wide array documentation both from Sun Microsystems (for free) and from GlassFish community.
  • GlassFish installation is as easy as executing 2 commands.
  • Deploying applications into GlassFish or even an entire cluster of glassfish instances is just 2 clicks away.
  • Quality of GlassFish components is out of any question, Metro is well known for supporting new WS-* standards, EJB support uses Toplink Essentials, MQ server is Sun open sourced MQ, etc.
  • GlassFish has very good interoperability with some other open source projects like, OpenESB and OpenSSO which allows you to have what you need to kick start your J2EE application without looking at any additional configuration.
  • Certainly performance is something which everyone should have in mind before considering other feaures, take a look at http://www.spec.org/jAppServer2004/results/res2007q3/jAppServer2004-20070703-00073.html and http://weblogs.java.net/blog/sdo/archive/2007/07/sjsas_91_glassf.html to find out more about how much capable GlassFish is.
  • GlassFish has connectors for both Eclipse and Netbeans, although other mentioned servers have a connector in Netbeans and Eclipse.
  • Seam support is available from GlassFish 1 upward.
  • Business rule engine support is available from OpenESB project integration.
  • About hibernate support, I cannot understand whether Jonathan means to use Hibernate as a persistence provider or plainly as an ORM, by the way both of this ?features? are available for GlassFish users.
  • GlassFish has an Update center, which allows you to update your application server from a remote repository.
  • GlassFish runs on all mentioned platforms, from Windows to AIX (Glasdfish 2 update 1 runs on AIX) and there is no restriction for you to run it on your platform of choice.

Mentioned items are in relation to what orginal article tried to compare. GlassFish can be used by a ROR developer by its integration with first class ROR IDE (Netbeans 6), It can serve you VOIP and SIP requirement by means of sailfin,etc. Any user with any kind of requirement will find GlassFish a suitable application server.

Although Jonathan did not mentioned GlassFish directly, but he gives his opinion by writing:In my experience commercial application servers have more bugs than the open source servers compared in this article, and they are more difficult to install. Deployment can also be an issue -- at least with the recent version of Sun's Java Application Server. The article could be more complete if Jonathan included GlassFish in his comparsion chart and at then end he could write that GlassFish has problematic deployment procedure

An statement which looks odd to me is: In my experience commercial application servers have more bugs than the open source servers compared in this article, and they are more difficult to install., Althogh it will be a complex procedure to setup a Cluser of Websphere (as a commercial application servers ) using websphere XD, Object Grid, and other available packages that faciliate enterprise scale deployment of Websphere, but WebSphere has a decent performance and reliability which is very hard to deny.

Notice: Some parts of this table taken from Jonathan Campbell article published by javaworld and is available at http://www.javaworld.com/javaworld/jw-12-2007/jw-12-appservers.html






How to Secure GlassFish installation.

Posted by kalali on December 05, 2007 at 01:49 PM | Permalink | Comments (0)

It is some days that I saw some posts about securing Glassfish in production environment, so I thought I write some of my experience here to let other secure the glassfish easier. There are some basic items that you will need to relay on in order to have a secure Glassfish installation.

  1. secure access to administration console, both web based and CLI.
  2. secure all ports and listeners that application server uses to interact with outside applications.
  3. secure your environment from GlassFish; Yes, glassfish can be evil if you have buggy software installed on you application server.
  4. secure your application server from the environment that it is operating on it.
  5. secure glassfish directories in order to prevent any accidental changes, use, etc in glassfish configuration files.
  6. Take care of all logging if you are not going to secure Glassfish on the file system.
  7. tips and tricks which are not mentioned in the above sections.
  8. firewalls, network security, clustered environment tips and tricks

But how you can do these, I will explain each item in as much details as I can begin with securing your administration console. As you know administration console is the main interaction point with an application server, however must of application servers let you perform all changes from a CLI or direct editing of server.xml, domain.xml and so on. But Web based administration console is the most open to access part of application server, So let’s see how we can secure it:

You will need to change administration password from the default one, do it by using the following command in CLI when your application server is running.


change-admin-password

Using this command you can change your administration password both for CLI and Web based console. The output of the command may differ from version or profile to another version and profile but it will asks you to enter old and new password, in case that it asks to accept a certificate accept it, you will change it later.

Second thing that you should change is master-password, make sure that you stop your application server before issuing the command as it will not work when the as is running. Following command in asadmin console will do it for you. Default master password value is “changeit”


change-master-password

Now you are sure that your administration console and keystore files are protected using a new password which you know.

Its time to take a closer look at application server web based console protection, you need to make sure that you have most possible protection over your administration console by limiting access to it using firewalls and after that you can add another level of protection and transmission integrity by using a mutual authentication using Digital Certificate.

By changing the administration http listener to use an a digital certificate specific for administration console and changing its setting to use client-cert authentication or mutual authentication you can ensure that your administration console will only opens in a browser which has a digital certificate signed by a CA known to your administration listener.

This way you can be sure that only the guys with that specific digital certificate will have access to your admin console and the administrator will not fool by anyone to connect to a mock server. On the other hand you have full protection of SSL over your transmitted data. To learn how you can setup your own CA and add keys to glassfish keystore take a look at some older entry of my weblog. however those entry shows how you can use digital certificate when your AS uses jks files ant certDB files.




110x32_anim_v1.gif Locations of visitors to this page


How to have your Own CA and configure Glassfish and your clients for mutual authentication?, Part II

Posted by kalali on August 23, 2007 at 02:19 PM | Permalink | Comments (0)

How to have your Own CA and conf

In the second part of the series, you can see how we can utilize EJBCA to create certification for a client side application which will communicate with Glassfish server when Client cert authentication (Mutual Authentication) is enabled whether by changing the listener attributes or by describing it in the web-config.xml.

In order to create client certification we will need to perform following steps as described in 4 sections:

Section 1: Creating clients certification profile:
  • Go to https://localhost:8080/ejbca/ and select Administration.
  • Select Edit Certification profiles from the left side menu.
  • Enter a name for the profile and press add button. I choose Clients as the name.
  • From the list select Clients Item and press Edit button.
  • Now profile edit page will open change the attribute as follow:
    • for Key Usage  you should select at least Digital Signature and Key Encypherment.
    • From  Extended Key Usage select Client Authentication
  • press save button.
Section 2: Create servers end entities profile:

Now you have create a profile which in next sections you can create certifications which will comply with it. Now we will need to create an End Entity Profile so follow these steps to create it.

  • From the left side menu click on  edit end entities profile .
  • Enter ClientsProfile as profile name and press add button.
  • From the list select ClientsProfile and press Edit End Entity Profile button.
  • Enter a user name and a password for the profile, I choose cAdmin/ cAdminAdmin.
  • Enter the common name
  • From the list of Available Certificate Profiles  select Clients which we made in last step.
  • select JKS as default token.
  • click Save

Now we are reaching an step in which we will create the real certificate that client will use to prove its identity and initiate SSL enabled session. To create the certificate perform following steps:

Section 3: Create Client certification
  • From the left side menu select add end entity link.
  • Select ClientsProfile as End Entity Profile.
  • Enter all information as you like.
  • Select JKS as Token.
  • press add end entity button
Section 4: Use the certification in Client Application.

You are done, the certification is ready to be downloaded and used.

  • Go to https://localhost:8080/ejbca/  and select Certification Enrollment.
  • Select Manually for a Server
  • Enter user name and password which you have entered for end entity in previous step.
  • Click OK.

By pressing OK a JKS file will download to your computer.

Create two copies of the file and Rename them  to keystore.JKS and cacerts.jks. In order to create a SSL enabled client, either web service client or any type of socket client which need to use SSL you can follow one of the following path:

  • When you want to run your java application pass following parameter to JVM, it will ask JVM to use your cacerts.jks and keystore.jks during initialing SSL communication and authentication.
-Djavax.net.ssl.trustStore="Truststore_Location"    -Djavax.net.ssl.trustStorePassword="Truststore_Password"   -Djavax.net.ssl.keyStore ="Keystore_Location" -Djavax.net.ssl.keyStorePassword="Keystore_Password"
  • Second way is adding the same parameter to your JVM during execution of your application code. using this way you are not forced to pass parameter and disclose your key stores passwords.

System.getProperties.put("javax.net.ssl.trustStore","Truststore_Location");
System.getProperties.put("javax.net.ssl.trustStorePassword","Truststore_Password");
System.getProperties.put("javax.net.ssl.keyStore","Keystore_Location"); 
System.getProperties.put("javax.net.ssl.keyStorePassword","Keystore_Password");

Make sure that you are using correct location and password for your files, passwords are same as one you used to download the JKS files.

I should say again that you can explore and perhaps learn more about jks files, keys and certification by exploreing your stores, you can use jks file editor located at http://members.aon.at/bhuber14/nbm.html. Also if you are may find more cool key store editor in NetBeans Module Portal

For more information or maybe to find some of your questions answered you may take a look at:






How to have your Own CA and configure Glassfish and your clients for mutual authentication?

Posted by kalali on August 16, 2007 at 09:05 AM | Permalink | Comments (0)

How to have your Own CA and conf

One of the most repeated question in GlassFish mailing list is SSL, Certification, Mutual Authentication,.... In this Entry I will try to address some of this questions by giving an step by step guide for using EJBCA to issue certificate, use them in both glassfish and clients which connect to glassfish in some manner. clients like web browser, standalone java applications,...

There are several tutorial and blog entry about configuring glassfish to use some specific certification in order to perform server authentication for clients over SSL and each of those weblog is an invaluable source of information. In this blog entry and perhaps the next one I will address another concerns which some people has for their GlassFish and client security. Some times we are running an application within an enterprise and we need to have mutual authentication for every clients that connect to server so we will need to have one certification for client and another one for our glassfish server. both of this certification should be valid (issued by an already known CA within glassfish trust store and client trust store). For these two entries I assume that our client and server will just accept certification issued by our own CA which is based on EJBCA.

Before we start the main job you will need to download and install EJBCA from its web site, then you will need to install it according to its manual which you can find in documentation section. After you installed and could view EJBCA administration console then you can follow the rest of the entry.

 

In order to create server certification we will need to perform following steps as described in 4 sections:

Section 1: Creating servers certification profile:
  • Go to https://localhost:8080/ejbca/ and select Administration.
  • Select Edit Certification profiles from the left side menu.
  • Enter a name for the profile and press add button. I choose servers as the name.
  • From the list select servers Item and press Edit button.
  • Now profile edit page will open change the attribute as follow:
    • for Key Usage  you should select at least Digital Signature and Key Encypherment.
    • From  Extended Key Usage select Server Authentication
  • press save button.
Section 2: Create servers end entities profile:

Now you have create a profile which in next sections you can create certifications which will comply with it. Now we will need to create an End Entity Profile so follow these steps to create it.

  • From the left side menu click on  edit end entities profile .
  • Enter ServersProfile as profile name and press add button.
  • From the list select ServersProfile and press Edit End Entity Profile button.
  • Enter a user name and a password for the profile, I choose sAdmin/ sAdminAdmin.
  • Enter the common name
  • From the list of Available Certificate Profiles  select Servers which we made in last step.
  • select JKS as default token.
  • click Save

Now we are reaching an step in which we will create the real certificate that Glassfish will use  in its SSL enabled listener. To create the certificate perform following steps:

Section 3: Create server certification
  • From the left side menu select add end entity link.
  • Select ServersProfile as End Entity Profile.
  • Enter all information as you like but make sure that CN should be Exact and fully qualified name of your sever as will access it from clients, for example if you are going to access the serve as computer1.mydomain.com then the CN should be the same if you are going to access it as Comuter1 then the CN should be that.
  • Select JKS as Token.
  • press add end entity button
Section 4: Use the certification in Application Server.

You are done, the certification is ready to be downloaded and used.

  • Go to https://localhost:8080/ejbca/  and select Certification Enrollment.
  • Select Manually for a Server
  • enter user name and password which you have entered for end entity in previous step.
  • Click OK.

By pressing OK a JKS file will download to your computer.

  • Create two copies of the file and Rename them  to keystore.JKS and cacerts.jks.
  • Goto Glassfish/domains/domain1 (If domain 1 is the domain that you want to configure for SSL).
  • Make sure that application server is stopped by issuing the following command.
	Glassfish_home/bin/asadmin  stop-domain domain1	
  • Now we need to change the master password in order to let glassfish open our new cacert.jks and keystore.jks so perform following command.
	Glassfish_home/bin/asadmin  change-master-password  \\\Here you should write the password that you choosed in last step/// --savemasterpassword=true
  • Now Goto glassfish_home/domains/domain1/config and create a backup from cacert.jks and keystore.jks.
  • Copy files that we create in first step of this section to this folder (overwrite the original files).
  • Open domain.xml (it is in domain1/config folder) by a text editor and replace all s1as occurrences with CN name that you have choose in section 3.
  • Start the application server.

You are done, you application server should start normally, but you have some more steps before you complete the mutual authentication capability.

Section 5: Enabling mutual authentication for a listener.

Open application server administration console and from the left side menu select Configuration> HTTP Service> HTTP Listeners> http-listener-2, now you should check the Security check box and select SSL tab, now make sure that you have checked Client Authentication check box.

You are done, point your browser to https://computer1.mydomain.com:8181 you will see that this page will only open for the browser that you have imported EJBCA administration certification. it means that both server and client must prove their identity before they could communicate.

In next entry of this series I will demonstrate steps that you need to follow in order to create a stand alone web service client.

Make sure that you need to delete the private key of you server from cacerts.jks (it is not necessary by the way). Best way to explore you key stores is using keytool which you can find more information about it Here. Also if you are may find more cool key store editor in NetBeans Module Portal

For more information or maybe to find some of your questions answered you may take a look at:




How to have your Own CA and configure Glassfish and your clients for mutual authentication?

Posted by kalali on August 16, 2007 at 09:05 AM | Permalink | Comments (0)

How to have your Own CA and conf

One of the most repeated question in GlassFish mailing list is SSL, Certification, Mutual Authentication,.... In this Entry I will try to address some of this questions by giving an step by step guide for using EJBCA to issue certificate, use them in both glassfish and clients which connect to glassfish in some manner. clients like web browser, standalone java applications,...

There are several tutorial and blog entry about configuring glassfish to use some specific certification in order to perform server authentication for clients over SSL and each of those weblog is an invaluable source of information. In this blog entry and perhaps the next one I will address another concerns which some people has for their GlassFish and client security. Some times we are running an application within an enterprise and we need to have mutual authentication for every clients that connect to server so we will need to have one certification for client and another one for our glassfish server. both of this certification should be valid (issued by an already known CA within glassfish trust store and client trust store). For these two entries I assume that our client and server will just accept certification issued by our own CA which is based on EJBCA.

Before we start the main job you will need to download and install EJBCA from its web site, then you will need to install it according to its manual which you can find in documentation section. After you installed and could view EJBCA administration console then you can follow the rest of the entry.

 

In order to create server certification we will need to perform following steps as described in 4 sections:

Section 1: Creating servers certification profile:
  • Go to https://localhost:8080/ejbca/ and select Administration.
  • Select Edit Certification profiles from the left side menu.
  • Enter a name for the profile and press add button. I choose servers as the name.
  • From the list select servers Item and press Edit button.
  • Now profile edit page will open change the attribute as follow:
    • for Key Usage  you should select at least Digital Signature and Key Encypherment.
    • From  Extended Key Usage select Server Authentication
  • press save button.
Section 2: Create servers end entities profile:

Now you have create a profile which in next sections you can create certifications which will comply with it. Now we will need to create an End Entity Profile so follow these steps to create it.

  • From the left side menu click on  edit end entities profile .
  • Enter ServersProfile as profile name and press add button.
  • From the list select ServersProfile and press Edit End Entity Profile button.
  • Enter a user name and a password for the profile, I choose sAdmin/ sAdminAdmin.
  • Enter the common name
  • From the list of Available Certificate Profiles  select Servers which we made in last step.
  • select JKS as default token.
  • click Save

Now we are reaching an step in which we will create the real certificate that Glassfish will use  in its SSL enabled listener. To create the certificate perform following steps:

Section 3: Create server certification
  • From the left side menu select add end entity link.
  • Select ServersProfile as End Entity Profile.
  • Enter all information as you like but make sure that CN should be Exact and fully qualified name of your sever as will access it from clients, for example if you are going to access the serve as computer1.mydomain.com then the CN should be the same if you are going to access it as Comuter1 then the CN should be that.
  • Select JKS as Token.
  • press add end entity button
Section 4: Use the certification in Application Server.

You are done, the certification is ready to be downloaded and used.

  • Go to https://localhost:8080/ejbca/  and select Certification Enrollment.
  • Select Manually for a Server
  • enter user name and password which you have entered for end entity in previous step.
  • Click OK.

By pressing OK a JKS file will download to your computer.

  • Create two copies of the file and Rename them  to keystore.JKS and cacerts.jks.
  • Goto Glassfish/domains/domain1 (If domain 1 is the domain that you want to configure for SSL).
  • Make sure that application server is stopped by issuing the following command.
	Glassfish_home/bin/asadmin  stop-domain domain1	
  • Now we need to change the master password in order to let glassfish open our new cacert.jks and keystore.jks so perform following command.
	Glassfish_home/bin/asadmin  change-master-password  \\\Here you should write the password that you choosed in last step/// --savemasterpassword=true
  • Now Goto glassfish_home/domains/domain1/config and create a backup from cacert.jks and keystore.jks.
  • Copy files that we create in first step of this section to this folder (overwrite the original files).
  • Open domain.xml (it is in domain1/config folder) by a text editor and replace all s1as occurrences with CN name that you have choose in section 3.
  • Start the application server.

You are done, you application server should start normally, but you have some more steps before you complete the mutual authentication capability.

Section 5: Enabling mutual authentication for a listener.

Open application server administration console and from the left side menu select Configuration> HTTP Service> HTTP Listeners> http-listener-2, now you should check the Security check box and select SSL tab, now make sure that you have checked Client Authentication check box.

You are done, point your browser to https://computer1.mydomain.com:8181 you will see that this page will only open for the browser that you have imported EJBCA administration certification. it means that both server and client must prove their identity before they could communicate.

In next entry of this series I will demonstrate steps that you need to follow in order to create a stand alone web service client.

Make sure that you need to delete the private key of you server from cacerts.jks (it is not necessary by the way). Best way to explore you key stores is using keytool which you can find more information about it Here. Also if you are may find more cool key store editor in NetBeans Module Portal

For more information or maybe to find some of your questions answered you may take a look at:




GlassFish version 2 monitoring capabilities

Posted by kalali on May 27, 2007 at 02:59 PM | Permalink | Comments (0)

GlassFish version 2 monitoring capabilities

GlassFish version 2 provides good mentoring information about different aspects of application server and all of your applications that are deployed into GlassFish but before it can show those statistical information you need to configure its monitoring service. Figure 1.

Although this statistical and monitoring information and the way that they are presented is not as luxurious as weblog and websphere one's but they are good enought to help you track what is going in your server.

To enable monitoring service of GlassFish you need Commence with openning administration console, Locate the configuration node and expand it now select monitoring now choose all components that you want to monitor, select high for more details and sure more overhead and low for less details and less overhead. Figure 1.

Configure your monitoring

Now you should be able to see some monitoring detailsby going to monitoring pages, monitorig pages are placed under different nodes in administration console based on your installation profile. If you are not sure about your glassfish profile, follow the developer profile item.

  • For the cluster or enterprise profile In the tree component, select Common Tasks, then click View Monitoring Data.
  • For the developer profile, in the tree component, select the Application Server node. Click the Monitor tab.

Glassfish categorize monitoring information under three categories, these categories are as follow:

Call Flow:shows you how many requests are replyed successfully or with a failure and how much time consumed for that request in different layer of application server. Figure 2

Call Flow

Runtime:this category provides information about JVM, Garbage Collection, HTTP service, Listeners (http/s), ect. for example under JMV node of these category you can use memory item to view fine grained details about your application server heap. Figure 3

Runtime

Applications:Let you select an application and view details about that application components, for example you can view how much time a servlet has called and how time its call taked. Figure 4

Applications

Resources:here you can view detailed information about all of your resources like connection pools, connectors, jms connection factories, etc. For example you can view fair amount of details about your connection pool in order to hunt possible connection leake or to tune your connection pool. Figure 5

Resources

Transactions:These allows you to view what is state of transactions that are running inside your application server.

It is my first blow entry written from my Ubuntu 7.04 installation and I am happy with my switch from OpenSuse to Feisty Fawn :-)




110x32_anim_v1.gif Locations of visitors to this page


How to install and use OpenSSO CLI (Command Line Administration Interface)

Posted by kalali on May 17, 2007 at 04:04 PM | Permalink | Comments (0)

OpenSSO  which is open source branch of Sun Java Access Manager has several module which you should install and configure in case that you want to have similar bundle from its open source branch.

One of main components is OpenSSO itself which you can obtain from  Its nightly builds page; just make sure to select latest link which will take you to the download page with links to OpenSSO modules.
OpenSSO file name should be OpenSSO.war; this file is server side application that handle all authentication and authorization related activities. in the download page you can see several other modules, for this blog entry I will give you some details about installing OpenSSO and Administration Command Line Tools. ((It should be last row link in component download page).

To install OpenSSO, you can follow a detailed installation instruction in OpenSSO easy installation just make sure that you remember value that you determined for  Configuration directory because we will use it to install CLI (Command Line administration Interface).

Now that you have installed OpenSSO you can install its CLI package. Download amAdminTools.zip and extract it somewhere in your hard dist. after you have extracted it follow this sequence to complete its installation open a terminal (cmd)  and navigate to directory that you extract the amAdminTools.zip; execute: setup -p  <OPENSSO_CONFIGURATION_DIRECTORY>

It should echo some text indicating that installation is successful. If you want to know more, Installation is nothing more than creation of batch files that I will talk about one of  them in next step. this batch files use some files that are located in opensso configuration directory to perform their operations.

the file that I will talk about is named amadm.bat or amadm.sh this file let you manage your OpenSSO installation from a command line interface even if opensso server is running. all sub commands of this command has a set of 2 common parameter

  1. -u amAdmin : this is default administration username. you can create more users with administration privileges.
  2. -w <password> it is your password which you determined during opensso installation.

Now lets try some commands


amadm.bat create-realm -e /realm12 -u amAdmin -w adminadmin

This command will create a new realm and put its parent is root realm.

amadm.bat list-realms -e / -u amAdmin -w adminadmin

This command list all realms that are created under parentship of root realm.

amadm.bat list-identities -e / -x "*" -t User -u amAdmin -w adminadmin

This command list all identities of type User which are exists in root realm. you can find a list of all sub commands by calling

amadm.bat

By default root realm is named openSSO and your created realm will be a child of that realm, Now you can open openSSO web based administraton console and check the result of CLI with it



A scenario based tutorial about using NetBeans BPEL, JBI and Web service developemt features

Posted by kalali on May 11, 2007 at 01:33 PM | Permalink | Comments (3)

NetBeans Enterprise pack 5.5.1 provides several new features in as well as those ones in version 5.5. One of the most important features is related to ESB. In this article I will cover some of NetBeans capabilities to develop application based on the SOA paradigm.

You will see what ESB is and how it can ease development and deployment. I will also show what BPEL is and how it can affect your development, while demonstrating NetBeans’ level of support for ESB and BPEL. Building a scenario-based sample which uses some of NetBeans Enterprise Pack features in the BPEL and ESB area is the final things I will demonstrate.

What can an ESB do for us?

An ESB which can act as a JBI compliant is an infrastructure that manages, monitors or enhances service's capabilities in several ways like providing more connectivity mechanisms which has been added to ESB by binding components. Binding components can interact with resources outside the ESB. For example a JDBC binding component can act like a consumer and poll a database table for new records and whenever new records become available transforms them to a standard message named Normalized Message and sends it to the other participants by using a message router named Normalized Message Router or NMR. Messages that are produced by binding components may require transformation in order to meet business rules or making usable messages for other binding components or service engines. A service engine provides and consumes services within ESB. BPEL service engine which hosts long running business process based on BPEL standard is as a sample of service engine.

JBI compliant ESBs are based on XML-web services standards and usually support several WS-I standards like WS-Addressing, WS-Security and etc. When you install NetBeans enterprise pack you are adding a wide range of capabilities to your IDE for developing composite applications which are equal to JBI service assemblies. At the same time, installing Enterprise pack will install a version of glassfish integrated with Open-ESB 2.0 that addresses all your needs.

What is BPEL role in your SOA?

I am not going to talk about technical details of BPEL; I would prefer to say what it can do. BPEL allows us to orchestrate some fine grained web services to perform a more coarse grained long lived asynchronous or short lived synchronous business operations. For example you can develop a web service that persists data based on some meta-data which are attached to your data, a web service that check validation against pre-defined rules, a service that sends email to some recipients. Now you can use BPEL and some other features that are provided by BPEL engine to perform a business operation like order saving and customer registration; so BPEL provides us with features that can highly reduce amount of fine grained web services that we develop in our entire enterprise.

What does NetBeans as a development tools?

NetBeans enterprise pack provides us with a first class designer for BPEL, WSDL and XSD. Another very good feature that is introduced in Enterprise pack 5.5.1 is CASA editor. Composite Application Service Assembly editor let developers to see a high-level view of how the Service Assembly is connected and configured. More importantly, users can modify connections between elements within the Service Assembly. The routing of Service Units and Binding Components can be easily tweaked, or completely redone as it provide visual editor enriched with a component palette for all available artifacts like binding components and service units.

Continue Reading...



Hibernate dynamic mapping and Dom4J enabled sessions

Posted by kalali on February 11, 2007 at 03:53 PM | Permalink | Comments (3)

Hibernate from version 3.0? provide a very useful feature for people who develop application frameworks. Indeed this feature allows you to work directly with XML documents and elements which represent entities.
Imagine that you have an application or an SDK which help users to manipulate data from different RDBMSs. Hibernate provide rich configuration facilities which help you configure  Hibernate dynamically in term of adding mapping data or other configuration artifacts that usually stores in hibernate.cfg.xml or equal properties files.

As we are planning to use Hibernate dynamic mapping and Dom4J entity mode i am going to blog about it during my evaluation.
OK, Hibernate provide 3 kinds of entity mode
  • POJO
  • DOM4J
  • MAP
Default mode sets to be POJO as it is most commonly used mode. This modes tell session how it should handle entities. We can configure a session to use any of this modes when we need that mode, but we can configure it in hibernate configuration file for by adding a property like

 <property name="default_entity_mode">dom4j</property>
To hibernate.cfg.xml . but for our sample we will create a session with dom4j entity mode. you can find a complete sample for this blog entry here . Make sure that you read readme file in project folder before you go toward executing it. For this sample I used Netbeans 6.0 M6 (which really rules) and Hibernate 3.2.1 . I wont tell steps to create project, XML file or ... but just actions and core required for hibernate side. you can see project structure in the following  image.

Hibernate dom4j session project structure

As you can see it is a basic ant based project.
Let me give you content of each file and explain about it as much as i could. First of all lets see what we have in hibernate.cfg.xml

 <?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration
PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory >
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost/hiberDynamic</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.c3p0.min_size">5</property>
        <property name="hibernate.c3p0.max_size">20</property>
        <property name="hibernate.c3p0.timeout">300</property>
        <property name="hibernate.c3p0.max_statements">50</property>
        <property name="hibernate.c3p0.idle_test_period">3000</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <!--<property name="default_entity_mode">dom4j</property> -->
        <mapping resource="dynamic/Student.hbm.xml"/>
    </session-factory>
</hibernate-configuration>


The configuration file is a simple and traditional hibernate configuration file with pooling enabled and  dialect sets to MySQL ones.
We have one mapping file which is named student.hbm.xml so we include it into the configuration file. If you do not have MySQL around then use Derby which is included into NetBeans ;-) .

 Log4J configuration is another traditional one, as you see
log4j.appender.stdout=org.apache.log4j.FileAppender
log4j.appender.stdout.File=messages_dynamic.log
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.rootLogger=WARN, stdout

We used a file appender which send formatted log entry into a file named messages_dynamic.log in project root directory. next file which we are going to take a look is Student.hbm.xml  it is our mapping file, where we define the student as a dynamic entity.

 <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class  entity-name="Student" table="Student">
        <id name="id" column="STUDENT_ID" type="long">
            <generator class="native"/>
        </id>
        <property  name="name" type= "string"  column="STUDENT_NAME"/>
        <property name="lastName" type="string" column="STUDENT_LAST_NAME" />
    </class>
</hibernate-mapping>

As you  can see there is just one change in  mapping file, we have entity-name attribute instead of class attribute. You should know that can have both class and entity-name attribute so an entity could be dynamic or mapped to a concrete class.

Next step is looking at our HibernateUtil which is known to the community for Hibernate booting and  hibernate instance management.
here is its code:
 
package persistence;
import org.hibernate.*;
import org.hibernate.cfg.*;

public class HibernateUtil {
  
    private static SessionFactory sessionFactory;
    static {
        try {
            sessionFactory = new Configuration().configure().buildSessionFactory();
       } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }
   
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    public static void shutdown() {
       
        getSessionFactory().close();
    }
}

Noting extra here. lets look at last part in which we try to use dom4j session to manipulate our data.


 package dynamic;
import java.util.*;
import org.hibernate.EntityMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import persistence.HibernateUtil;
import org.dom4j.*;


public class DynamicMapping {
   
    public static void main(String[] args) {
        Session session = HibernateUtil.getSessionFactory().openSession().getSession(EntityMode.DOM4J);
        Transaction tx = session.beginTransaction();
Query deleteQuery = session.createQuery("delete from Student");
deleteQuery.executeUpdate();
tx.commit();

tx = session.beginTransaction();
        //create some some student and save them
        {
            Element anStudent = DocumentHelper.createElement("Student");
            Element nameElement = DocumentHelper.createElement("name");
            nameElement.setText("Alice");
           
            Element lastNameElement = DocumentHelper.createElement("lastName");
            lastNameElement.setText("Cooper");
           
            anStudent.add(nameElement);
            anStudent.add(lastNameElement);
            session.save(anStudent);
        }
        {
            Element anStudent = DocumentHelper.createElement("Student");
            Element nameElement = DocumentHelper.createElement("name");
            nameElement.setText("Lea");
           
            Element lastNameElement = DocumentHelper.createElement("lastName");
            lastNameElement.setText("Connor");
           
            anStudent.add(nameElement);
            anStudent.add(lastNameElement);
            session.save(anStudent);
        }
       
        tx.commit();
        //List all student
        Query q = session.createQuery("from Student ");
       
        List students = q.list();
        org.dom4j.Element el = (org.dom4j.Element)students.get(0);
        System.out.println(el.getText());
        for (Iterator it = students.iterator(); it.hasNext();) {
            org.dom4j.Element student = (org.dom4j.Element)it.next();
           
           
            System.out.println("Printing an Student details: ");
           
            for ( Iterator i = student.elementIterator(); i.hasNext(); ) {
                Element element = (Element) i.next();
                System.out.println( element.getName()+":  "+ element.getText());
            }
        }
        //retrieve an student, update and save it
       
        q = session.createQuery("from Student where  name =:studentName ");
        q.setParameter("studentName", "Alice");
        Element alice = (Element) q.uniqueResult();
       
        alice.element("name").setText("No Alice any more");
        tx=session.beginTransaction();
        session.save(alice);
        tx.commit();
       
        session.close();
        HibernateUtil.shutdown();
    }
}

In the begging we create a session with dom4j entity mode. so it will return Dom4J elements as our entities. in next two blocks i have create two students one is Alice Cooper and the other is John connor  (what does this name remind you? ;-) . we simply ask our session to save them as we do for usual POJO mode. Session know what to do with dom4j elements as it is configured as a DOM4J session.
In Second block we query our table and retrieve all entities into a list, but this list is not a list of Student POJOs instead it is a list of DOM4J elements. so we need to do some XML processing when we want to extract our entity properties. you can learn more about DOM4J at Here .

Next step we retrieve a single row, edit and save it into our database, Its all simple DOM4J operation which you should use over some elements to manipulate your data.

Build file that i used contains two target that we will use during this project. first one is hbm2ddl which will create our database structure and the second one is run target which will execute our main class. it is not required to include build file here  you can download the sample and check it yourself. make sure you look at readme file before digging into execution of application.

In next few days I will try to do a simple benchmark for some simple CRUD operation to have a basic clue about DOM4J entity mode in our environment.






110x32_anim_v1.gif Locations of visitors to this page Whats Your Google PageRank?


Jonas Joins to Netbeans supported application servers

Posted by kalali on September 17, 2006 at 01:22 PM | Permalink | Comments (1)

Jonas Joins to Netbeans supported Application servers
By release of first public version of JOnbAS List of netbeans supported application servers growth to
  1. Sun java application server (Glassfish)
  2. JBoss application server
  3. Tomcat servlet container
  4. WebLogic application server
  5. JonAs application server
and im sure this is a growing list.
by my experiences , Netbeans has very good support for application server.
specially its support for Glassfish (Sun microsystem itself application server) outstanding.
with the current module you can :
  • Starting and stopping the server
  • Java and JSP debugging
  • Generating the default server specific deployment descriptors
  • Deploying, undeploying the Web, EJB and EAR modules
  • Browsing the deployed WAR, EJB and EAR modules
which is almost enough.

I think sooner or later we will see good support for Geronimo , Resin and Jetty as contributed or independed modules, and it is that time which Netbeans application server support has no reason not be the best.







Netbeans 5.5 and Jdeveloper 10.1.3.1 both sounds very good...

Posted by kalali on August 25, 2006 at 07:15 AM | Permalink | Comments (0)

Netbeans 5

Netbeans 5.5 and Jdeveloper 10.1.3.1 which one ?
Both Jdeveloper and Netbeans that i am talking about them are in beta and developer preview stage.
Netbeans as an Opensource IDE has its own fast growing user community.

Netbeans 5.5 beta 2 let features include :

  • develop and deploy on tomcat / Glassfish and Jboss out of the box.
  • As core features it has many code generation facilitis which can help to bootstrap an application ,it has code generation for CMPs , session facades ,ws client stub....
  • Having an almost first class profiler , first class J2me development pack
  • New c/c++ development pack
  • good support for SVN and CVS
  • very good Swing designer
  • developer collaboration module
  • Heavy support of SUN by giving the source codes for some of its extra pack

which Made NetBeans a good choice for developers.

One of the packs that donated by sun· is Enterprise pack , Enterprise pack features in brief are as follow :

  • UML 2 compliant modeler
  • visual BPEL
  • visual WSDL designer
  • xml visual tools for xml schema declaration ...
  • facilities to develop web service and apply security on them.
Sun announced that it will add Java Studio creator to NetBeans Stack as another package.
having Creator can attract many users to Netbeans as it provide a rich set of feature for web application developers.

but what about Oracle JDeveloper 10.1.3.1?
some times ago Oracle announced that it will let developers to use JBeveloper for free . so Jdeveloper and Netbeans from one point of view are the same ,You will not pay any penny for them.
Oracle really boosts JDeveloper in recent years which made JDeveloper a choice for j2ee application developers
JDeveloper Editor has changed to a very powerful editor with a good refactoring support.
opposite to Netbeans which you need to download several package to gain most of its feature you will not need to download any extra package to make use of jdeveloper as it is appropriated.
·
  • Oracle have much more code generation falsities that Netbeans .
  • visual ESB modeling allows you to assemble you ESB component visually (its ESB is not JBI compliant)
  • visual WSDL designer
  • visual xml development tools
  • good swing designer and data binding using oracle ADF
  • good JSF / Struts support , indeed Jdeveloper JSF support with its ADF faces is brilliant.
  • WYSIWYG for HTML and jsp pages with support of third party jsf libraries like Myfaces.
  • first class database development facilities ( for oracle database mostly).
  • Only you can use oracle server suite as development server there is no support for other application servers.
  • No support for c/c++ development (AFAIK).
  • built-in profiler
  • very powerful web page generation which can bootstrap a data driven web page design.
  • UML modeler (1.4 compliant)
  • very rich set of facilities for Web service development
  • ...

I think JDeveloper (for now) is ahead of NetBeans as it provide much more facilities for developers , but for later version we can not tell anything because NetBeans people are unpredictable , as they prove their credibility by release of NetBeans 5.

What you have read is my opinion which might be biased. we never can say that one IDE is 100% better than another , it is just context oriented and the users view point. but one thing is completely obvious that JDeveloper and NetBeans both are going to provide rich facilities for SOA. NetBeans by means of· Enterprise pack and using glassfish with integrated BPMS from intalio and· what it has acquired from seebyond.
and oracle with its SOA suite and JDeveloper , both are going to make choice harder for developers.







Develop web application with netbeans ,seam and Glassfish

Posted by kalali on August 15, 2006 at 05:05 AM | Permalink | Comments (1)

Register New User register.jsp

In this two part series I will try to show you how easily you can  build applications using NetBeans 5.5 based on  seam , facelets , jsf and new EJB 3 standard.

I will not discuss any of framework in details as you can find detailed information about each of them in their homepage and some other articles.
I want just show , How you can use NetBeans with some leading frameworks to build your web based applications. I will not discuss NetBeans specific tasks in details .
I will more focus on leveraging this stuff together using NetBeans IDE.

What you will need to follow  this series :

  • NetBeans enterprise edition 5.5 , you will need Glassfish or JBoss to continue with this series. check and make sure that your NetBeans has application server bundled otherwise get a copy of glassfish from its website.
  • seam 1.0.1 GA  or newer.

seam distribution contain Facelets too , but i strongly suggest you get Facelets distribution separately and take a look at its samples and very good documentation. indeed both Facelets and seam has very good documentation.

In this entry I will introduce each of this frameworks in very brief  to make the series stand alone , and i will show you how to setup the development environment and we will go with first part which is developing seam layer codes.

JBoss seam is created to leverage maximum possible feature of Java EE 5 standards like JSF and EJB3.
seam , seamlessly integrate EJB3 as a backend with JSF as presentation , meanwhile provide management of long running process
by using JBPM . and give you ability to focus on your business logic rather than silly data providing stuff. By leveraging Facelets helps you to do even more with seam and JSF.

To name its features I can say:

  • Lesser XML, More Annotation. (please do not blame me for naming annotation and XML in one line :-))
  • it let you go with your business logic rather thinking and resolving some common issue like user conversation state.
  • seam has a more flexible context model , it has 8 context , by means of this context you can manage your application more effective. for example a business process live in business process context .
  • Accessing each component in entire seam context with one unique name.
  • Managing workplaces and conversations .
  • It easily will let you develop Portlet by providing a Portlet context . we will discuss this item in latter parts

With many more features.

But about JSF , JSF is  a web framework , it is  Standard and  Developed under JSR 127.
Some of JSF features are as follow:

  •  User interface framework
  •  Server-side UI components
  •  Event model , something like desktop applications event model , but very reduced.
  •  Component state
  •  Renderers , Render Kits , for example ADF faces has a telnet render which make it possible to render a ADF faces application for a  telnet client.
  •  Validation
  •  Type conversion
  •  Internationalization

about Facelets , we will discuss more in next articles , but for now you should know that Facelets bring some view related enhancement and features to JSF community .
To name some of features :

  • Facelets make it possible to develop your entire web pages using your favorite page designer like Dream weaver or Microsoft FrontPage. to achieve this feature it introduce a new attribute, jsfc ,that make it possible to change each html element  to a JSF equal component. it is similar to Tapestry 's jwcid attribute. So you can use all binding and event handling stuff of JSF and availability and ease of use of html WYSIWYG.
  • Facelets provide a template-ing  features like Velocity's for JSF . it allows you to test JSF views out of container.
  • Some decoration features like what tile bring to struts community and SiteMesh ,generally, to all java based web application.

lets start the job of creating simplest sample ;) .

I assume that you download seam and extract it in seam_home Also your NetBeans 5.5 is running and an application server capable of  containing ejb3 (Glassfish) is configured with your IDE.

for sake of simplicity we make one   Library in our NetBeans IDE to make our job easier. as you know each library could contain some jar files, etc...
 

Create a library name it seam and add the following jar files to it , the first
seam_home\jboss-seam.jar
seam_home\jboss-seam-ui.jar
seam_home\hibernate-all.jar
seam_home\thirdparty-all.jar

add seam library  to Registeration-EJBModule and Registeration-WebModule

Switch to runtime view (CTRL+5).Extend database node  , if you have no database created in your embedded derby  then create a database and create a table with following  characteristics
Table Name: users
Fields :

username varcahr(255) , primary key
password varchar(255) , not null
name varcahr(255) , not null

after you create this table , create a new enterprise application project by going to , file>new project>enterprise application
name it Registeration. make sure that you have selected the Java EE 5 as j2ee version.

go to project view (CTRL+1) And select Registeration-ejbModule , right click on it and select CMP entity bean from database...
Now you should be able to select the JDBC connection that you have made in above step and give it a package name.
click next and select users table from left column and add it to right column.
click finish.
That's it , you have your CMP ready to go.

  • what we need to add to the CMP bean class in addition to its created structure
  • another constructor with all the CMP  fields.
  • some annotation for getters , to help us in validation

final shape of users CMP will be like :


package cmps;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.validator.Length;
import org.hibernate.validator.NotNull;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
/**
 *
 * @author Masoud Kalali
 */
@Entity
@Name("user")
@Scope(org.jboss.seam.ScopeType.SESSION)
@Table(name="users")
public class Users implements Serializable{
   private static final long serialVersionUID = 1881413500711441951L;
    private String username;

    private String password;

    private String name;
    
    /** Creates a new instance of Users */
    public Users() {
    }

    
    public  Users(String name, String password, String username)
 {
this.name = name;
this.password = password;
this.username = username;
}
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "username", nullable = false)
     @Length(min=5, max=15) 
    public String getUsername() {
        return this.username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Column(name = "password", nullable = false)
     @Length(min=5, max=15) 
    public String getPassword() {
        return this.password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Column(name = "name", nullable = false)
     @Length(min=5, max=15) 
    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
}

we are finished with our POJO EJB :-) , now lets go and handle web layer stuff , from now we are working with seam view layer and JSF , I will talk about Facelets later in other articles of this series.

as I said in sample scenario we have just one action , so we can use a  managed bean or plain java object or whatever that is useable here as action listener or use a stateless session bean (using session bean is what JBoss offer) so we will use a stateless session bean to implement our action listener , it will also helps you to see how an stateless session bean is implemented in java EE 5.
so create a session bean by using , file > new > session bean , now you can select session bean type to be stateless , and change the package name to be sbeans
click finish  , editor will open up and show you the stateless seasion bean class.   
change the class body , in a way that final class looks like :

import cmps.Users;
import java.util.List;

import javax.ejb.Stateless;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.hibernate.validator.Valid;
import org.jboss.seam.annotations.Factory;


import org.jboss.seam.annotations.IfInvalid;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Outcome;
import org.jboss.seam.annotations.datamodel.DataModel;
import org.jboss.seam.core.FacesMessages;
import org.jboss.seam.ejb.SeamInterceptor;

@Stateless
@Name("")
public class ActionBean implements sbeans.ActionLocal
{
   
   @IfInvalid(outcome=Outcome.REDISPLAY)
   public String ()
   {
      List existing = em.createQuery("select username from User where username=:username")
         .setParameter("username", user.getUsername())
         .getResultList();
      if (existing.size()==0)
      {
         em.persist(user);
         return "success";
      }
      else
      {
         FacesMessages.instance().add("User #{user.username} already exists");
         return "success";
      }
   }

}

we will need to add same method signature to our session bean local interface , so add the method signature to ActionLocal class. it will looks like :
package sbeans;


/**
 * This is the business interface for Action enterprise bean.
 */
public interface ActionLocal {
      public String ();
}
now we are finished with the action , you may ask what are those annotation stuff in the session bean , so I should ask you to take a look at seam reference or wait until next part of this series. I should say that it is a very same version of seam sample that is implemented again in NetBeans IDE.
we are finished with EJBModule for now , lets take a look at what we will have in web module. first of all you need to add JSF framework to web module to do this , right click on web module and select properties , go to frameworks node and add JSF framework to the project. In web module we just have 2 JSF pages , one to , one to show the that s/he ed . Create following JSF files ,
register.jsp same as seam sample register.jsp , used for registering purpose
registered.jsp same as seam sample registered.jsp , used for showing the user that he/she is ed

we need to add some navigation case to our faces-config.xml , so extend web module note and under configuration files open the faces-config.xml we should add 4 navigation case to it , so right click inside the editor ,which show content of faces-config.xml, and select add navigation rule. a dialog will open , just fill the dialog as following table show
Rule From View /register.jsp

Now right click in the editor and add 4 new navigation case , these cases will handle navigating from one view to another.

From View From Outcome To view
/register.jsp success registered.jsp

lets code with the register.jsp , open the register.jsp in your NetBeans editor change the content to :

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib prefix="s" uri="http://jboss.com/products/seam/taglib"%>
<html>
<head>
<title> New User</title>
</head>
<body>
<f:view>
<h:form>
<table border="0">
              <s:validateAll>
<tr>
<td>Username</td>
<td><h:inputText id="username" value="#{user.username}" required="true" /></td>
<td>      <h:message for="username"/>       </td>
</tr>
<tr>
<td>Real Name</td>
<td><h:inputText  id="name" value="#{user.name}" required="true" /></td>
<td>      <h:message for="name"/>       </td>
</tr>
<tr>
<td>Password</td>
<td><h:inputSecret id="password" value="#{user.password}"  required="true" /></td>
<td>      <h:message for="password"/>       </td>
</tr>
          </s:validateAll>
</table>
<h:messages globalOnly="true"/>
<h:commandButton type="submit" value="" action="#{.}"/>
</h:form>
</f:view>
</body>
</html>


No we need to create the registered.jsp which show that our user is registered. open the file in your editor and change its content to looks like :

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<html>
<head>
<title>Successfully ed New User</title>
</head>
<body>
<f:view>
Welcome, <h:outputText value="#{user.name}"/>,
you are successfully ed as <h:outputText value="#{user.username}"/>.
</f:view>
</body>
</html>

Now we are almost finished with JSf files , there are some changes that we should make in web.xml and faces-config.xml.first open web.xml and add the following lines to it.make sure the you add them directly inside <web-app> node.

 <context-param>
		<description>
		</description>
		<param-name>org.jboss.seam.core.init.jndiPattern</param-name>
		<param-value>java:comp/env/registration/#{ejbName}/local</param-value>
</context-param>

<listener>
	<listener-class>org.jboss.seam.servlet.SeamListener</listener-class>
</listener>

<ejb-local-ref>
	<ejb-ref-name>registration/RegisterActionBean/local</ejb-ref-name>
	<ejb-ref-type>Session</ejb-ref-type>
	<local>sbeans.RegisterActionLocal</local>
<	ejb-link>RegisterActionBean</ejb-link>
</ejb-local-ref>

Now open faces-config.xml and add the following lines to it.
<lifecycle> <phase-listener>org.jboss.seam.jsf.SeamPhaseListener</phase-listener> </lifecycle>

That's it , you are finished creating your first seam sample in netbeans , lets execute the application and see the result. press f6 and wait until your browser opens , navigate to http://localhost:8080/Registration-WebModule/faces/register.jsp enter some information and then press register button.

You can check whether it applied or not by switching to runtime view and checking your Users table data . you can find complete explanation of jsp/java codes in Seam tutorial chapter 1 at : http://docs.jboss.com/seam/1.0.0.GA/reference/en/html/tutorial.html





Locations of visitors to this page Whats Your Google PageRank?


Step by Step toward a jms sample in NetBeans and yes GlassFish. part 2 : Remote Client

Posted by kalali on May 10, 2006 at 06:01 AM | Permalink | Comments (0)

In previous part you saw that how easy is to make an MDB to consume messages and a jsp/Servlet Front End to send message to a queue.
in this part i will show you how you can send message to a queue from a remote j2se client. you should know that in jms sending and reciving mesages has similar steps , some small changes require to consume message from a j2se client instead of sending messages.
to make it more clear , the main purpose of an MDB is to consume messages as they arrive , The MDB onMessage(..) is called whenever a message become available in destination that MDB is binded to it.

sure we can do what ever we want after message recieved. for example you can send the message that you recive from a queue to several topics , you can process it to do some database operation.... usually we use JMS for executing Asynchronous operations ,bringing more decoupling of a system components....

but lets come to our own steps to create a simple remote client that will sends some messages to tQueue that we made in first part of this series. then we will see that our messages are reciveing by TMDB. As you know we used a context object to locate the Queue and ConnectionFactory . the servlet code was like:
...
  Context ctx = new InitialContext();
...
By default a JNDI client assume that it is in a correctly configured environment , so when we do not pass a HatshTable to IinitialContext , the InitialContextFactory will return a context configured with that environment .In server environment we do not need to explicity pass parameters to InitialContext unless we need to initiate a context for another environment.
But, what are this parameters and how we can use them to initiate a context for none default environemtn or in places that there is no default environemt pre-configured , situation like standalone remote clients?
in a such situation we should configure the InitialContext using a HashTable that contain some parameters, There are several parameter that can be used to configure the initialContext but Two most important ones are :
  • provider url , for glassfish in iiop format it is : iiop://127.0.0.1:3700
  • We can use a key like Context.PROVIDER_URL to put its value into hashtable , also we may use java.naming.provider.url String to put value of this parameter into HashTable . this parameter is vendor dependent.
  • initial context factory , for glassfish it is : com.sun.appserv.naming.S1ASCtxFactory
  • This is another important parameter that we must set before we can access a JNDI Tree , indeed it is totaly vendor dependent because each vendor has its own implementation for its JNDI access. This factory will create the context object along with the url that you put into the hashtable. we may use Context.INITIAL_CONTEXT_FACTORY or "java.naming.factory.initial" string as a key to put this value into the hashtable
As i said there are some other parameters that you can set , like security parameters for authentication and .... but those are not necessary.
I should tell that we can also make this parameter to be the jvm default parameter and allows the Initialcontext to return a context without need to pass any arguments. in this way we need to pass parameters to java command when we want to start it. for example you can use :
java -Djava.naming.provider.url="iiop://127.0.0.1:3700" -Djava.naming.factory.initial="com.sun.appserv.naming.S1ASCtxFactory" to start our application. this way you allows the Initialcontext to return a context without need to configure it by a HashTable. For our Sample we will use a hashtable to configure the InitialContext , but you can try to pass parameters to java instead and observ the execution of your application.
To create a j2se remote client we need to add some jar files to our project , NetBeans provide its own way to manage jar files that may be used in more than one project. it is Libraries....
Run NetBeans, From Tools menu select Library Manager , create a new library and name it jms . Now you can add as much jar files to this library as you need , then it will be reuseable for your other projects.
add following jar files to this library , I use glassfish_home as installation directory of glassfish.
  • glassfish_home/lib/appserv-rt.jar
  • glassfish_home/lib/javaee.jar
  • glassfish_home/lib/install/applications/jmsra/jmsra.jar
  • glassfish_home/lib/install/applications/jmsra/imqbroker.jar
  • glassfish_home/imq/lib/imq.jar
  • glassfish_home/lib/appserv-admin.jar
  • glassfish_home/imq/lib/jms.jar

Create a j2se project using , File > new project > general > java application. name the application jmsClient and allow the IDE to create a Main class for you.
You shoud add that library that you create to this project. to do this , expand the project node , right click on the libraries and select add library Now from the library list select jms .
Up to now you have done 30% of creating an stand alone remote client to interact with your jms resources like connectionFactories and destinations.
Now we need to code the main method of main class . expand the jmsClient node , expand the source packages and finally open the main class of your project.
The overall look of your code shoul be like the following :
public class JmsClient {
    Context ctx;
    public JmsClient() {
        Hashtable properties = new Hashtable(2);
        properties.put(Context.PROVIDER_URL,"iiop://127.0.0.1:3700");
        properties.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.appserv.naming.S1ASCtxFactory");
        try {
            ctx = new InitialContext(properties);
        } catch (NamingException ex) {
            ex.printStackTrace();
        }
    }
   public Object lookup(String name){
        try {
            return ctx.lookup(name);
        } catch (NamingException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        JmsClient client = new JmsClient();
        try{
            ConnectionFactory     connectionFactory = (ConnectionFactory)client.lookup("jms/tConnectionFactory");
            Queue     queue = (Queue)client.lookup("jms/tQueue");
            javax.jms.Connection  connection = connectionFactory.createConnection();
            javax.jms.Session        session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
            MessageProducer messageProducer = session.createProducer(queue);
            for(int i=0;i<5;i++) {
                TextMessage message = session.createTextMessage("It is a message from main class "+  ": "+ i);
                System.out.println( "It come from main class:"+ message.getText());
                messageProducer.send(message);
            }
        } catch(Exception ex){
            ex.printStackTrace();
        }
    }
}
Now lets see what the above code means , i will not go indepth because JMS APIs are discussed too much :-) .
In constructor we configured a context object named ctx
we encapsulate the lookpu task in a method named lookup(...) we usually use a service locator or cached service locator to locate our objects in JNDI because JNDI lokups are time consumer
In main method:
  • we create a ConnectionFactory by looking it up in the jndi by using our context and dummy lookup(...) method.
  • we create a Queue by looking it up in the jndi by using our context and dummy lookup(...) method.
  • Then we create a connection using that ConnectionFactory
  • we obtain a Session (jms Session) using our connection
  • we made the messageproducer which is our tools to send message to that Queue ,
  • in a loop we create and sent 5 text message to the queue.

Now lets run the program and see the result , to run the application you nedd to complete the first part of this series , then you should run the application server , and if you like to have a demonestration like what i will show you , you should deploy the application that we made in first part.
i assume you have completed first part and you have the application server running , Now run the client that we made and what you will see in output window should be like :



and if you take a look at application server log file (in runtime tab , expand the servers node and rigt click on the glassfish instance , now select view server log..) what you should see in the server log should be something like :



messages that we send via standalone client will reach the queue that the MDB is listening on it , as soon as we send a message MDB will pick it up and start processing it.
you can download the standalone client project from here




GlassFish is Open source , but how much Open it is ?

Posted by kalali on May 09, 2006 at 02:07 AM | Permalink | Comments (0)

We know that GlassFish is opensource under CDDL license , being opensource is good but having a good and open relation with community is very good.
GlassFish has the most active community between opensource project that i have been involve a bit closer than observing , having that TheAquarium weblog make it magnifisant.Meanwhile you think that that weblogs is available in more that 3 languages, and it shows how much hard GlassFish people works to provide community with information that they need.
its Wiki is a great source of information and shows how much far GlassFish people goes in making a good communication with the community.
wiki pages update very often , you will find new information in its wiki / weblogs whenever you look at them.I think there is more with this glassfish to reveal than being just reference implementation of Java EE 5.
if you check TheAquarium in a daily basis you will see that Glassfish components are going to Maven repository of java .net very fastly , and it means that we can use maven for our project which are based on java ee 5.




Step by Step toward a jms sample in NetBeans and yes GlassFish

Posted by kalali on May 05, 2006 at 06:40 AM | Permalink | Comments (4)

Java EE 5 brings many ease of use in EJB development world and certainly it is one of biggest step ahead in java EE land.
NetBeans 5.5 is another big step toward making development on top Java EE some easier. NetBeans is a very easy to learn and use because it does not bring many stuff on the screen to "Occupy all the space" instead it provide maximum useability by means of limited number of views.
GlassFish as Reference implementation of JAVA EE 5 , provide you with all service that are named in java EE spec but it is not similar to older RI version of J2EE ,just remember J2EE 1.3 RI
it is much more better in term of functionality, performance, ease of use and ...
here I will tell you steps that you need to follow to build a simple MDB , a web based message producer and a remote message producer.

when you follow this entry you will be able to deal with basic aspect of JMS in Action and not only on your papers. but what do we need to have our JMS application running ?
  • A JMS implementation that is configured with our server , it can be done using embedded servers that are shipped with application servers or using remote / local MQ servers.
    GlassFish uses Sun message Queue , which is going to be available under the same license that GlassFish is provided. You can find more information about open source version at : http://mq.dev.java.net
  • You also need to setup a Queue and a connection factory in your application server.*
  • you should Create an MDB , and then implement the onMessage() method in way that you like.
*I should tell you that you can create your Queue and connection factory in many ways , yes more than two ways .
  • use GlassFish server web based administration console
  • use GlassFish command line console
  • using NetBeans 5.5 , yes NetBeans provide you some wizard thingy to make JMS / JDBC resources from withing NetBeans and then registering them to Application server.
I assume you know NetBeans and you registered GlassFish as an application server in NetBeans server manager
To create Queue and connection follow these steps :
  • Run The IDE and go to runtime tab , expand server node and start the GlassFish instance.
  • right click on GlassFish node and select view admin console
  • login to admin console ,In left side navigation panel , expand the resources and expand JMS resources
  • click on connection factories and from main frame click on new button , fill in the values as following ones
    • JNDI Name: jms/tConnectionFactory
    • Type: javax.jmsConnectionFactory **
    • Description: some description here
    • give it a name like : tConnectionFactory
    • Click OK button
    ** in JMS 1.1 we can use same factory for both publish/subscribe and point-to-point messaging
  • now we need to create a queue to be our messages destination, click on destination resources from main frame click on new and fill in the values as following ones
    • JNDI Name: jms/tQueue
    • Type: javax.JMS.Queue
    • Description: some description here
    • give it a name like : tQueue
    • Click Save button
Now we have our JMS Configuration ready to serve some MDB and remote client. Create a new enterprise application with two kind of modules , one EJB module and one web module , name it whatever you want but I named this sample jms
go to project view , right click on EJB module and select NewMessage-Driven Bean...
a window will open and ask you for some attributes of this MDB fill in the names like :
  • EJB Name : TMDB
  • package : mdbs
  • Mapped Name : jms/tQueue***
click finish and you are done , your MDB skeleton is ready and you just need to implement the onMessage(...) method.
*** This is where our MDB is assigned to , whether it is a topic in publish/subscribe scenario or a queue in point-to-point scenario.
Now change the implementation of your onMessage(...) as following , we also add one private object to our class , make sure that you include it too.
  @Resource
    private MessageDrivenContext mdc;
    public void onMessage(Message message) {
     
        TextMessage msg = null;
        try {
            if (message instanceof TextMessage) {
                msg = (TextMessage) message;
System.out.println("A Message received in TMDB: " +
                        msg.getText());
            } else {
               System.out.println("Message of wrong type: " +
                        message.getClass().getName());
                
            }
        } catch (JMSException e) {
            e.printStackTrace();
            mdc.setRollbackOnly();
        } catch (Throwable te) {
            te.printStackTrace();
        }
    }

we just made one more change in class skeleton and that is our MessageDrivenContext variable , we usually use this to call setRollbackOnly(...) when we use an MDB in a transactional scenario for this sample you simpley can ignore it.
Now lets make our web application to send some messages to that Queue and let the MDB fetch and process them.
wxpand web application node , and double click on index.jsp after it opens , change its content like the following , sure you can use component platte to drag and drop items to jsp source file :-)

<%@page contentType="text/html"%>

<%@pag