Friday May 16, 2008

GlassFish V3 - Using JDBC Connection Pool / JDBC Resource / MySQL


This blog talks about creating a JDBC Connection Pool and an associated JDBC resource with MySQL as the Database vendor.


The
default database "sakila" of MySQL is used in this example. All these
could be done so easily with Netbeans 6.1 after installing the
GlassFish V3 plugin. 


This screencast explains how to create a JDBC Connection pool in the
administration console and its associated JDBC resource. It also shows
a HelloWorld web application that used this resource to get some values
from a table in sakila database.

Watch the screencast :


GlassFish V3 TP2 JDBC


Download GlassFish V3 TP2 from https://glassfish.dev.java.net/downloads/v3-techPreview-2.html

Tuesday Nov 06, 2007

Management Rules - observedmbean property

My previous blog on selfmanagement and https://glassfish.dev.java.net/javaee5/selfmanagement/selfmanagement_example.html explain how to create management rules with an example.

Assumptions : 

Same example as in the above link (memory rule) taken. 

Custom Mbeans  Memory (impl-class-name:com.sun.example.mbeans.Memory) and MemoryActionBean (impl-class-name:com.sun.example.action.MemoryAction) are deployed.

Problem : 

In GUI, when a new management rule is created following the steps and with the values :

Observed Mbean : com.sun.examples.mbeans.Memory

Observed Attribute : FreeMemory 

and other values as specified in the example,

the server.log shows an error message that the rule is not configured because of some errors. The log looks like


 MemRule;monitor;|SGMT0017:
Error creating and configuring the rule : MemRule due to
IlegalArguments specified for its event type : monitor. Create the
rule with correct arugments for the configured event.|#]


Solution :

Modify the domain.xml under install_directory/domains/domain1/config/ directory - edit the management rule MemRule :

Change the line

property name="observedobject" value="com.sun.example.mbeans.Memory"

to

property name="observedmbean" value="Memory"

 
Restart the server after this change. And you will see that the error message goes away. Note here that "observedobject" is changed to "observedmbean" and the new value is the name of the custom mbean deployed with the impl-class-name : com.sun.example.mbeans.Memory.

Explanation :

In GUI, the Observed Mbean takes values like
"user:impl-class-name=com.sun.example.mbeans.Memory,name=Memory,server=server".

This value is translated into "observedobject" property in domain.xml. Hence if you specify "com.sun.example.mbeans.Memory", in domain.xml you will see this value against the property "observedobject". 

Very few know that there is another property called "observedmbean" that accepts the mbean name directly. But in GUI, there is no explicit way of specifying this observedmbean property. One has to enter the whole object name for the input "Observed Mbean" in GUI, which will get translated into "observedobject" in domain.xml. Alternatively, domain.xml can be modified with observedmbean property.

Whereas in CLI, you could just specify the parameter "observedmbean"
with value "Memory" in the command line, without even specifying the "observedobject" property.

Ex: asadmin create-management-rule --port 4848 --user admin_user
--action  MemoryActionBean --eventtype monitor --eventloglevel WARNING --eventproperties
<blah-blah>:observedmbean=Memory:<blah-blah> rule_name

This is an advantage CLI has over GUI.  

 

Tuesday Oct 30, 2007

Troubleshooting - Cluster startup Failure

Recently i had this problem.. I setup a cluster with an instance. But was not able to start it up. 

I got a series of  java.net.ConnectException: Connection refused exceptions and the instance did not startup.

What did the wonder?

 The /etc/hosts file had the following entries:

127.0.0.1 mymachine mymachine localhost

 When i commented out this line in the hosts file and add a physical IP entry like

129.xxx.xxx.xx mymachine

 and startup the instance, it goes through fine :)

 Reason

MQ needs the hostname to map to the absolute IP and not 127.0.0.1.


Friday Oct 26, 2007

Lookup from Standalone Client

My previous blog was about accessing a JDBC resource from an ejb. 

