Sunday, August 17, 2014

Perfofming SEO friendly site redirection on a java app server to another domain

Hello everybody,

Today I will analyze a very simple and successful way to redirect you old domain hosted in a java app server (Tomcat for our example) to your new domain so that search engines understand that the old domain does not exist anymore and has moved to a new location (SEO friendly : Search Engine Optimizations friendly). All you need to do is set up your old domain to respond with an http status code 301 that means "Moved Permanently" for any request.

First, in the root directory of your old domain create a jsp with the name redirect.jsp containing the following code :

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%
response.setStatus(301);
response.setHeader( "Location", "http://www.NEW-DOMAIN.com");
response.setHeader( "Connection", "close" );
%>

Replace "http://www.NEW-DOMAIN.com" with the url of your new domain.

Next add the following lines inside the root directory's web.xml (for Tomcat installations inside webapps/ROOT/WEB-INF/web.xml):


<servlet>
   <servlet-name>redirectorrr</servlet-name>
   <jsp-file>/redirect.jsp</jsp-file>
</servlet>
<servlet-mapping>
   <servlet-name>redirectorrr</servlet-name>
   <url-pattern>/*</url-pattern>
</servlet-mapping>

And we're done. You may notice that the servlet name is totally irrelevant, so you can change it to anything you like (change it in both lines to a new servlet name).



p.s.
You can find me on fiverr for more personalized requests on any java app server configuration problem or java error that you encounter, with deliverance of less than a day (true!) and money back guarantee if not satisfied.

Saturday, April 23, 2011

Glassfish 2.1.1 on Linux: Performance Tuning Essentials

Glassfish may be the best J2EE Application Server out there. It is stable, it is fully j2ee 1.5 compatible, it runs all technologies and it is open source! I love this application server.
Here are some tips that will make it respond faster and increase its capacity in requests per second.

1. Disable application auto-deployment and dynamic class reloading :
Stand-Alone Instances > server (Admin Server) > Advanced tab
-> Auto Deploy --> uncheck
-> Reload  --> uncheck

2 Disable dynamic JSP reloading :
Edit "default-web.xml" inside the config directory of each instance and change the init-param development to false for the org.apache.jasper.servlet.JspServlet (instance restart is required):

3. Minimize logging.
Logger writes to disk and that is very expensive. So you can rearrange logging levels to "SEVERE" for all the loggers (since this setting is dynamic and you can change it to diagnose without restarts, Cool!).
Admin Console > Logger Settings page > Log Levels tab

Further log minimizing:
Tail your server.log at peak hours and watch carefully at the messages. Catch the loggers that print unnecessary messages and either speak to the programmer to minimize the messages of their applications or you can immediately adjust the logging level for that logger subsystem!
Add a new property with the logger name and set the level to SEVERE or even OFF!!!

4. Tuning HTTP File Caching in memory for faster response to static resources:
Configurations > config-name > HTTP Service (HTTP File Cache)
Globbally : true
Max Files Count : 128 - 512 (is a good start for small applications but it really depends on the applications static resources)
Max Age : 86400 (1 day) - 604800 (7 days) is a good start for non dynamic reloading applications (see tip No 3)

5. JVM Parameters:
Configurations > config-name > JVM Settings (JVM Options).

-server [maximum program execution speed by advanced optimized compilation]
-XX:+UseConcMarkSweepGC [using the Concurrent Mark Sweep garbage collector can cause a drop in throughput for heavily utilized systems, because it is running more or less constantly, but it prevents long pauses, so it is best for real time applications]
-XX:+DisableExplicitGC [Disable explicit full gc collections (System.gc() calls) since it would only interfere with the garbage collection algorithms and create big pause times]
-Xms=-Xmx [having the same starting and maximum heap memory will avoid spending time on any kind of unnecessary resizing of the heap memory]
-Xmn [Set at most half of the heap memory, since the garbage collection here should faster, more often and contains short lived objects. A good start is 1/5 of the heap size.]
-Xss128k [128k Stack Size is a very good start. If you get Stack Overflow error increase it by 128k at a time until you reach a point where you no longer get the error. You might even lower it to 64k (or lower) if your application is really lightweight, and then you will be able to serve more concurrent clients ]
-XX:SurvivorRatio=8 [survivor space and eden ratio will be 1:8. If survivor spaces are too small, copying collection overflows directly into the old generation. If survivor spaces are too large, they will be empty.]
-XX:MaxPermSize=-XX:PermSize [If you get an "java.lang.OutOfMemoryError: PermGen space", you need to increase this value, since the default is 64MB. If you set the initial size and maximum size to equal values you may be able to avoid some full garbage collections that may occur if/when the permanent generation needs to be resized.]

-XX:+CMSClassUnloadingEnabled [Enables the CMS Garbage collector (if you use it) to cleanup the PermGen space too. ]
-XX:+UseParNewGC [this parallel young generation collector can be used with the concurrent low pause collector that collects the tenured generation.]
-XX:ParallelGCThreads [If number of cpus is less than 8 then put the number of cpus else add (3 + (5/8) * (number of cpus)) ]
-XX:TargetSurvivorRatio=90 [Allows 90% of the survivor spaces to be occupied instead of the default 50%, allowing better utilization of the survivor space memory. ]

-XX:MaxTenuringThreshold=30

-Djava.awt.headless=true
-Dcom.sun.enterprise.server.ss.ASQuickStartup=false

JVM Parameters example:
-server -Xmx2g -Xms2g -Xmn800m -Xss128k -XX:SurvivorRatio=8 -XX:+UseConcMarkSweepGC -XX:+DisableExplicitGC -XX:+UseParNewGC -XX:TargetSurvivorRatio=90 -XX:MaxTenuringThreshold=30 -Djava.awt.headless=true -Dcom.sun.enterprise.server.ss.ASQuickStartup=false



6. Tuning Linux :
Start by checking system limits for file descriptors with this command:
$ cat /proc/sys/fs/file-max
8192
The current limit shown is 8192. To increase it to 65535, use the following command (as root):
$ echo "65535" > /proc/sys/fs/file-max
To make this value to survive a system reboot, add it to /etc/sysctl.conf and specify the maximum number of open files permitted:
fs.file-max = 65535
Note: The parameter is not proc.sys.fs.file-max, as one might expect.
To list the available parameters that can be modified using sysctl:
$ sysctl -a
To load new values from the sysctl.conf file:
$ sysctl -p /etc/sysctl.conf
To check and modify limits per shell, use the following command:
$ limit
The output will look something like this:
cputime         unlimited
filesize        unlimited
datasize        unlimited
stacksize       8192 kbytes
coredumpsize    0 kbytes
memoryuse       unlimited
descriptors     1024
memorylocked    unlimited
maxproc         8146
openfiles       1024
The openfiles and descriptors show a limit of 1024. To increase the limit to 65535 for all users, edit /etc/security/limits.conf as root, and modify or add the nofile setting (number of file) entries:
*         soft    nofile                     65535
*         hard    nofile                     65535
The character “*” is a wildcard that identifies all users. You could also specify a user ID instead.
Then edit /etc/pam.d/login and add the line:
session required /lib/security/pam_limits.so
On Red Hat, you also need to edit /etc/pam.d/sshd and add the following line:
session required /lib/security/pam_limits.so
On many systems, this procedure will be sufficient. Log in as a regular user and try it before doing the remaining steps. The remaining steps might not be required, depending on how pluggable authentication modules (PAM) and secure shell (SSH) are configured.

Tune the TCP/IP settings :

Add the following entry to /etc/rc.local
echo 30 > /proc/sys/net/ipv4/tcp_fin_timeout
echo 60000 > /proc/sys/net/ipv4/tcp_keepalive_time
echo 15000 > /proc/sys/net/ipv4/tcp_keepalive_intvl
echo 0 > /proc/sys/net/ipv4/tcp_window_scaling

Add the following to /etc/sysctl.conf

# Disables packet forwarding
net.ipv4.ip_forward = 0
# Enables source route verification
net.ipv4.conf.default.rp_filter = 1
# Disables the magic-sysrq key
kernel.sysrq = 0
net.ipv4.ip_local_port_range = 1204 65000
net.core.rmem_max = 262140
net.core.rmem_default = 262140
net.ipv4.tcp_rmem = 4096 131072 262140
net.ipv4.tcp_wmem = 4096 131072 262140
net.ipv4.tcp_sack = 0
net.ipv4.tcp_timestamps = 0
net.ipv4.tcp_window_scaling = 0
net.ipv4.tcp_keepalive_time = 60000
net.ipv4.tcp_keepalive_intvl = 15000
net.ipv4.tcp_fin_timeout = 30

Add the following as the last entry in /etc/rc.local
sysctl -p /etc/sysctl.conf
Reboot the system.

Use this command to increase the size of the transmit buffer:

tcp_recv_hiwat ndd /dev/tcp 8129 32768

Make the OS to use swap file only on emergencies:
swappiness=0
swap off; swap on

7. Disable the Security Manager only if your application server is inside an intranet or inside a very well protected environment (If you are sure that no malicious code will be run on the server and you do not use authentication within your application, then you can disable the security manager). It is generally not recommended but it could provide a significant performance boost (since the security manager has expensive calls).
Configurations > config-name > JVM Settings (JVM Options)
delete the option that contains the following text:
-Djava.security.manager


8. Performance monitoring tools:
jconsole : jmx instance monitoring
jvisualvm : will give you a clear view of the cpu utilization, the garbage collections, perm gen size and jvm options. It can also profile and create thread dumps.
Applications Manager : is a nice commercial monitoring tool. Has good support for GlassFish (There is a Free Licence for up to 5 Glassfish instances through jmx).
nmon : nice open source linux monitoring command line gui.

9. Disable monitoring if you have no problems to detect and resolve.
Configurations > config-name > Monitoring
Change all levels to Low if you still need a little monitoring, or Off if your applications are running smoothly.

10. Update your software as often as your infrastructure availability/downtime permits. Update your jdk, since bug fixes and optimizations may increase the performance of your application server and make some weird errors go away! The same goes for the operating system, as well as the jdbc drivers or any other libraries your applications use.

11. Patch Glassfish 2.1.x with the latest Grizzly 1.0.x releases.
The Grizzly thread manager library is the heart of GlassFish. Since oracle is not planning to release another v2 release, this kind of patch is significant and relatively easy. Unless you decide to move on to v3 release!

First Check the current Grizzly version by setting the JVM property: "-Dcom.sun.enterprise.web.connector.grizzly.displayConfiguration=true".
Make sure the web-container log level is INFO. Restart Glassfish instance and check server.log. You should see an output like this :

Grizzly 1.0.30 running on Mac OS X-10.5.8 under JDK version: 1.6.0_15-Apple Inc.
port: 8080
maxThreads: 5
ByteBuffer size: 4096
useDirectByteBuffer: 8192
maxKeepAliveRequests: 250
keepAliveTimeoutInSeconds: 30
Static File Cache enabled: false
Pipeline : com.sun.enterprise.web.portunif.PortUnificationPipeline
Round Robin Selector Algorithm enabled: false
Round Robin Selector pool size: 1
Asynchronous Request Processing enabled: true|#]

where Grizzly version is 1.0.30. Please note, that if you'll see a similar output, but without Grizzly version in it, it means that your version is older than 1.0.30, so a Grizzly upgrade is recommended. Download latest Grizzly 1.0.x binary file from:
http://download.java.net/maven/2/com/sun/grizzly/grizzly-framework-http/
and save it to a directory, for example :
/home/gfuser/grizzly/grizzly-framework-http-1.0.30.jar

Then set Glassfish prefix-classpath to "/home/gfuser/grizzly/grizzly-framework-http-1.0.30.jar" to force Glassfish use the latest Grizzly classes instead of the embedded ones. Restart Glassfish and check the server.log again to confirm the success of the patch. Reset the web-container log level to SEVERE.


Further reading.

Java Tuning White Paper :
http://java.sun.com/performance/reference/whitepapers/tuning.html

Frequently Asked Questions about Garbage Collection :
http://www.oracle.com/technetwork/java/faq-140837.html

Tuning Garbage Collection :
http://www.oracle.com/technetwork/java/gc-tuning-5-138395.html
 
Java HotSpot VM Options :
http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html

Sun Java System Application Server 9.1 Performance Tuning Guide :
http://download.oracle.com/docs/cd/E19159-01/819-3681/


Any comments, suggestions, problems or requests will be warmly welcomed.

p.s.
You can find me on fiverr for more personalized requests on any java app server configuration problem or java error that you encounter, with deliverance of less than a day (true!) and money back guarantee if not satisfied.



Wednesday, November 24, 2010

Install Apache Geronimo (as service) on Ubuntu Linux

Apache Geronimo is an Open Source J2EE server. And it can be installed rather easily on Ubuntu Linux (10.04).

As a reminder, the following instructions presume that one uses its current ubuntu account. For an enterprise environment it is recommended to create a new user account, for example g_user, that will own all the geronimo files and will start and stop the server (will be referred from now on as GERONIMO_OWNER and ${user}) and add this user to the sudoers as needed.


- First step is to install sun java.
sudo add-apt-repository "deb http://archive.canonical.com/ lucid partner"
sudo apt-get update
sudo apt-get install sun-java6-jdk


- Second step is to download and extract (install) Geronimo:
Download from :
http://geronimo.apache.org/apache-geronimo-v22-release.html
I downloaded the latest stable release with tomcat:
geronimo-tomcat6-javaee5-2.2-bin.tar.gz

Then md5sum it (to gain problem-solving time):
md5sum geronimo-tomcat6-javaee5-2.2-bin.tar.gz
and crosscheck it with the md5 sum on the site.

Extract the archive:
tar -xvzf geronimo-tomcat6-javaee5-2.2-bin.tar.gz

Rename the extracted directory to something smaller:
mv geronimo-tomcat6-javaee5-2.2 geronimo.2.2
From now on when we will refer to the full path of the geronimo.2.2 directory as ${GERONIMO_HOME}.
 
Open .bashrc file:
gedit /home/${user}/.bashrc

Add JAVA_HOME, JRE_HOME and JAVA_OPTS at the end of .bashrc:
export JAVA_HOME=/usr/lib/jvm/java-6-sun   
export JRE_HOME=/usr/lib/jvm/java-6-sun/jre
export JAVA_OPTS="-Xmx256m -XX:MaxPermSize=128m"
Run .bashrc (just this once):
. .bashrc
Or close the terminal and open a new one.

- Last step is to start the server:
cd ${GERONIMO_HOME}/bin
./geronimo start

And the server is up and running!
You can browse the Administration console at
http://localhost:8080/
Click the link "Administration -> console" on the left.
Provide the default credentials :
system/manager
And geronimo is at your disposal!

To maximize security, it is time to change the default admin username and password. You need to stop geronimo:
cd ${GERONIMO_HOME}/bin
./geronimo.sh stop --user system --password manager
Open user/passwords file
gedit ${GERONIMO_HOME}/var/security/users.properties
and add a new line with the new administrator user and his password like this:
g_admin=g_admin_pass
Next time you start the server the password will be automatically encrypted.
Open permission/groups file:
gedit ${GERONIMO_HOME}/var/security/groups.properties
Assign administration and monitoring privileges only to the new user. Change the two uncommented lines like this:
admin=g_admin
monitor=g_admin
Lastly you should change the file permissions on these files:
chmod -R 600 ${GERONIMO_HOME}/var/security

To create a service in order to automate startup open/create the following file:
sudo gedit /etc/init.d/geronimo2
Add the following code. You only need to set correctly for your system the variables GERONIMO_HOME, GERONIMO_OWNER, GERONIMO_ADMIN and GERONIMO_PASS inside the script.

#!/bin/bash
# chkconfig: 234 20 80
# description: Geronimo Server start/stop script
# processname: geronimo2

JAVA_HOME=/usr/lib/jvm/java-6-sun
JRE_HOME=/usr/lib/jvm/java-6-sun/jre
JAVA_OPTS="-Xmx256m -XX:MaxPermSize=128m"

GERONIMO_HOME=/home/gfuser/geronimo.2.2
GERONIMO_OWNER=g_user
GERONIMO_ADMIN=g_admin
GERONIMO_PASS=g_admin_pass

export JAVA_HOME JRE_HOME JAVA_OPTS GERONIMO_HOME GERONIMO_OWNER GERONIMO_ADMIN GERONIMO_PASS

start() {
  geronimo_state=`ps -ef | grep "geronimo" | grep "/bin/server.jar" | grep -v grep | wc -l`
  if [ $geronimo_state -gt 0 ]; then
    echo "Geronimo is already UP!"
  else 
    echo -n "Starting geronimo: "
    cd $GERONIMO_HOME/bin
    su $GERONIMO_OWNER -c "$GERONIMO_HOME/bin/geronimo.sh start"
    sleep 20
    echo "done."
  fi
}

stop() {
  geronimo_state=`ps -ef | grep "geronimo" | grep "/bin/server.jar" | grep -v grep | wc -l`
  if [ $geronimo_state -gt 0 ]; then
    echo -n "Gracefully stoping geronimo: "
    su $GERONIMO_OWNER -c "$GERONIMO_HOME/bin/geronimo.sh stop --user $GERONIMO_ADMIN --password $GERONIMO_PASS"
    sleep 10
    echo "done."
  else
    echo "Geronimo is already DOWN!"
  fi
}

force_stop() {
  geronimo_state=`ps -ef | grep "geronimo" | grep "/bin/server.jar" | grep -v grep | wc -l`
  if [ $geronimo_state -gt 0 ]; then
    echo -n "Forcefully stoping geronimo: "
    su $GERONIMO_OWNER -c "$GERONIMO_HOME/bin/geronimo.sh stop --force --user $GERONIMO_ADMIN --password $GERONIMO_PASS"
    echo "done."
  else
    echo "Geronimo is already DOWN!"
  fi
}

status() {
  geronimo_state=`ps -ef | grep "geronimo" | grep "/bin/server.jar" | grep -v grep | wc -l`
  if [ $geronimo_state -gt 0 ]; then
    echo "Geronimo is UP!"
  else
    echo "Geronimo is DOWN!"
  fi
}

case "$1" in
  start)
    start
;;
  stop)
    stop
;;
  status)
    status
;;
  force_stop)
    force_stop
;;
  restart)
    stop
    sleep 2
    start
;;
  *)
  echo "Usage: $0 {start|stop|force_stop|restart|status}"
esac

exit 0

Now you need to change the file permissions:
sudo chmod 755 /etc/init.d/geronimo2

Next create the upstart conf file:
sudo gedit /etc/init/geronimo2.conf
and add the following code

# geronimo2

start on runlevel [2345]
stop on runlevel [16]

respawn

pre-start exec /etc/init.d/geronimo2 start
post-stop exec /etc/init.d/geronimo2 stop


Reload upstart configuration:
sudo initctl reload-configuration
Start geronimo service :
sudo initctl start geronimo2

And the geronimo service is securely installed and will be started on every boot.

p.s.
You can find me on fiverr for more personalized requests on any java app server configuration problem or java error that you encounter, with deliverance of less than a day (true!) and money back guarantee if not satisfied.

Sunday, November 21, 2010

GlassFish 2 Cluster Configuration on the Same Machine

This tutorial will guide you through a GlassFish 2.1.1 Cluster with two instances on the same machine. We are going to use the CLI interface to make our life simpler.
[Whenever you encounter the \ symbol in one of the commands, it means that the command continues on the following line. So you have to copy both lines (including the \ symbol) at your terminal.]
After a successful installation of glassfish with cluster profile (setup-cluster.xml), as explained on the download page:

https://glassfish.dev.java.net/downloads/v2.1.1-final.html

Go to directory ${GF_HOME}/bin and delete default domain domain1 (or you can just ignore it).
asadmin delete-domain domain1
and create a new domain with adminport 4000, name das :
asadmin create-domain --adminport 4000 --profile cluster das
Use the following credentials (or your own, just make sure to make the changes on the password file later on)
Admin user : admin
Admin pass : admin111
Master pass : admin111
We are going to use a password file inside ${GF_HOME}/bin in order to make the steps quicker with the following three lines :
AS_ADMIN_ADMINPASSWORD=admin111
AS_ADMIN_PASSWORD=admin111
AS_ADMIN_MASTERPASSWORD=admin111
You should better change the file preferences so that no one else can view this file except the GF admin:
chmod 600 passwords
First step is to start the new domain:
asadmin start-domain --user admin --passwordfile passwords das
Create the first node agent, connecting on DAS at 4000 port, (and then start it):
asadmin create-node-agent --user admin --port 4000 \
   --passwordfile passwords agent1
asadmin start-node-agent --user admin --passwordfile passwords agent1
Create the cluster farm named cl1 (connecting on DAS at 4000 port) that will group both of the clustered instances:
asadmin create-cluster --user admin --passwordfile passwords \
   --port 4000 cl1
Create the first instance (gf1 on http port 9080) and the second instance (gf2 on http port 9090) that communicate to the domain (DAS on port 4000) through the node agent (agent1) and reference our cluster (cl1):
asadmin create-instance --user admin --passwordfile passwords \
   --port 4000 --nodeagent agent1 --systemproperties \
   HTTP_LISTENER_PORT=9080 --cluster cl1 gf1
and
asadmin create-instance --user admin --passwordfile passwords \
   --port 4000 --nodeagent agent1 --systemproperties \
   HTTP_LISTENER_PORT=9090 --cluster cl1 gf2
Last step is to start the cluster and the instances with the following command:
asadmin start-cluster --user admin --port 4000 \
   --passwordfile passwords cl1
Now when you point your browser to http://localhost:4000/ and login as admin/admin111 you will see on your left the "Clusters" Task, with cl1 child. And cl1 will have two children gf1 and gf2. To deploy an application to the cluster, all you need to do is remove the target "server" and add the target "cl1" (either at deployment or after deployment).
You will also see the "Node Agents" Task that has the agent1 node agent.
Here are the startup commands :
asadmin start-domain --user admin --passwordfile passwords das
asadmin start-node-agent --user admin --passwordfile passwords agent1
asadmin start-cluster --port 4000 --passwordfile passwords cl1
and the shutdown commands:
asadmin stop-cluster --user admin --passwordfile passwords cl1
asadmin stop-node-agent agent1 
asadmin stop-domain das


p.s.
Here are all the commands one after another in order to run them as a script:

asadmin create-node-agent --user admin --port 4000 --passwordfile passwords agent1
asadmin start-node-agent --user admin --passwordfile passwords agent1
asadmin create-cluster --user admin --passwordfile passwords --port 4000 cl1
asadmin create-instance --user admin --passwordfile passwords --port 4000 \
  --nodeagent agent1 --systemproperties HTTP_LISTENER_PORT=9080 --cluster cl1 gf1
asadmin create-instance --user admin --passwordfile passwords --port 4000 \
  --nodeagent agent1 --systemproperties HTTP_LISTENER_PORT=9090 --cluster cl1 gf2
asadmin start-cluster --user admin --port 4000 --passwordfile passwords cl1
And the shutdown-delete commands in order to clean up your installation.

asadmin stop-cluster --user admin --passwordfile passwords cl1
asadmin stop-node-agent agent1 
asadmin delete-instance --user admin --passwordfile passwords --port 4000 gf1
asadmin delete-instance --user admin --passwordfile passwords --port 4000 gf2
asadmin delete-cluster --port 4000 --user admin --passwordfile passwords cl1
asadmin delete-node-agent agent1
asadmin delete-node-agent-config --port 4000 --user admin --passwordfile passwords agent1
asadmin stop-domain das
asadmin delete-domain das


p.s.
You can find me on fiverr for more personalized requests on any java app server configuration problem or java error that you encounter, with deliverance of less than a day (true!) and money back guarantee if not satisfied.

Thursday, October 7, 2010

Compile apache 2 with mod_deflate on Linux


I have always had trouble finding a simple "How to" to compile apache with exactly what I needed, meaning the common modules plus the mod_deflate. It turns out it is very simple. And that is probably why no one has bothered putting down the steps.

This installation will install apache 2.0.63 and zlib 1.2.5, on an ubuntu 10.04 machine. But I can rather safely presume, that the following steps will be the same for any *nix that has already installed the c compiler.

First of all, I downloaded the latest apache source package from httpd.apache.org [ http-2.0.63.tar.gz ].

Next , I downloaded the latest zlib source package from zlib.net [ zlib-1.2.5.tar.gz ].

I copied both packages inside /opt/packages and run the following commnads from a terminal:

cd /opt/packages
tar -xvf httpd-2.0.63.tar.gz
tar -xvf zlib-1.2.5.tar.gz

cd zlib-1.2.5
./configure –prefix=/usr/local/zlib
make
sudo make install

cd ../httpd-2.0.63

(The following three lines is one command. Just copy it with the slashes and it will run correctly. Slash tells the terminal that the command will continue in the next line!)
./configure --prefix=/usr/local/apache2 \
--enable-mods-shared="all" --enable-deflate \
–with-z="/usr/local/zlib"

make
sudo make install

So zlib is now installed in /usr/local/zlib and apache inside /usr/local/apache2 which are the default install locations.

And now to enable mod_deflate for most common files by editing httpd.conf:

LoadModule deflate_module /usr/lib/apache2/modules/mod_deflate.so
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/javascript text/css application/javascript application/x-javascript

I hope this little "how to" will save you a lot of time and trouble.
Especially for all of you making your first steps with apache.
 

p.s.
You can find me on fiverr for more personalized requests on any java app server configuration problem or java error that you encounter, with deliverance of less than a day (true!) and money back guarantee if not satisfied.
 

Saturday, July 17, 2010

Configure MySQL Connection Pool in Glassfish V3

The MySQL connection pool in GlassFish V3, is actually as easy as it was in V2!

First of all, we need to download from www.mysql.com the latest jdbc driver:

http://dev.mysql.com/downloads/connector/j/5.1.html

Extract the downloaded archive and take the mysql-connector-java-x.x.x-bin.jar from the compressed archive and put it in {glassfish_installation}/glassfish/lib directory and restart glassfish (from {glassfish_installation}/glassfish/bin directory):

asadmin stop-domain domain1
asadmin start-domain domain1

Now we need to navigate to the administrator application:
http://localhost:4848/
 
Open the 'Resources' -> 'JDBC' -> 'Connection Pools' and select 'New'.
Fill in the Connection Pool 'Name' with a suitable name like MySQLPool.
Select 'Resource Type' : 'javax.sql.DataSource'.
Select 'Database Vendor' : 'MySQL'.
Select 'Next'.

At the next page go down at the additional Properties.
Find and edit the following properties :
Fill in property 'User' with the 'Value' : {db_user}
Fill in property 'Password' with the 'Value' : {db_user_pass}
Fill in property 'URL' with the 'Value' :
jdbc:mysql://[host]:[port]/[database name]
Select 'Finish'.

Navigate to Connection Pools and select the pool you just created.
Click Ping to test that it is working. If it is not, it is probably because you have mistyped the connection credentials. Go to 'Additional Properties' tab of the connection pool detail page and correct any errors. Try ping again.

Open the 'Resources' -> 'JDBC' -> 'JDBC Resources' and select 'New.
Fill the JNDI Name like 'jdbc/myconnnection'.
Select from 'Pool Name' combo box the pool we just created.
And select 'OK'.

The Connection Pool is ready!


p.s.
You can find me on fiverr for more personalized requests on any java app server configuration problem or java error that you encounter, with deliverance of less than a day (true!) and money back guarantee if not satisfied.

Tuesday, May 18, 2010

Cuda 3.0 installation on Ubuntu Linux 10.04

I need to point out, that it is somewhat appalling the need to write a new tutorial for every time either a linux version or a product (pick your favourite) version is released. That said, I am off to provide the tutorial.

I had to read many tutorials and walkthroughs, as well as forum threads to succeed in the installation. So some parts might look very familiar!

First of all we will need to install the cuda graphics driver. Afterwards the cuda toolkit, followed by the cuda sdk. Finally we 'll install gcc 4.3 beacuse Cuda cannot cooperate with gcc 4.4 with which Ubuntu 10.04 ships. The linux version I am using is i386. I presume the instructions will work as well with x86_64 kernel.

Go to the official nvidia-CUDA download page:
http://developer.nvidia.com/object/cuda_3_0_downloads.html#Linux

Download the CUDA Toolkit and the CUDA SDK:

CUDA Toolkit for Ubuntu Linux 9.04 (32-bit)
GPU Computing SDK code samples and more

-----------------------------
Installing the NVIDIA driver:
-----------------------------
We'll need the latest cuda development driver available (195.xx), but first we'll uninstall the existing drivers.

1. Uninstall existing NVIDIA drivers and nvidia-glx.

(if you have enabled nvidia in system->administration->hardware drivers, then disable them first and possibly reboot)

sudo apt-get purge nvidia-*

2. Stop gdm service by running

sudo service gdm stop

3. Install drivers from nvidia repository

sudo add-apt-repository ppa:nvidia-vdpau/ppa
sudo apt-get update
sudo apt-get install nvidia-185-modaliases nvidia-glx-185 nvidia-settings
sudo nvidia-xconfig

4. Reboot and log back in.

5. Run

nvidia-settings

to verify that your driver version is at least 195. Look for the driver version in the window:
The 195.xx NVIDIA Driver for use with CUDA.

----------------------------
Installing the CUDA Toolkit:
----------------------------

After having installed the driver we now need to install the CUDA toolkit itself.

1. Run:

sudo sh cudatoolkit_3.0_linux_32_ubuntu9.04.run

2. Press enter to install at the default location.

/usr/local/cuda

3. Register the new library files:

sudo gedit /etc/ld.so.conf.d/cuda.conf &

and add the following to the empty file

/usr/local/cuda/lib

Save the file and close gedit.
Then run:

sudo ldconfig

Create a link to the libcuda.so library:

cd /usr/lib
sudo ln -s nvidia-current/libcuda.so libcuda.so

Also add to the end of your ~/.bashrc file.

export PATH=/usr/local/cuda/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/cuda/lib

restart bash

----------------------------------------------------------
Installing the CUDA SDK and Compiling the Example Programs
----------------------------------------------------------

We will now install the CUDA SDK to our own home directory (we can experiment with the supplied demos):

1. Install SDK to the default location

sh gpucomputingsdk_3.0_linux.run

2. As CUDA does not yet work with GCC 4.4 we will have to install gcc-4.3:

sudo apt-get install gcc-4.3 g++-4.3 g++-4.4
sudo update-alternatives --remove-all gcc
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.3 43 --slave /usr/bin/g++ g++ /usr/bin/g++-4.3 --slave /usr/bin/gcov gcov /usr/bin/gcov-4.3
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.4 44 --slave /usr/bin/g++ g++ /usr/bin/g++-4.4 --slave /usr/bin/gcov gcov /usr/bin/gcov-4.4
sudo update-alternatives --config gcc ### choose gcc 4.3

3. Install CUDA SDK requirements

sudo apt-get install libglut3-dev libxi-dev libxmu-dev

4. Go to SDK source dir:

cd ~/NVIDIA_GPU_Computing_SDK/C$

5. You should now be able to compile everything by running

make

This should now compile all the examples in the SDK without errors.

---------------------------------------------
Verify Installation
---------------------------------------------

We can now verify that everything is working:

1. Run (from ~/NVIDIA_GPU_Computing_SDK/C):

bin/linux/release/deviceQuery

On my machine I get the following output (depending on your harware, you output may be different. mine is a GeForce 8500 GT):

------------------------------------------------
bin/linux/release/deviceQuery Starting...

CUDA Device Query (Runtime API) version (CUDART static linking)

There is 1 device supporting CUDA

Device 0: "GeForce 8500 GT"
CUDA Driver Version: 3.0
CUDA Runtime Version: 3.0
CUDA Capability Major revision number: 1
CUDA Capability Minor revision number: 1
Total amount of global memory: 536150016 bytes
Number of multiprocessors: 2
Number of cores: 16
Total amount of constant memory: 65536 bytes
Total amount of shared memory per block: 16384 bytes
Total number of registers available per block: 8192
Warp size: 32
Maximum number of threads per block: 512
Maximum sizes of each dimension of a block: 512 x 512 x 64
Maximum sizes of each dimension of a grid: 65535 x 65535 x 1
Maximum memory pitch: 2147483647 bytes
Texture alignment: 256 bytes
Clock rate: 1.57 GHz
Concurrent copy and execution: Yes
Run time limit on kernels: Yes
Integrated: No
Support host page-locked memory mapping: No
Compute mode: Default (multiple host threads can use this device simultaneously)

deviceQuery, CUDA Driver = CUDART, CUDA Driver Version = 134566327, CUDA Runtime Version = 3.0, NumDevs = 1, Device = GeForce 8500 GT


PASSED

Press to Quit...
-----------------------------------------------------------
-----------------------------------------------------------

That was it. It was a little hard, but it is worth the effort.

Let us only hope that we will not be obligated to write a new one for every release!!!

Monday, May 17, 2010

Load Oracle OCI driver on GlassFish (linux)

I had a really hard time finding the way to load the Oracle native libraries (Oracle runtime 10gR2 installation) on GlassFish (2.1.1) in linux (CentOS 5.4). Apparently GlassFish ignores the famous LD_LIBRARY_PATH variable for unknown reasons. I even tried setting it at the system wide profile. Nothing worked.

The java error was :
java.lang.UnsatisfiedLinkError: no ocijdbc10 in java.library.path

I wrote a small java class that loaded the oci driver successfully. I was sure the parameters were correct. GlassFish still ignored them. I realised that GlassFish was the problem. I tried setting -Djava.library.path. It still didn't work.

To make a long story short the answer is to set it at the GlassFish Admin GUI :
Configuration -->
server-config -->
JVM-settings -->
Tab: Path Settings -->
Native Library Path Prefix : /path/to/oracle/client/installation/lib

I hope this will save you the time I spent searching fruitlessly the internet.
Cheers

p.s.Do not forget to give the Oracle native libraries the rx permissions to the FlassFish Admin user!

p.s.2
You can find me on fiverr for more personalized requests on any java app server configuration problem or java error that you encounter, with deliverance of less than a day (true!) and money back guarantee if not satisfied.

Tuesday, March 16, 2010

Run php pages on tomcat!

Today I feel the urge to congratulate some of our colleagues that strive to bring helpful extensions to our favourite open source software. The subject at hand is Tomcat and it's capability to run php!

As a java based server, tomcat serves jsp and java servlets. It has also embedded libraries for cgi should anyone would like to use it. But now an open source project called php-java-bridge brings php web projects to Tomcat. The installation is rather simple for a single php application, while making tomcat run php by default is hardly difficult!

I am not going to write any kind of tutorial this time, because the original tutorial that I have found here is complete.

Good job boys.
Keep Tomcat the best application server!

P.S.
I only need to add one thing missing from the tutorial mentioned. In my ubuntu box I needed first to install php5 and php-cgi (along with all its dependencies!) with:
sudo apt-get install php5 php-cgi


p.s.2
You can find me on fiverr for more personalized requests on any java app server configuration problem or java error that you encounter, with deliverance of less than a day (true!) and money back guarantee if not satisfied.

Sunday, March 7, 2010

Nmon on ubuntu 9.10

My favourite operating system is linux. At home I use ubuntu 9.10. A colleague of mine introduced me to a monitoring tool that can monitor almost anything! It is called nmon and it is provided by ibm as open source for linux. The latest binaries are for ubuntu 8.10 which do not work, so I had to compile from the source. I run onto a couple of problems and since I could not find anywhere a complete walkthrough for installing nmon in ubuntu, I decided to write one!

What we are going to need is g++, ncurses and nmon. What we are going to do is install g++, download ncurses, compile them and install them, and lastly we are going to compile nmon.

1) Open a terminal and run :
sudo apt-get install g++
2) download latest ncurses release (the moment this was written the ncurses-5.7.tar.gz was the latest) from ftp://ftp.gnu.org/gnu/ncurses/ and save it in a directory. For this example it will be inside /downloads
3) open a terminal and cd to the directory :
cd /downloads
4) Unzip and then untar the ncurses
gunzip ncurses-5.7.tar.gz
tar -xvf ncurses-5.7.tar
5) cd to the ncurses directory
cd ncurses-5.7
6) run configure and make
./configure
make
7) install as root
sudo make install
8) browse for nmon source code at http://nmon.sourceforge.net/pmwiki.php?n=Site.CompilingNmon
and
9) save lmon13d.c (or the latest source code) and makefile in /downloads
10) rename lmon13d.c to lmon.c
mv lmon13d.c lmon.c
11) make
make nmon_x86_ubuntu810
12) rename nmon_x86_ubuntu810
mv nmon_x86_ubuntu810 nmon
13) copy nmon to /usr/bin in order to be available in the path (or any other directory in the $PATH variable).

That is all. nmon is a rather complete tool for monitoring a linux system.
I hope you like it.

Wednesday, January 27, 2010

Comparing GlassFish and OAS costs

I made a comparison in one of my previous posts that needs some corrections. So I'll just start the comparison from the beginning to avoid any confusion.

The purpose of this post is to compare, from an application server administrator's perpspective, GlassFish and OAS. Say we have 55.000 Euros to spend for a linux application server, hardware and software.

In case we buy oas enterprise edition 10g, its price goes to about 25.000 Euros per core (More like per two cores according to Oracle). So with 50.000 Euros we get a dual core (4 cores) license and with the remaining 5.000 we can get a machine with the best quad core in the market, and 8GB of memory. Let's assume that the rest of the hardware will be the same.

In case we choose glassfish, the oracle ADF Framework licensing amounts to 4000 Euros per core (per two cores). So, with 40.000 Eurow we get a 10 core (20 cores) licensing and with the remaining 15.000 Euros we get a machine (from dell's site) with 20 cores (2x6cores + 2X4cores) and 40GB memory.

With both servers we get clustering and support. And I need to add that glassfish community support is as good as oracle's.

It doesn't matter how fast OAS is compared to GlassFish. It may even be twice as fast (which isn't true). With those money and GlassFish one can buy 5 times more cpu power and memory.

And as a last stroke, I need to add the yearly support fee to Oracle. Instead of paying support and licensing fees, which amount to about 20% the initial cost per year. If we save this money, we can invest them in a new system every four or five years. (And the rest of the money can go to seminars!)

A clear win for open source and glassfish against oracle application server!

Sunday, January 10, 2010

GlassFish and Toplink ( ..continued )

My experience with GlassFish has increased since my last post.

There is already an ADF Faces - JPA eclipselink application that runs smoothly now for a few weeks on GlassFish. The only problem that came up after the successful code tests, was the Connection Pool leakage. There are some differences between the OAS and the GlassFish Connection Pooling. As a result, I had to tweak the preferences a little. In the 'General' tab I disabled the 'Connection Validation Required' checkbox to save time on connection gets. Also, at the 'Advanced' tab I set the 'Leak Reclaim' to true and the 'Leak Timeout' to 120 secs. The leak timeout may vary depending on the application. These two tweaks have stabilized the application.

The other important thing that I need to mention, is the difficulty that I found in installing two different versions of toplink. So the workaround is to install a new GlassFish installation for every toplink version (because the toplink libraries are installed in the installations's lib directory). I am lucky to have only two toplink versions (10.1.3.5 and 10.1.3.3) to handle!

But it is a serious thing to be considered in the following GlassFish versions: The library loader per version and the grouping of libraries. It is the one thing that I miss OAS for!


p.s.
You can find me on fiverr for more personalized requests on any java app server configuration problem or java error that you encounter, with deliverance of less than a day (true!) and money back guarantee if not satisfied.

Tuesday, December 15, 2009

Firebird Connection Pool in Glassfish 2.x.x

We will create in a few easy steps a Firebird Connection Pool on GlassFish 2.1.1.

First of all, we need to download the latest jdbc driver from:

http://www.firebirdsql.org/index.php?op=files&id=jaybird

Extract the downloaded archive and take the jaybird-full-x.x.x.jar from the compressed archive and put in {glassfish}/lib directory and restart glassfish:

asadmin stop-domain domain1
asadmin start-domain domain1

Now we need to navigate to the administrator application:
http://localhost:4848/
 
Open the 'Resources' -> 'JDBC' -> 'Connection Pools' and select 'New.
Fill in the Connection Pool 'Name'.
Select 'Resource Type' : 'javax.sql.ConnectionPoolDataSource'.
Select 'Next'.

At the next page complete the 'Datasource Classname' with :

org.firebirdsql.pool.sun.AppServerConnectionPoolDataSource

Then go down at the additional Properties.
Find and edit the following properties :
Select 'Name' : 'userName' and 'Value' : {db_user}
Select 'Name' : 'password' and 'Value' : {db_user_pass}
Select 'Name' : 'databaseName' and 'Value' : {host_name}:{db_path}
for example:
localhost:/my_data_files/mydb.fdb
Select 'Finish'.

Navigate to Connection Pools and select the pool you just created.
Click Ping to test that it is working. If it is not, it is probably because you have mistyped the connection credentials. Go to 'Additional Properties' tab of the connection pool detail page and correct any errors. Try ping again.

Open the 'Resources' -> 'JDBC' -> 'JDBC Resources' and select 'New.
Fill the JNDI Name like 'jdbc/myconnnection'.
Select from 'Pool Name' combo box the pool we just created.
And select 'OK'.

The Connection Pool is ready!


p.s.
You can find me on fiverr for more personalized requests on any java app server configuration problem or java error that you encounter, with deliverance of less than a day (true!) and money back guarantee if not satisfied.

Monday, December 14, 2009

Create Postgresql Connection Pool in Glassfish 2.x.x

We will create a PostgreSQL (8.4) Connection Pool on a GlassFish 2.1.1 [and GlassFish v3].

First of all, we need to download the latest jdbc driver:

http://jdbc.postgresql.org/download.html

Copy the downloaded archive postgresql-x.x.-xxx.jdbc4.jar in {glassfish}/lib directory and restart glassfish:

asadmin stop-domain domain1
asadmin start-domain domain1

Now we need to navigate to the administrator application:
http://localhost:4848/
 
Open the 'Resources' -> 'JDBC' -> 'Connection Pools' and select 'New.
Fill in the Connection Pool 'Name'.
Select 'Resource Type' : 'javax.sql.DataSource'.
Select 'Database Vendor' : 'PostgreSQL'.
Select 'Next'.

At the next page go down at the additional Properties.
Find and edit the following properties :
Select 'Name' : 'User' and 'Value' : {db_user}
Select 'Name' : 'Password' and 'Value' : {db_user_pass}
Select 'Name' : 'DatabaseName' and 'Value' : {db_name}
Select 'Name' : 'ServerName' and 'Value' : {server_hostname}
If your dqatabase is not in the default port (5432) you might also need to edit the following attribute :
Select 'Name' : 'PortNumber' and 'Value' : {port_number}
Select 'Finish'.

Navigate to Connection Pools and select the pool you just created.
Click Ping to test that it is working. If it is not, it is probably because you have mistyped the connection credentials. Go to 'Additional Properties' tab of the connection pool detail page and correct any errors. Try ping again.

Open the 'Resources' -> 'JDBC' -> 'JDBC Resources' and select 'New.
Fill the JNDI Name like 'jdbc/myconnnection'.
Select from 'Pool Name' combo box the pool we just created.
And select 'OK'.

The Connection Pool is ready!


p.s.
You can find me on fiverr for more personalized requests on any java app server configuration problem or java error that you encounter, with deliverance of less than a day (true!) and money back guarantee if not satisfied.

Mysql Connection Pool in GlassFish 2.x.x

As a followup to a previous post, regarding the creation of an oracle connection pool in GlassFish 2.1.1, we will create a MySQL connection pool.

First of all, we need to download from www.mysql.com the latest jdbc driver:

http://dev.mysql.com/downloads/connector/j/5.1.html

Extract the downloaded archive and take the mysql-connector-java-x.x.x-bin.jar from the compressed archive and put in {glassfish}/lib directory and restart glassfish:

asadmin stop-domain domain1
asadmin start-domain domain1

Now we need to navigate to the administrator application:
http://localhost:4848/
 
Open the 'Resources' -> 'JDBC' -> 'Connection Pools' and select 'New.
Fill in the Connection Pool 'Name'.
Select 'Resource Type' : 'javax.sql.DataSource'.
Select 'Database Vendor' : 'MySQL'.
Select 'Next'.

At the next page go down at the additional Properties.
Find and edit the following properties :
Select 'Name' : 'User' and 'Value' : {db_user}
Select 'Name' : 'Password' and 'Value' : {db_user_pass}
Select 'Name' : 'URL' and 'Value' :
jdbc:mysql://[host]:[port]/[database name]
Select 'Finish'.

Navigate to Connection Pools and select the pool you just created.
Click Ping to test that it is working. If it is not, it is probably because you have mistyped the connection credentials. Go to 'Additional Properties' tab of the connection pool detail page and correct any errors. Try ping again.

Open the 'Resources' -> 'JDBC' -> 'JDBC Resources' and select 'New.
Fill the JNDI Name like 'jdbc/myconnnection'.
Select from 'Pool Name' combo box the pool we just created.
And select 'OK'.

The Connection Pool is ready!


p.s.
You can find me on fiverr for more personalized requests on any java app server configuration problem or java error that you encounter, with deliverance of less than a day (true!) and money back guarantee if not satisfied.

Install eclipselink in Glassfish 2.x.x

Installing eclipselink in glassfish is a piece of cake.

First step is to download the eclipselink.jar from :

http://www.eclipse.org/eclipselink/downloads/

Second step is to put ecllipselink.jar (some might also need the persistence.jar) in {glassfish_home}/lib so that the library is available to all domains.

Third step is to create a connection pool. Use the following tutorial for an oracle pool:

http://mariosgaee.blogspot.com/2009/12/oracle-connection-pool-in-glassfish.html

And last, deploy your eclipselink application.


p.s.
You can find me on fiverr for more personalized requests on any java app server configuration problem or java error that you encounter, with deliverance of less than a day (true!) and money back guarantee if not satisfied.

Monday, December 7, 2009

Oracle Connection Pool in GlassFish 2.x.x

Glassfish does not ship with oracle jdbc drivers. The oracle driver needs to be added manually.  The driver can be found either in a JDeveloper or oracle client or database installation in {install_path}/jdbc/lib, or from oracle's site:

http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/htdocs/jdbc_10201.html

Glassfish needs at least ojdbc14.jar to work properly. Older drivers do not work. Put the ojdbc14.jar in {glassfish}/lib directory and restart glassfish:

asadmin stop-domain domain1
asadmin start-domain domain1

Now you need to navigate to the administrator application:
http://localhost:4848/
 
Open the 'Resources' -> 'JDBC' -> 'Connection Pools' and select 'New.
Fill in the Connection Pool 'Name'.
Select 'Resource Type' : 'javax.sql.ConnectionPoolDataSource'.
Select 'Database Vendor' : 'Oracle'.
Select 'Next'.

At the next page go down at the additional Properties.
Select all the properties and select 'Delete Properties'.
Select 'Add Property', fill 'Name' : 'user' and 'Value' : {db_user}
Select 'Add Property', fill 'Name' : 'password' and 'Value' : {db_user_pass}
Select 'Add Property', fill 'Name' : 'url' and 'Value' :
jdbc:oracle:thin:@[host][:port]:SID
or
jdbc:oracle:thin:@//[host][:port]/SID
Select 'Finish'.

Navigate to Connection Pools and select the pool you just created.
Click Ping to test that it is working. If it is not, it is probably because you have mistyped the connection credentials. Go to 'Additional Properties' tab of the connection pool detail page and correct any errors. Try ping again.

Open the 'Resources' -> 'JDBC' -> 'JDBC Resources' and select 'New.
Fill the JNDI Name like 'jdbc/myconnnection'.
Select from 'Pool Name' combo box the pool we already created.
And select 'OK'.

The Connection Pool is ready!


p.s.
You can find me on fiverr for more personalized requests on any java app server configuration problem or java error that you encounter, with deliverance of less than a day (true!) and money back guarantee if not satisfied.

GlassFish and Adf Toplink 10g (2)

As a followup to the previous post I feel the obligation to add my testing experience of a small but full featured ADF Faces and ADF Toplink application in glassfish.

The basic problem I stumbled upon was the External Transaction Controller. Toplink.jar does not provide a TransactionController for GlassFish, although there is one for Oc4j, JBoss, WebSphere and Weblogic. As a result, we have to create one on our own.

The way to call the Transaction Manager in Glassfish is:
java:appserver/TransactionManager

We need to create a new class named GFTransactionController:
===============================================v
package oracle.toplink.transaction.gf;

import javax.transaction.TransactionManager;
import oracle.toplink.transaction.JTATransactionController;

public class GFTransactionController extends JTATransactionController {

public GFTransactionController() { }

protected TransactionManager acquireTransactionManager() throws Exception {
return (TransactionManager)jndiLookup("java:appserver/TransactionManager");
}

public static final String JNDI_TRANSACTION_MANAGER_NAME = "java:appserver/TransactionManager";
}

===============================================
In order to compile this class one needs toplink.jar ({jdev_install}/toplink/jlib) and j2ee.jar ({glassfish_install}/lib) in the classpath.
Then we open toplink.jar (the one inside glassfish) with winrar. We navigate to folder oracle/toplink/transaction. Right click --> Create new folder --> gf. Navigate to gf and drag and drop the GFTransactionController.class file inside. Our new toplink.jar is ready. We copy the new toplink.jar in {glassfish_install}/lib.

We also need to change the Transaction Controller in our project.
Open your adf model project in Jdeveloper and follow these instructions:
===============================================
1. In the Applications Navigator, select DataModel --> Application Sources --> TopLink.
2. Select sessions.xml. In the Structure pane, double-click 'default' (or whatever you have named it).
3. On the General page, select the External Transaction Controller check box in Options.
4. Enter the following transaction class:
oracle.toplink.transaction.gf.GFTransactionController

===============================================

The other problem that I found was at web.xml. JDeveloper creates by default a new web project with a 2.4 xsd for web.xml. We need to change that to a 2.5 xsd. So we open our web.xml and replace our
===============================================
< web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" >
===============================================
with
===============================================
< web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5" >
===============================================

Now redeploy your project and all ejb junctionality is working correctly.

Another minor change is the result of this command: getServletConfig().getServletContext().getRealPath("/test/");
Oc4j returns a slash at the end, while Glassfish does not. A simple solution is to add the last slash after the command:
getServletConfig().getServletContext().getRealPath("/test")+"/";

As I have already mentioned in a previous post, 90% of the problems is a path translation error, because the two servers handle paths a little differently.

As a conlcusion, I need to note that GlassFish can successfully run an ADF Faces with ADF Toplink (EJB 3) Application with only a few configuration changes and some slight code modifications! Apart from TransactionController, all the others pass in OC4J too. So, there is no need to start using glassfish as a testing server if you are already using JDeveloper!


p.s.
You can find me on fiverr for more personalized requests on any java app server configuration problem or java error that you encounter, with deliverance of less than a day (true!) and money back guarantee if not satisfied.

Sunday, December 6, 2009

GlassFish and Adf Toplink 10g

After my success in deploying an ADF Faces web application in Glassfish (2.1.1), I got a crazy idea. Why not try deploying an ADF Faces with ADF Toplink (EJB 3.0 SessionBean with Pojos) enterprise application in GlassFish? Oracle has deploying instructions for JBoss and WebLogic. What these application Servers have more than GlassFish? Exactly. Nothing!

So I put my thoughts into work. The first success came when I put toplink.jar in ${glassfish}/lib, restarted the server and the model was successfully deployed with no errors! Then I started adding one by one all the runtime libraries that where reported missing by glassfish deployer. Finally I reached a point where deployment was successful, but there were still runtime errors. I continued adding more libraries, one by one. But when I added xmlparserv2.jar library I returned to square one. The deployment was once again unsuccessful. I googled the error:

------------------------------------------------
java.lang.UnsupportedOperationException: This parser does not support specification "null" version "null"
at javax.xml.parsers.DocumentBuilderFactory.setSchema(DocumentBuilderFactory.java:561)
...
-----------------------------------------------


All hits I got for this error was about using an older xml parser. But I could not figure out why. I searched inside the xmlparserv2.jar and found some javax.* classes apart from oracle.* classes. So I deleted all javax.* classes from inside the jar in order not to override the default classes, and I created a new xmlparserv2.jar (I also removed from xmlparserv2.jar the directory META-INF/services). I renamed it to oxmlparserv2.jar and added it to project libraries.

The application was deployed once again. I was really happy. But my troubles weren't over yet. Not even a simple query would run without giving the error:

----------------------------------------------
javax.servlet.ServletException: javax.el.MethodNotFoundException: Method not found: findItemByName.execute(javax.faces.event.ActionEvent)
root cause
javax.faces.el.MethodNotFoundException: javax.el.MethodNotFoundException: Method not found: findItemByName.execute(javax.faces.event.ActionEvent)
root cause
javax.el.MethodNotFoundException: Method not found: findItemByName.execute(javax.faces.event.ActionEvent)
----------------------------------------------


This was an even more obscure error. I presumed it would still have to do with some missing library. All I needed was to find which library. But there was no error 'noClassDefFoundError' to help me this time! Then I remembered that JDeveloper supports installing all of its runtime libraries to various applications servers, why not glassfish too? Since there is no glassfish installation process in JDeveloper, I improvised. I downloaded a JBoss v4 and installed it. I opened JDeveloper 10.1.3.5 and then I followed the menu:
Tools --> ADF Runtime Installer --> JBoss.
I completed the installation throught the wizard. Jdev then displayed a summary of the installed libraries. Based on this list I figured out that I only needed to use those libraries that were installed in {server}/default/lib directory of JBoss. The others did not seem very important. Here is a list of those that worked form me:

----------------------------------------------------
adf-connections.jar
adfbinding.jar
adfcm.jar
adfm.jar
adfmtl.jar
adfmweb.jar
adfshare.jar
adfui.jar
antlr.jar
bc4jct.jar
bc4jctejb.jar
bc4jdomgnrc.jar
bc4jdomorcl.jar
bc4jimdomains.jar
bc4jmt.jar
bc4jmtejb.jar
cache.jar
collections.jar
commons-cli-1.0.jar
commons-el.jar
concurrent.jar
dc-adapters.jar
dms.jar
http_client.jar
jazncore.jar
jdev-cm.jar
jsp-el-api.jar
libs.txt
mdsrt.jar
ojdbc14.jar
ojpse.jar
oracle-el.jar
oraclepki.jar
ordhttp.jar
ordim.jar
osdt_cert.jar
osdt_core.jar
osdt_saml.jar
osdt_wss.jar
osdt_xmlsec.jar
oxml.jar
oxmlparserv2.jar
runtime12.jar
share.jar
toplink-agent.jar
toplink.jar
translator.jar
xmlef.jar
xsqlserializers.jar
xsu12.jar
----------------------------------------------------


So I copied them to my {glassfish}/lib dir. Except for xml.jar and xmlparserv2.jar. For those two I deleted all javax.* classes from the jar and then I copied them with new names, as oxmlparserv2.jar and oxml.jar, in order to distinguish them in the future.

The result was astounding. The application was deployed successfully and run a query! Total Success!

All that is left to do now, is run thorough tests on every adf-toplink application that needs to be deployed in glassfish, so as to find any minor inconsistencies. As a hint, I have found that the path is handled differently between the two servers. This thought will solve almost 90% of the rest of the incompatibility problems.

Concluding, I need to say that glassfish server has already surpassed my expectations. It is a free open source application server that can compete evenly with other commercial application servers. And if it can run oracle's applications, then it can run any j2ee application!

I want to add as a last thought, as a big organization's application server administrator, a comparison, between glassfish and oas. Say we have 35.000 Euros to spent for a linux application server, hardware and software.

In case we buy oas enterprise edition, its price goes to about 15.000 Euros a core. So with 35.000 Euros we get a dual core license and that leaves 5.000 to get a machine with the best dual core in the market, and at least 10GB of memory. Let's assume that the rest of the hardware will be the same.

In case we choose glassfish, all the money goes to hardware. What do we buy with 35.000 Euros? Two machines (as I saw at dell's site) with 24 cores ( 4 x Intel 6cores) and 48GB memory each. Which sums up to 48 cores running almost at top speed and 96GB of memory. With both servers we get clustering and support. And I need to add that glassfish community support is as good as oracle's.

What I make of it? I don't care how fast oas is. It may even be twice as fast (or even thrice as fast) as glassfish. Who cares? With those money and glassfish one can buy 24 times more cpus and memory.

And as a last stroke, I need to add the yearly support fee to oracle. Instead of paying support and licensing fees, which amount in around 20% a year. If we save this money, we can invest them in a new system every four or five years. (And all the rest of the money can go to seminars!)

A clear win for open source and glassfish against oracle application server!


P.S.
There is an error in this comparison. While GlassFish is open source and therefore free, the use of ADF framework is not. I have a more accurate comparison here.