Questions ‘n’ Answers – Technology

Just another WordPress.com weblog

What are good Java Profiling Tools?

Posted by qnaguru on September 17, 2009

Java Profiling Tools included in JDK:

Visual VM – <JDK_HOME>\bin\jvisualvm.exe

This is a very good visual tool, that automatically connects to all local java processes and provides details on them.

JConsole – <JDK_HOME>\bin\jconsole.exe

This is very similar to Visual VM.

JStat - <JDK_HOME>\bin\jstat.exe

This is Java Virtual Machine statistics monitoring tool. You need to know jvmid of the java vm to use it.

JHat – <JDK_HOME>\bin\jhat.exe

This is a Java Heap Analysis Tool.

Other Java Profiling Tools:

StackProbe Profiler

http://www.stackprobe.com/

JRockit Mission Control

http://www.oracle.com/technology/products/jrockit/missioncontrol/index.html

Eclipse Memory Analyzer Tool

http://www.eclipse.org/mat/

YourKit Java Profiler

http://www.yourkit.com/

Posted in Java, Performance, Uncategorized | Tagged: , , , | Leave a Comment »

How can we get a thread dump of running java process

Posted by qnaguru on September 3, 2009

First find out java processes:

# jps
19420 MyServer
19843 Jps
8259 Bootstrap

Then using that process id, run jstack to get a thread dump:

# jstack 19420

NOTE: jps and jstack are JDK tools.

Another way to get a thread dump would be to use:

# kill -3 19420

Posted in Java, Performance, Uncategorized | Leave a Comment »

BlazeDS vs GraniteDS vs LCDS vs Red5 – how do they compare?

Posted by qnaguru on July 28, 2009

Tool RTMP HTTP Channels Java Remoting Audio/Video Scalability Licensing Author
BlazeDS No Yes Yes No Average Free Adobe
GraniteDS No Yes Yes No Average Free Franck Wolff
LCDS Yes Yes Yes No High License Adobe
Red5 Yes No Yes Yes ? Free Red5
Quick Summary follows…

BlazeDS – http://opensource.adobe.com/wiki/display/blazeds/BlazeDS/

  • Can scale to few hundred simultaneous connections.
  • Clustering is supported.
  • Automatic fall-back of channels is supported.
  • No support for NIO (used for supporting a large number of user threads, with a limited pool of server threads) – depends on Web Application Servers servlet thread pool to serve requests.

GraniteDS – http://www.graniteds.org

  • Has Granite Channels (http based). eg: Gravity Channel: similar to long polling of Blaze-DS. Used for data push
  • The primary goal of this project is to provide a framework for Flex 2+/EJB 3/Seam/Spring/Guice/POJO application development with full AMF3/RemoteObject benefits
  • No support for Servlet 3.0 (async) yet – it is in future roadmap i.e No support for NIO (used for supporting a large number of user threads, with a limited pool of threads) – depends on Web Application Servers servlet thread pool to serve requests.

LCDS – http://www.adobe.com/products/livecycle/dataservices/

  • Is the big daddy of Blaze-DS. In addition to all Blaze-DS functionality, it supports RTMP, and can serve a very large number of simultaneous requests (in the order of few thousands), which it achieves by its own NIO implementation i.e it internally uses a small number of threads to serve a very large number of requests (user threads).
  • Can be used in production, for free, on a single-cpu machine. For multiple cpu machines you need to buy license.

Red5 – http://osflash.org/red5

  • Supports Audio/Video streaming. Uses RTMP protocol.
  • Is probably the only popular free audio/video streaming tool.
  • Can be deployed as a web-application.

Posted in Collaboration, Flex Data Services | Tagged: , , , | Leave a Comment »

How do i allow/prevent remote connection to MySQL?

Posted by qnaguru on December 4, 2008

If you are not able to connect to MySQL(typically the error message will be ‘Access Denied’) from a remote host, you need to look into these:

Have you granted permission to connect from remote host ?

mysql> grant all on *.* to ‘<mysqluser>’@'<remoteHostName>’;

The above grants <mysqluser> to connect from <remoteHostName> to any database(*.*);

What does the above grant SQL actually do ?

It adds/updates the ‘user’ table in default mysql database (although you always see 0 rows affected upon running the grant sql!).

You can see this here (login as root):

mysql> use mysql;

mysql> select host, user, password from user;

In case this still does not work for you, the problem is most likely that you do not have the correct ‘host’, ‘user’ values sitting in that ‘user’ table.