This blog talks about accessing the JDBC resource i created in the last blog, from a standalone client.

I use the same configuration from my previous blog : jdbc/cactus for my resource that needs to be accessed.

My sample will have the following code:

InitialContext ctx = new InitialContext();

javax.sql.DataSource ds = (javax.sql.DataSource) ctx.lookup("jdbc/cactus";)

Connection c = ds.getConnection();

insert(......);

c.close();

Compile the sample

 Run the sample

 Note the included jars in the classpath

  • appserv-rt.jar
  • javaee.jar
  • appserv-admin.jar
  • imqjmsra.jar
  • derbyclient.jar

Also, observe the system properties for the server host and naming service port.

JDBC resource lookup from EJB

Accessing a JDBC resource from an EJB is a fairly simple thing to do. As simple as the following:

 
1. Start domain and database

After installing GlassFishV2, start the domain domain1 and start the database. I would be using Derby in this example. Derby can be started in 2 ways    

  • <INSTALL_ROOT>/bin/asadmin start-database
  • From netbeans : Tools -> Java DB Database -> Start JavaDB Server. The port settings for the server started up can be modified in ~/.netbeans-derby/derby.properties

 Now, the database is started at port :1527 and domain is running at 4848.

2. Create a JDBC Connection pool and JDBC Resource

 Login to the Admin Console (http://localhost:4848) and navigate to Resources->JDBC->ConnectionPools. Click on New and enter the details like Name:Cacti  ResourceType:javax.sql.DataSource DatabaseVendor:Derby. In the next screen, accept the default values but don't forget to enter the following additional properties

  • DatabaseName : sampleDB
  • ConnectionAttributes : create=true (if the sampleDB does not exist)
  • Password : dbpassword
  • PortNumber : 1527 (or the customized DB port)
  • ServerName : localhost
  • User : dbuser

Click on Finish. To verify, click on the 'Cacti' connection pool you just created and do a 'Ping connection Pool".

 Navigate to Resources->JDBC->JDBCResource on the left panel of the admin console and click on New. Specify a JNDI name as "jdbc/cactus". I chose to append the name cactus with jdbc since i am accessing a database. Choose the pool name you just created "Cacti" and click on 'OK'.

3. Access the resource in your app

Suppose i have an EJB that has to use this JDBC resource. This can be done as follows in the SampleEjb.java : test() method

InitialContext ic = new InitialContext();
DataSource ds = (javax.sql.DataSource) ic.lookup("jdbc/cactus";)

Connection con = ds.getConnection();

insert("something", ...., con);

con.close();

Create the appropriate Remote and Home interfaces.  

4. Specifying the appropriate deployment descriptors:

Consider this is a web application.

application.xml

 <application>
    <display-name>Sample EJB Test</display-name>
    <module>
            <web>
                <web-uri>sample-test.war</web-uri>
                <context-root>/sample-test</context-root>
            </web>
    </module>
    <module>
            <ejb>sample-test.jar</ejb>
    </module>
</application>

ejb-jar.xml

<ejb-jar>
    <description>Sample test</description>
    <display-name>Sample test </display-name>
  <enterprise-beans>
      <session>
          <description> Sample bean </description>
          <display-name> Sample bean </display-name>
          <ejb-name>SampleRemote</ejb-name>
          <home>examples.SampleRemoteHome</home>
          <remote>examples.SampleRemote</remote>
          <ejb-class>examples.SampleEjb</ejb-class>
          <session-type>Stateless</session-type>
          <transaction-type>Bean</transaction-type>
      </session>
  </enterprise-beans>
</ejb-jar>

 sun-ejb-jar.xml

<sun-ejb-jar>
        <enterprise-beans>
                <ejb>
                        <ejb-name>SampleRemote</ejb-name>
                        <jndi-name>SampleRemote</jndi-name>
                </ejb>
        </enterprise-beans>
</sun-ejb-jar>
 

web.xml 

<web-app>
    <distributable/>
    <servlet>
        <servlet-name>SampleTestServlet</servlet-name>
        <display-name>Sample Test Servlet</display-name>
        <servlet-class>servlets.SampleTestServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>SampleTestServlet</servlet-name>
        <url-pattern>/SampleTestServlet</url-pattern>
    </servlet-mapping>
</web-app>
 

5. After all this coding, the structure would look like

/opt/sample
           -src
                -examples.SampleEjb
                -examples.SampleRemoteHome
                -examples.SampleRemote
                -servlets.SampleTestServlet
           -descriptor
                -ear
                    -application.xml
                -jar
                    -ejb-jar.xml
                    -sun-ejb-jar.xml
                -web
                    -web.xml
           -web
                 -index.jsp
           -build.xml
 

Build this application, create an ear and deploy this application on the application server via the admin console.

6. The Application can be accessed via http://localhost:8080/sample-test

Wednesday Sep 05, 2007

2 Machine Cluster Setup - CLI mode


Build : GlassFish V2 b58c on Solaris

Namesake names of machines : Tiger.cat.com, Cactus.plant.com

Using the Command Line Interface of GlassFish, a cluster can be setup with ease across 2 machines. Heres how it can be done:

1. Download GF v2 b58c from https://glassfish.dev.java.net/downloads/v2-b58c.html

2. Unbundle GlassFish following the instructions and do a ant -f setup-cluster.xml to enable clustering support on the installation.

Do Step2 on both Tiger.cat.com and Cactus.plant.com

3. On Tiger.cat.com, do the following:

  • Under {GF_install}/bin, do "asadmin start-domain" which will start up the default domain "domain1".
  • Create a node-agent as using the command "asadmin create-node-agent --host localhost --port 4848 man-agent"
  • Create a cluster with the command "asadmin create-cluster --host localhost --port 4848 cat-cluster"
  • Create an instance with the command "asadmin create-instance --host localhost --port 4848 --nodeagent man-agent --cluster cat-cluster instance1"

Note that in all the above steps, 4848 is the admin port of the domain domain1.

  • Start the node-agent : "asadmin start-node-agent --syncinstances=true man-agent"

The "syncinstances" flag starts up the cluster and instance as well. Its default value is false.


4. On Cactus.plant.com, do the following:

  • Under {GF_install}/bin, execute "asadmin create-node-agent --host Tiger.cat.com --port 4848 animal-agent" to create a node-agent on this machine pointing to the DAS (Tiger.cat.com).

After this step, observe in the /nodeagents directory that animal-agent is created.

  • Create an instance on this machine as "asadmin create-instance --host Tiger.cat.com --port 4848 --nodeagent animal-agent --cluster cat-cluster instance2"

  • Start node-agent, while the other node-agent is running: "asadmin start-node-agent --syncinstances=true animal-agent"

 2 machine cluster is successfully setup !!!

Thursday Aug 09, 2007

In-line upgrade

In-line upgrade is performed when "asadmin start-domain" is invoked on a particular domain. asadmin is found in install_root/bin directory. The domain on which start-domain command is invoked, is evaluated if it corresponds to the latest binaries or it matches that of an old installation. For ex: Let us consider domain1 is started, it is checked if it is a v2 domain or v1 domain or an earlier 8.x domain. If it is not a v2 domain, upgrade tool is automatically invoked. The domain is upgraded maintaining all the old configuration. It becomes ready-to-use with v2 binaries. After an upgrade, this upgraded domain can be started for further deployment and other processing.


Let me explain this with an example.

Example : SJSAS8 is installed in /opt/sjsas. The domains root is /opt/sjsas8/domains with a single domain, domain1. When GlassFish is also installed in /opt/sjsas, the binaries are upgraded in /opt/sjsas directory. The domain still exists in /opt/sjsas/domains without any configuration upgrade. To do this upgrade, execute

/opt/sjsas/bin/asadmin start-domain --domaindir /opt/sjsas/domains domain1



Actual Process :

The asadmin command recognizes an old domain in the specified domain dir and performs upgrade by invoking upgrade tool with all the inputs needed. This is an in-line upgrade viz., the domains root will remain the same before and after the upgrade for both source and target.

Upgrade tool becomes the internal process that is forked. If an upgrade is not needed, the domain is started up, as usual.



Why this new type of upgrade?

Lot of reasons...


  • Simple way of doing an upgrade

  • asadmin start-domain command is known to all

  • Ease of use without knowing the internal process

  • No need to provide any inputs like source, target or credentials

  • Only inputs provided are domain name and domain directory, where it exists

Tuesday Feb 27, 2007

GlassFish Upgrade Story

Why do you want to upgrade?

Well!!! Lot of reasons!!! Take the example of a browser, mozilla. In the update center, you get to know some cool feature X has been released in the next version. You want to get the new version, but do not want to lose your current data and configuration, like bookmarks etc. Mozilla upgrades in the way we want to keep our customized data. When browser is restarted after an update, you see that cool feature X along with all your previous configuration.

Would this not be cool if something like this happens in the Application Server too. There are new versions of GlassFish coming up and you might want to do the same thing - upgrade from a previous version to the latest version. The good news is, you could do that!!! And i'm going to explain just that, with some links for you.

Some of the following terms speak a lot about the Upgrade tool of GlassFish.

Side-by-Side Upgrade:

Installing application server in different locations and performing an upgrade. For ex: SJSAS8 is installed in /opt/SJSAS8 and GlassFish is installed in /opt/GlassFish. When upgrade is performed from /opt/SJSAS8 to /opt/GlassFish, it is called a side-by-side upgrade.

In-place Upgrade:

Installing application servers in the same location. For ex: SJSAS8 is installed in /opt/Appserver and you would like to install GlassFish also in the same location, to save some space, the inplace upgrade happens.

Binaries Vs Configuration:

When you install GlassFish, you would see under the install root, "bin", "lib", "domains" etc. The "domains" directory would contain all the configuration information like "deployed applications" and customized settings pertaining to each of the domains under it. The other directories are the binaries of the application server you have installed, with which new features become usable. These include the "config", "bin", "lib" etc.

Upgrade:

When an upgrade is performed, the binaries and configuration, both have to be transferred. This could be done In-place or Side-by-side (explained above). In both the cases, the transfer of binaries is done by the GlassFish installer and the configuration transfer is done by the AS Upgrade Tool. This is clearly demarcated, in the sense that, a binary upgrade could be done with/without the configuration upgrade. The configuration is not affected unless the AS Upgrade Tool is invoked.

AS Upgrade Tool Functionality:

The Upgrade tool works in these simple steps. It could be invoked in the following ways :


  • Running asupgrade from the install_root/bin directory. This invokes the GUI mode of the tool.

  • Executing asupgrade -c from the install_root/bin directory. This invokes the CLI (Command Line Interface) mode of the tool.

  • asupgrade -c has some more options as well, for mentioning the source and target locations. For details, on this, refer the Upgrade tool manual.

When upgrade tool is invoked in one of the above modes, it prompts for the source and target locations. Here source location refers to the directory of the domain that needs to be upgraded. Target refers to the GlassFish application server domains root to which the configuration is to be upgraded. In an In-place upgrade, the domains root directory will be the same.

Apart from these, the admin credentials are also prompted for. When all these details are provided, upgrade tool creates the necessary domains, transfers the configuration, transfers the applications deployed, transfer the realms and logs all these into an upgrade.log. By all these what i mean is that, the domain.xml under domain config directory is modified to incorporate all the config changes from the source.

Links:

These are some of the links that could be useful to you.
1. Prasad's blog : http://blogs.sun.com/prsad/entry/upgrading_to_glassfish
2. AS Upgrade One Pager : http://www.glassfishwiki.org/gfwiki/attach/OnePagersOrFunctionalSpecs/upgrade-one-pager.html

Monday Jan 23, 2006

Photos

These are some of the snaps taken during the Cisco party.












Thursday Jan 19, 2006

GlassFish : Self Management Rules

Self Management is an initiative taken in GlassFish to reduce the complexity of the management tasks. Mundane management tasks are automated by means of self-configuring. System Administrators who are responsible for monitoring the application server for unpredictable conditions no longer have to detect them manually. This is an easy-to-use feature that comes in handy at the unpredictable run-time conditions. This feature enables to recover from failures by detecting and preventing them, thus improving availability (self-healing). Even security threats are detected and self-protective actions are taken in response. The framework has been developed using standard technologies.

Self Management comprises of a set of management rules. You could create different rules based on the various event types. As mentioned at glassfish.dev.java.net, the different type of events are as follows.
  • Lifecycle events
  • Monitor events
  • Log events
  • Trace events
  • Timer events
  • Notification events
This blog is more about how to create management rules easily. I will show examples for some of the different type of rules. The action we take in response to the occurrence of an event, could be anything from sending an email notification to displaying an alert or killing some processes depending on what is appropriate for the particular event.

Let us take an example of displaying a pop-up window as an alert. Action mBeans implement the NotificationListener interface. The handleNotification() method for our action will look like the following.

    public synchronized void handleNotification(Notification notification,Object handback) {
        try {
            JFrame. setDefaultLookAndFeelDecorated(true);
            JFrame myFrame = new JFrame("MyAction");
            myFrame. setSize(250, 180);
            myFrame. setLocation(300,200);
            myFrame. getContentPane().add( new Label("Action has been invoked",Label.CENTER), BorderLayout.CENTER);
            myFrame. setVisible(true);
            myFrame. show();
        } catch (Exception ex) { // Log the exception }
    }

Let us name this class as CustomAction which is in the com.sun.myrule.action package. It has a corresponding CustomActionMBean. Follow these steps to deploy the action on the application server.

1. Compile the files and make a jar out of these two files.

2. After starting the application server, open the admin console by typing http://localhost:4848 on a browser.



Figure1: Admin Console


3. On the left pane, click on "Custom MBeans". On the right pane, all the deployed mbeans are listed. To deploy our action mbean, click on Deploy. Select the jar file that you just created against the "File to upload" column and click Next.



Figure2: Custom MBeans




Figure3: Creating Custom MBeans


4. Enter a name for the mbean. This will later be used while creating the rule. Enter name as "CustomAction".

5. Enter the class name along with the package name. In this case, it is com.sun.myrule.action.CustomAction.



Figure4: Creating Custom MBeans: Step 2


6. Click Finish.

The action mbean is successfully deployed on the application server.

We will use the same action mbean for all the rules. This action mbean will be called each time an event is triggered. For more information on actions, refer to actions section in glassfish.dev.java.net

Now let us proceed and create rules.

Simple rules for creating a rule:

1. Identify the event type you need. For example : lifecycle
2. Identify the mandatory and optional properties for that event type. For example : lifecycle event requires a property called "name".
3. Identify the action mbean you would like to use for your rule.
4. You could use the Application server Command line interface (CLI) or the Graphical user interface (GUI) to create rules.
5. Make sure the server is started before proceeding with rule creation.

Example 1 : Assuming the administrator wants to be notified everytime the application server shuts down or is terminated because of a failure. Continuous monitoring is necessary for this kind of a situation. Therefore, a rule could be created mentioning a notification to be sent to the administrator when this event is triggered. Management rule bundles together the event and the action.

Let us examine how this rule could be created.

After starting the application server with the command "asadmin start-domain", use either CLI or GUI to create the rule.

CLI mode :

/bin/asadmin create-management-rule
--host localhost --port 4848 --user admin
--action CustomAction
--eventtype lifecycle
--eventloglevel WARNING --eventproperties name=shutdown
my_lifecycle_rule

GUI mode :

  • Start admin console by typing http://hostname:port on a browser, after starting the application server.
  • Go to the Management Rules tab under the Configurations tab in the left pane. This displays the list of rules deployed on the server on the right pane.




  • Figure5 : Management Rules


  • Click on New
  • Type the name of the rule as "my_lifecycle_rule".
  • Check the Status checkbox to enable the rule.
  • Enter description
  • Choose event type as lifecycle.
  • Click on Next if you are done with this page.




  • Figure6 : New Management Rule


  • In the next page, select "shutdown" against Event and enter a description if desired.
  • Select "CustomAction" listed in the action list box and click Finish.




Figure7 : New Management Rule : Step 2


The rule is successfully created and is deployed on the application server. The action will be triggered everytime the application server shuts down. Similarly, rule could be configured to take some action on ready and termination.

Example 2 : The administrator wants to be beeped once in a while regarding some status. A rule could be created to do this as follows.

CLI mode :

/bin/asadmin create-management-rule
--host localhost --port 4848 --user admin
--action CustomAction
--eventtype timer
--eventloglevel INFO
--eventproperties pattern=MM\\\\/dd\\\\/yyyy\\\\/HH\\\\:mm\\\\:ss:
datestring=01\\\\/20\\\\/2006\\\\/12\\\\:00\\\\:00:
period=30000000:
message=Hello
my_timer_rule

Note here that "/" and ":" are escape sequences. Period, mentioned in milliseconds, is the period after which the notification is to be sent after the date mentioned in datestring.

GUI mode :
  • Start admin console by typing http://hostname:port on a browser, after starting the application server.
  • Go to the Management Rules tab under the Configurations tab in the left pane. This displays the list of rules deployed on the server on the right pane.
  • Type the name of the rule as "my_timer_rule".
  • Check the Status checkbox to enable the rule.
  • Enter description
  • Choose event type as timer.
  • Click on Next if you are done with this page.
  • Enter the values for datestring, pattern and other fields.
  • Select "CustomAction" listed in the action list box and click Finish.
Another example of a rule to monitor the runtime memory of the JVM can be found here .

Tuesday Jan 17, 2006

Cisco Disco

This is my first blog on blogs.sun.com. And this is gonna be about the 20th anniversary event of Cisco Systems. I happened to go for the Cisco's 20th anniversary event in bangalore along with a friend of mine who works in Cisco. The event was on a very grand scale. And they called it "Its the time to C(D)isco".

We went to KSLT stadium in cubbon park around 4:30 in the evening and from then on, it was total fun for 6 hours. There were lot of things to eat. After grabbing a juice, we went to the main pavilion where there were lot of games and more food. They were calling out for couples by the time we entered. The couples were asked to dance with a small balloon between their foreheads. The best thing was they were not supposed to touch it and balance it such that it doesn't fall down. It was so funny watching them. We then moved on to the other stalls. There was a tatoo lady painting beautiful faces of children with butterflies and hearts, while they were munching something. Then there was Hoopla, a ring throwing game wherein we grab gifts by skillfully getting them lie within the ring. Kids were having a nice time.

The rock band of Cisco performed after that in the stadium. They had composed 2/3 songs and some they sang from hindi movies. Two of the greatest singers in Indian movie industry had come to perform in a short while. Alka Yagnik and Udit Narayanan (some of you might be big time fans) made special appearance at the big podium. Lights glittering, a balloon was shot which sent out bits of glittering streamers down. Seemed like shining golden stars were being strewn across from the sky and that was when Alka started with some very beautiful numbers from Tere Naam and Kabhi Kushi Kabhi Gham. Everybody was spellbound. Her voice was very melodious and seemed to sweep me off my feet. She sang for about 1 hour and a half. While she was singing, we had a sumptuous dinner. What a nice evening! It was Udit's turn and he started with his first song, "Papa Kehte hain". Time seemed to flow like a river.

It was time for us to leave because we were getting late and it was becoming cold in the night. We left half-heartedly playing back and again the nice time we had. It was a wonderful evening to cherish.
About

shalini_m

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today