try giving <remoteIPAddress> in place of <remoteHostName> while running the grant SQL.

Other things to look at:

See the following files:

/etc/hosts, /etc/hosts.allow, /etc/hosts.deny – check if the remote IP/Host has been explicitly denied access. 

Check if IPTables has a rule to block remote host:

# iptables -L

Posted in Linux, MySQL | Tagged: , | Leave a Comment »

How to prevent DOS (denial of service) attack?

Posted by qnaguru on November 25, 2008

Let us assume you are hosting a web-application using a Apache Server on a Linux machine. With this configuration you can use one of these to prevent such an attack:

(i) IP Tables – this works at very low network level.

(ii) Mod Security module (with apache) – this ofcourse works at web-server level.

(iii) Mod Evasive (with apache) – this ofcourse works at web-server level. This is closest to what you may need.

(iv) Dos Deflate – this is a script that runs regularly to find offenders and block them via IP Tables.

IP Tables

IP Tables is a Linux module which is normally available by default on Linux machines, if not; you can always install it. It is capable of analyzing (for source IP Address, destination IP Address, destination Port etc.) incoming packets and doing various things with them, like letting them in, rejecting them etc.

Here are some useful commands.

To log all incoming requests

iptables -I INPUT 1 -j LOG –log-level debug –log-prefix “IPTablesLog: “
iptables -I OUTPUT 1 -j LOG –log-level debug –log-prefix “IPTablesLog: “
iptables -I FORWARD 1 -j LOG –log-level debug –log-prefix “IPTablesLog: “

Configure the system log (you need to do this to see logs):

Add this line to /etc/syslog.conf (NOTE: there is a tab between ‘*.debug’ and ‘/var/log/iptables.log’ – and not a space.):
*.debug /var/log/iptables.log

Restart log service:

Restart Syslog
service syslog restart

Flush IP Tables (resets IP tables such that no rules apply):

# iptables -F

Restart IP Tables (any rules added from command line will be lost):

# service iptables restart

Log packets from/to a particular IP:
iptables -I INPUT -s <TheIPHere> -j LOG –log-level debug –log-prefix “IPTablesLog: “
iptables -I OUTPUT -d <TheIPHere> -j LOG –log-level debug –log-prefix “IPTablesLog: “
iptables -I FORWARD d <TheIPHere> LOG –log-level debug –log-prefix “IPTablesLog: “

Log Packets for a particular destination port (always use this as the last statement):
iptables -I INPUT -p tcp –dport 80 -j LOG –log-level debug –log-prefix “IPTablesLog: “

Reject Packets from a particular source for a particular destination port:
iptables -I INPUT -s <TheIPHere> -p tcp  –dport 80 -j REJECT –reject-with icmp-port-unreachable

iptables -A INPUT -s 192.168.0.121 -p tcp  –dport 80 -j DROP

Limit Packets for a particular destination port:
iptables -I INPUT -p tcp –dport 80 -m limit –limit 10/sec –limit-burst 10 -j ACCEPT

If you want to permanently add any of the above rules you can add them to the file:/etc/sysconfig/iptables. And then restart iptables. Note that order of the commands could be important.

Mod Security

This is an module that allows you to configure Apache in a variety of useful ways. For example, preventing uploads of a certain kind, preventing access to pages with a certain extension, and so on…

URL: http://www.modsecurity.org
Download: http://www.modsecurity.org/download/direct.html

Most of the information regarding that is available on its website.
In brief the install instructions are:

a.) Download Mod Security gzip .
b.) Unzip it in some dir.
c.) Configure it by issuing command: # ./configure –with-apxs=<APACHE_HOME>/bin/apxs
d.) Compile: # make

e.) Install: # make install

f.) In <APACHE_HOME>/conf/httpd.conf add following lines (the second line is optional):

LoadFile /usr/lib/libxml2.so
#Next line is optional.
#LoadFile /usr/lib/liblua5.1.so

LoadModule security2_module modules/mod_security2.so

g.) Download the Core Rules (these are example config files for mod security)
unzip them such that they land up inside <APACHE_HOME>/conf/modsecurity/

h.) In <APACHE_HOME>/conf/httpd.conf add following lines:
Include conf/modsecurity/*.conf

The most important conf file in that dirs are:
modsecurity_crs_10_config.conf
modsecurity_crs_30_http_policy.conf

You can edit them as you see fit. And rest of the config files you can move to some other sub-dir, if you do not want them loaded.

i.) Now you can restart Apache, and you should be all set.

Now, that you have mod security, you will wonder where is the option for preventing DOS attacks? Infact, Mod Security by itself cannot prevent DOS; but it can do so in conjunction with another tool called ‘httpd guardian’.  See the SecGuardianLog option on this page: http://www.modsecurity.org/documentation/modsecurity-apache/2.1.0/modsecurity2-apache-reference.html .

This particular httpd guardian tool can also be used independently (in which case it analyzes apache logs) or in conjunction with Mod Security in which case it receives information from Mod Security; either way it analyzes input information to determine action to take. The download location of this particular tool is this:

It is available at: http://www.apachesecurity.net/tools/index.html and the download location of httpd-guardian is: http://apache-tools.cvs.sourceforge.net/viewvc/apache-tools/apache-tools/httpd-guardian?view=markup .

Mod Security is probably a great tool, but it does not seem right for the purpose of preventing DOS attacks – mainly because that is really not built into the tool, and it uses a yet another tool (httpd-guardian) to achieve it. So you get the picture, too many pieces involved etc. I have used Mod Security, but not in conjunction with httpd-guardian, so i may not be the best person to pass judgement in this regard.

Mod Evasive

This is the solution that i finally zeroed on and found to be the best solution. It is easy to configure and test.  And preventing DOS attacks is the primary purpose of this tool.

Install Instructions: http://wiki.leenox.in/index.php/Installing_mod_evasive

Download from: http://www.zdziarski.com/projects/mod_evasive/mod_evasive_1.10.1.tar.gz
Compile and Install: #<APACHE_HOME>/bin/apxs -cia mod_evasive20.c

Add to httpd.conf:
<IfModule mod_evasive.c>
DOSHashTableSize 3097
DOSPageCount 2
DOSSiteCount 50
DOSPageInterval 1
DOSSiteInterval 1
DOSBlockingPeriod 300
DOSLogDir “<PathToYourApacheLogDirHere>”
DOSEmailNotify myemal@email.com
</IfModule>

NOTE: Do not forget that even a single web page can have many images and such things, so loading a single page can also cause many requests to be sent to the server(to load images etc). So, you will need to arriveat an appropriate values for the above params yourself.
Explanation of params (this link is useful http://www.directadmin.com/forum/showthread.php?s=&threadid=10957)

DOSHashTableSize
Size of the hash table. The greater this setting, the more memory is required for the look up table, but also the faster the look ups are processed. This option will automatically round up to the nearest prime number.

DOSPageCount
Number of requests for the same page within the ‘DOSPageInterval’ interval that will get an IP address added to the blocking list.

DOSSiteCount
Same as ‘DOSPageCount’, but corresponds to the number of requests for a given site, and uses the ‘DOSSiteInterval’ interval.

DOSPageInterval
Interval for the ‘DOSPageCount’ threshold in second intervals.

DOSSiteInterval
Interval for the ‘DOSSiteCount’ threshold in second intervals.

DOSBlockingPeriod
Blocking period in seconds if any of the thresholds are met. The user will recieve a 403 (Forbidden) when blocked, and the timer will be reset each time the site gets hit when the user is still blocked.

Logs:
You can still see the log messages here whenever a IP Address is blocked:
- <APACHE_HOME>/logs/error_log ( eg: [error] [client <IPAddressHere>] client denied by server configuration: )

- <APACHE_HOME>/logs/<dos_<IP>>( A file with IP Address in its name is created here if an IP Address is blocked)

- /var/log/messages – ( eg: mod_evasive[6480]: Blacklisting address <IPAddressHere>: possible DoS attack)

You can easily test Mod Evasive. Just keep F5 pressed on a web-page of your site (the browser will load the page again and again very fast), and when mod evasive kicks in it will return 403 error.

NOTE: One thing that did not work for me was that, even when a IP Address was correctly identified and blocked, i could still continue to randomly access the web-application.

DOS Deflate

This is a shell script that runs via cron every minute, and checks the processes on that machine. If there are too many http processes initiated by a particular IP Address, it blocks that IP Address using IPTables, and will unblock the IP Address again after some time (based on configuration i.e in ddos.conf file – see the link below).

http://deflate.medialayer.com/ - this is main URL you want to see.

After looking at it, i thought it required one improvement, i.e it should not just check for all processes but should check for httpd processes (assuming u r running Apache ofcourse). For this change the following line in instrall.sh from:

netstat -ntu | awk ‘{print $5}’ | cut -d: -f1 | sort | uniq -c | sort -n

to:

netstat -aptn | grep httpd | awk ‘{print $5}’ | cut -d: -f4 | sort | uniq -c | sort -n

Remember that the concept is quite striaght forward, and you can even write your own java program (if you are unconformatable with shell scripts) to achieve the same.

How do i find that i am under DOS attack?

If you are using Mod Evasive, you can see its logs or you may receive a mail from it if that is configured correctly. But, if you are not using any such thing, read on…

The most obvious thing is that your application will become ‘unexpectedly’ overloaded (and therefore unresponsive). Remember, you could be genuinely overloaded too, because your web-application is so popular! So, one key thing is that it would be ‘unexpected’, another that, most of the requests would seem to come from some specific IPs (which would further confirm that this is an auotmated attack).

On Linux, find out if there are a huge number of http processes:

Find if you have huge number of http processes (>100 is not good):
#ps -aux|grep HTTP|wc -l

#ps -aux|grep HTTP

You have more than 30 connection from a single ip. Under normal cases there is no need for that many number of connection requests from a single IP. Try to identify such ips/networks from the list you get.
#netstat -lpn|grep :80 |awk ‘{print $5}’|sort

If you identify suspicious IPs, you can block them using iptables.

NOTE: In case of DDOS (distributed denial of service) there will be more than one IP that would be suspicious, and it would be much more difficult to stop it too, as the source IP may keep changing.

If you are running an Application Server (say tomcat) – all the threads will be occupied (busy), causing the application to become unresponsive.

Is there a even better and robust solution?

Yes ofcourse, the most robust solution to this problem is to be found in expensive Hardware Load Balancers, or FireWalls.

Posted in Apache, Deployment, Linux, Performance, Security | Tagged: , , , , , , , , | 1 Comment »

How to configure Jetty (in various ways)?

Posted by qnaguru on November 18, 2008

Setting up Apache/Jetty (to talk to one another i.e apache will forward requests to jetty)

For Jetty – Edit the file: <JETTY_HOME>\etc\jetty.xml to include the following xml fragment:

<Call name=”addConnector”>
<Arg>
    <New class=”org.mortbay.jetty.ajp.Ajp13SocketConnector”>
      <Set name=”port”>8009</Set>
     </New>
  </Arg>
</Call>

For Apache – set it up to forward your requests to Jetty (no different than what you would do for it to forward requests to Tomcat).

For details on how to setup Apache/Tomcat to talk to one another, see the relevant post here.

Posted in Uncategorized | Leave a Comment »

How can i monitor and improve performance of my Apache/Tomcat/MySQL application?

Posted by qnaguru on October 30, 2008

Monitor Apache

You can view status of your Apache Web Server by going to a URL of the kind:

This allows us to view status of Apache by going to a URL like:
If the above URL does not work, your apache is probably not configured to return status. For information on how to set it up for this, see Apache Mod Status.

To view the JK Status, go to a URL of the kind:

http://host/jk-status

Monitor-Tomcat

You can view a lot of useful statistics of Tomcat by looking at its Admin Console:

http://<IP:port>/ > click on status link.

Things to look for here are under the approriate headings JVM, jk-8009 (assuming apache is configured to connect via jk on port 8009), http-8080.

JVM

Free Memory – Not sure how this works.

Total Memory – Not sure how this works.

Maximum Memory – this is the maximum amount of memory available to tomcat server, it is the value of the -mx setting in your tomcat startup java command (in catalina.sh). If no mx setting is done, a default value is assumed (which is different for windows and linux)

 

jk-8009 or http-8080

Here the important things to look at are:

Max threads: 200 Current thread count: 28 Current thread busy: 8
Request count: 19 Error count: 0

Max threads – this is maximum number of threads that tomcat can have to process incoming requests (and its internal functions).

Current thread count – this is total number of threads in tomcat’s threadpool at present. Threads will get garbage collected from this pool. And the pool size can grow to ‘Max threads’ size when necessary.

Currrent thread busy – this is total number of threads that are processing variour requests at present.

Request count – total number of http requests received by tomcat since the time it was started.

Improve -Tomcat

You have a performance problem in tomcat when:

Current Thread Count is near about Max Threads. This is a clear indicator that tomcat is receiving more requests faster than it can handle. The default Max Thread setting is 200 which is good enough for most applications, but you can change it here in <TOMCAT_HOME>/conf/server.xml – look for your connector element, here you can change (or add if not present) maxThreads attribute. See http://tomcat.apache.org/tomcat-5.5-doc/config/http.html . But beware, you cannot increase this value indiscrimnately(will affect memory and performance both), the optimum value is based on your hardware, and primarily the number of CPUs you have (more the better for increasing maxThreads). Thumb Rule: Do not change defaults, unless you really have to.

You see Out of Memory Exceptions in your catalina log. See the <TOMCAT_HOME>\logs\catalina.out log file. This is a clear indicator that your application needs more memory than what is available. The min,max memory available can be changed here: <TOMCAT_HOME>\bin\catalina.sh or .bat.  You can add a entry like this somewhere  (A good place would be immediately before this line: # Set juli LogManager if it is present)

(on linux): JAVA_OPTS=”$JAVA_OPTS -ms256M -mx512M”

(on windows): set JAVA_OPTS=-ms256M -mx512M

Monitor MySQL

You can check lots of important mysql params by going to mysql prompt and typing as follows:

mysql> SHOW VARIABLES;

One of things of interest in the response would be: max_connections. This will tell you how many max concurrent connections are allowed.

You can also find out how many concurrent MySQL connections exist at any point in time by using following command:

mysql> show processlist;
The number of rows in the response is equal to number of connections to MySQL at that time.

Improve MySQL

The most important thing you need to find out is if you are running out of db connections. This you can find out by using the above mentioned commands i.e show processlist shows equal number of connections as max_connections. If this happens you need to increase the max_connections.. HOW?

Ofcourse check the usual things in your db connection pool, you pool size cannot be greater than max_connection value ofcourse.

How to see Log of DB Queries being executed?

How to find how much time is being spent in execution of each query?

How to find the amount of data(bytes) being returned by each query?

Posted in Apache, Deployment, Java, MySQL, Performance, Tomcat, Uncategorized | Tagged: , , , | Leave a Comment »

How can i prevent automated registrations using a (captcha) image?

Posted by qnaguru on October 11, 2008

In your user registration pages you may want to provide a generated image, which the user will be required to read and type its contents onto a text box. This will prevent automated bots etc. from filling up the form doing fake registrations.

What you need is:

A image tag in your user form, the src of it should point to a program (.jsp,struts-action etc.) which returns a randomly image (which has text), but before returning this program must store the image text in Session too, so that it when the form is submitted, you can retrieve what the user typed for the image text and compare it against what i stored in the session.

Not clear?

Ok your user form looks like this:

<form action=”/registerUser”>

Email: <input type=”text” name=”email”>

Name: <input type=”text” name=”thename”>

<img src=”/myapp/getMySecretImage.do”>

Type the image text here: <input type=”text” name=”thesecret”>

</form>

So, as you see above, the registration form has a image with an src that is pointing to a struts action. It could as well point to a JSP page or a CGI Script or whatever is capable of generating a image and returning.

Now, let us see what the image generation program looks like. Remember that it will not just return the image but also store the text that will display inside the image in user session.

So, if you are writing your struts action’s (/getMySecretImage) executre method will look like this (you can put the same thing in a servlet or JSP):

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class MyCaptchaStrutsAction extends Action
{

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
    
        String imageFormat = “jpg”;
      response.setContentType((new StringBuilder(“image/”)).append(imageFormat).toString());
         try
         {
             Color backgroundColor = Color.red;
             Color borderColor = Color.black;
             Color textColor = Color.white;
             Color circleColor = new Color(160, 160, 160);
             //Font textFont = new Font(“Arial”, 0, paramInt(request, “fontSize”, 24));
             Font textFont = new Font(“Arial”, 0, 24);
             int charsToPrint = 6;
             int width = 130; //paramInt(request, “width”, 130);
             int height = 40; //paramInt(request, “height”, 40);
             int circlesToDraw = 6;
             float horizMargin = 20F;
             float imageQuality = 0.95F;
             double rotationRange = 0.69999999999999996D;
             BufferedImage bufferedImage = new BufferedImage(width, height, 1);
             Graphics2D g = (Graphics2D)bufferedImage.getGraphics();
             g.setColor(backgroundColor);
             g.fillRect(0, 0, width, height);
             g.setColor(circleColor);
             for(int i = 0; i < circlesToDraw; i++)
             {
                 int circleRadius = (int)((Math.random() * (double)height) / 2D);
                 int circleX = (int)(Math.random() * (double)width – (double)circleRadius);
                 int circleY = (int)(Math.random() * (double)height – (double)circleRadius);
                 g.drawOval(circleX, circleY, circleRadius * 2, circleRadius * 2);
             }

             g.setColor(textColor);
             g.setFont(textFont);
             FontMetrics fontMetrics = g.getFontMetrics();
             int maxAdvance = fontMetrics.getMaxAdvance();
             int fontHeight = fontMetrics.getHeight();
             String elegibleChars = “ABCDEFGHJKLMPQRSTUVWXYabcdefhjkmnpqrstuvwxy23456789″;
             char chars[] = elegibleChars.toCharArray();
             float spaceForLetters = -horizMargin * 2.0F + (float)width;
             float spacePerChar = spaceForLetters / ((float)charsToPrint – 1.0F);
             g.getTransform();
             StringBuffer finalString = new StringBuffer();
             for(int i = 0; i < charsToPrint; i++)
             {
                 double randomValue = Math.random();
                 int randomIndex = (int)Math.round(randomValue * (double)(chars.length – 1));
                 char characterToShow = chars[randomIndex];
                 finalString.append(characterToShow);
                 //maxAdvance * 2;
                 //fontHeight * 2;
                 int charWidth = fontMetrics.charWidth(characterToShow);
                 int charDim = Math.max(maxAdvance, fontHeight);
                 int halfCharDim = charDim / 2;
                 BufferedImage charImage = new BufferedImage(charDim, charDim, 2);
                 Graphics2D charGraphics = charImage.createGraphics();
                 charGraphics.translate(halfCharDim, halfCharDim);
                 double angle = (Math.random() – 0.5D) * rotationRange;
                 charGraphics.transform(AffineTransform.getRotateInstance(angle));
                 charGraphics.translate(-halfCharDim, -halfCharDim);
                 charGraphics.setColor(textColor);
                 charGraphics.setFont(textFont);
                 int charX = (int)(0.5D * (double)charDim – 0.5D * (double)charWidth);
                 charGraphics.drawString((new StringBuilder()).append(characterToShow).toString(), charX, (charDim – fontMetrics.getAscent()) / 2 + fontMetrics.getAscent());
                 float x = (horizMargin + spacePerChar * (float)i) – (float)charDim / 2.0F;
                 int y = (height – charDim) / 2;
                 g.drawImage(charImage, (int)x, y, charDim, charDim, null, null);
                 charGraphics.dispose();
             }

             g.setColor(borderColor);
             g.drawRect(0, 0, width – 1, height – 1);
             Iterator iter = ImageIO.getImageWritersByFormatName(imageFormat);
             if(iter.hasNext())
             {
                 ImageWriter writer = (ImageWriter)iter.next();
                 ImageWriteParam iwp = writer.getDefaultWriteParam();
                 if(imageFormat.equalsIgnoreCase(“jpg”) || imageFormat.equalsIgnoreCase(“jpeg”))
                 {
                     iwp.setCompressionMode(2);
                     iwp.setCompressionQuality(imageQuality);
                 }
                 writer.setOutput(ImageIO.createImageOutputStream(response.getOutputStream()));
                 IIOImage imageIO = new IIOImage(bufferedImage, null, null);
                 writer.write(null, imageIO, iwp);
             } else
             {
                 throw new Exception(“No encoder found.”);
             }
             request.getSession().setAttribute(“CAPTCHA”, finalString.toString());
             g.dispose();
         }
         catch(Throwable e)
         {
          System.out.println(“Unable to build Captcha image: ” + e);
         }    
    
     return null;
    }

}

(NOTE: This image generation code in its JSP version is here. It has only been put in struts action form above.)

You will see that this line above:

request.getSession().setAttribute(“CAPTCHA”, finalString.toString());
stores the image text in session.

So, when the registration form is submitted, you can check against it.

 

 

 

 

Posted in Uncategorized | Tagged: , , | Leave a Comment »

Why am i not able to connect to DB2 from java on linux?

Posted by qnaguru on August 14, 2008

This may happen because you do not have the right environment variables set up on linux machine. The best pointer to this is that, when you are logged in as db2 unix user (note that in db2 database user is also an operating system user) you are able to connect to the database, but when you are logged in as some other user, it fails.

The environment variables that you need to set are:

export DB2DIR=/opt/ibmapps/db2/V9.0
export DB2INSTANCE=mydb2inst
export LD_LIBRARY_PATH=/home/mydb2inst/sqllib/lib32
export LOGNAME=mydb2inst
export PATH=/usr/lib/qt-3.3/bin:/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:

/usr/sbin:/usr/bin:/root/bin:/usr/local/JDK1.5.0_12/bin:/home/mydb2inst/sqllib/bin:

/home/mydb2inst/sqllib/adm:/home/mydb2inst/sqllib/misc

 

You can see that these environment variables do exist when you login as the db2 unix user. This you can see by typing:

$ set

Posted in DB2, Java, Linux | Tagged: , , | Leave a Comment »

How to write java code to invoke a Web-Service?

Posted by qnaguru on July 29, 2008

Step 1 – Get Apache Axis2

Download Apache Axis (http://ws.apache.org/axis2/). Just unzip it in a dir. Lets say your Apache Axis is unzipped here: c:\axis2. Lets call this dir <AXIS_HOME>

Step 2 – Get hold of the wsdl

Get hold of the wsdl file that describes the web-service. Every web-service has an associated wsdl file. Normally, the web-service URL with a ‘?wsdl’ suffix appended to it, will show you the wsdl file. So, if a web-service you want to invoke is available at: http://host:port/superservice/servicemall . You can see the wsdl via a URL: http://host:port/superservice/servicemall?wsdl

Step 3 – Create the Stub

Stub is nothing but the web-service invocation code that you are going to generate now. Go to your command line window, change to dir: <AXIS_HOME>\bin , and run this command:

WSDL2Java -uri servicemall.wsdl

NOTE: servicemall.wsdl should be present in AXIS_HOME\bin dir. Instead of pointing to that file, you could even use a URL format pointing to the wsdl as follows: WSDL2Java -uri http://host:port/superservice/servicemall?wsdl

You will see that stub code has been generated here: <AXIS_HOME>\bin\src. Here you will see that a file ends with *Stub.java name, this is the stub file you need. The contents of this java file look quite complex, but you dont need to worry about all its contents. You will only need to know the Constructor, Parameter, and Response related sub-classes in this file.

Step 4 – Use the Stub

Lets write a MyWebServiceInvoker.java file now, that will invoke the Stub (which in turn invokes the actual web-service). Assuming the name of the name of the stub file generated was: ServiceMallStub, and that the service we want to invoke takes one param (item id), and returns item details when its method getItemDetails is invoked.

You will notice that parameter and the response are also inner classes in the generated stub java file, and they have appropriate methods for your use.

public class MyWebServiceInvoker
{
 public static void main(String[] args)
 {
  try
  {
   com.servicemall.ServiceMallStub serviceMallStub = new com.servicemall.ServiceMallStub();  
   com.servicemall.ServiceMallStub.MyItem theParam = new com.servicemall.ServiceMallStub.MyItem();
   theParam.setItemid("11");
   theParam.MyItemResponse theResp = serviceMallStub.getItemDetails(theParam);
   boolean result = theResp.getItemResult();
   System.out.println("Result is:" + result);   
  }
  catch (Throwable t)
  {
   System.out.println(t);
  }
 }

Step 5 – Run

Just compile and run the MyWebServiceInvoker. To compile, you must put the <AXIS_HOME>\lib\ jar files in the classpath. To run in addition you must have the compiled stub classes in your classpath too. (You could also use the build.xml that is generated along with source code for compilation)

Step 6 – Does it work?

If you dont see any errors, and get a response back from the service, all’s well!

A common cause of exception is HTTP Protocol mismatch (although the exception message doesnt give suitable hint about it!). You may have to ask your stub to use HTTP 1.0 protocol, instead of the default HTTP 1.1 protocol it uses.  This you can do in the constructor class of the stub.

Search for this line: //Set the soap version
_serviceClient.getOptions().setSoapVersionURI(org.apache.axiom.soap.SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI);

Now, just below this line, add this line:

_serviceClient.getOptions().setProperty(org.apache.axis2.transport.http.HTTPConstants.HTTP_PROTOCOL_VERSION, org.apache.axis2.transport.http.HTTPConstants.HEADER_PROTOCOL_10);

Compile, and try again.

Tested with: Apache Axis 2.1.3,  JDK 1.5

Posted in Web-Service | Tagged: , , | 1 Comment »