My Quotes

When U were born , you cried and the world rejoiced
Live U'r life in such a way that when you go

Tuesday, April 13, 2010

Find files recursively and remove unwanted comments

I always wanted to scna whole folder and remove unwanted comments from my java codings. Here is a method which you can ready made use it to acheive this. I hope that this helps some one. Of course your javac task will remove comments from the class file but having a source file with clean code always makes an impression.

I have a string array of extensions so that this can be used for other types of files also.

If you make the variable boolean changeExt=true; then the file will be overwritten, else a new file will be created with an extension of


import java.util.regex.Matcher;
import java.util.regex.Pattern;

    private void findFilesandReplaceComment() {
        File rootDir = null;
        String[] extensions = { "java" };
        boolean recursive = true;
        String fileContent=null;
        Collection dirFiles = null;
        String encoding=null;
        Iterator fileIterator = null;
        String commentStr=null;
        FileOutputStream fout = null;
        File inputFile = null;
        PrintStream pout = null;
        boolean changeExt=true;
        String fileExt = null;
            rootDir=new File("some directory");
            commentStr = "(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?://.*)";
            fileIterator = FileUtils.iterateFiles(rootDir, extensions, recursive);
                inputFile = (File);
                fileContent=FileUtils.readFileToString(inputFile, encoding);
                // Open an output stream
                if(changeExt == true){
                    fileExt = inputFile.getName().substring(0,inputFile.getName().indexOf(".java"))+".changed";
                    fileExt = "";
                fout = new FileOutputStream(new File(inputFile.getAbsolutePath()+fileExt));
                pout = new PrintStream(fout);
                pout.println(fileContent.replaceAll(commentStr, ""));
        }catch (Exception e) {
            rootDir = null;
            dirFiles = null;
            fileIterator = null;
            fout = null;
            inputFile = null;
            pout = null;
            fileExt = null;

Sunday, April 11, 2010

Indian T20 from IPL-3

My 15 member team which can compete with any side on any given day for T-20

Murali Vijay
Shikhar Dhawan
Ambati Rayudu
Abhishek Nayar
Saurabh Tiwary     
Naman Ojha (keeper)
Manish Pandey
Robin Uthappa (Alternate keeper)
Abhishek Jhunjhunwala     
Irfan Pathan  **   
Shadab Jakati     
Pragyan Ojha
Rajat Bhatia     
Pradeep Sangwan
Umesh Yadav

Friday, April 9, 2010

How do I make my blog SEARCHABLE via google

1) Go to Google web master tools
2) Login with your gmail account
3) Once logged in "add a new site".
4) It will provide you with a META TAG content. Either you can VERIFY the site at this point or you can VERIFY LATER.
5) Add it in your blog site HTML page right at the top

    Do edit your blog here are the steps
    Click on the Layout --> EDIT HTML
6) Add this META tag from web master.
7) Allow 3-4 days for Google to pick your blogs.


Switch statements can only be used on ints or enums. For strings we are heavily relying on if-else-if blocks.

That said, if you really want a switch, you can provide a string switching capability with an enum.

import java.util.HashMap;
import java.util.Map;
public enum UserActionMapping {
    private final String token;
    private static Map<String,UserActionMapping> tokenMap;
    private UserActionMapping(String token){
        this.token = token;
     private static void map(String token, UserActionMapping op){
         if (tokenMap==null) tokenMap = new HashMap<String,UserActionMapping>();
     public static UserActionMapping forToken(String token){
         return tokenMap.get(token);
     public static long getActionMapping(String[] actionMappingOps){
         long returnValue=0L;
         for (String opString : actionMappingOps){
             UserActionMapping operation = UserActionMapping.forToken(opString);
             switch (operation) {
                 case CREATE_USER:{
                     System.out.println("create user");
                     returnValue= 1;
                 case UPDATE_USER:{
                     System.out.println("update user");
             System.out.println ("returnValue="+returnValue);
         return returnValue;
     public static void main(String[] args) {
         String[] actionMappingOps = new String[]{"create","update"};

Wednesday, April 7, 2010

Output decoding using OWASP API

It was always on the back of my mind to centralize the output encoding using OWASP API rather than changing every single page in my application,.
Following two are the possible two options to implement for output encoding. However, our recommendation is to use Option 2.
Option 1: Implementing the solution in common place:
The encode implementation can be done in a response filter level. System has to pass all the responses through this filter, before rendering in front end.
This response filter should encode only the dynamic data which are rendered in the front end and not all the “JSP” file content.
Option 2: Implementing the encoding in all JSP files.
System has to encode all dynamic data which are in the “JSP” files using the below methods based on type of data.
value = escapeHtmlFull(value);
value = ESAPI.encoder().encodeForHTML(value);
value = ESAPI.encoder().encodeForHTMLAttribute(value);
value = ESAPI.encoder().encodeForJavaScript(value);
value = ESAPI.encoder().encodeForCSS(value);

In order to implement using the Session Filter here is my class which does the output decoding and centralizes the output decoding with OWASP API.

public final class MutableHttpResponse extends HttpServletResponseWrapper {

private ByteArrayOutputStream output = null;
private FilterServletOutputStream stream = null;
private PrintWriter writer = null;

public MutableHttpResponse(HttpServletResponse response) {




public String getContent() throws IOException {

return new String(output.toByteArray());

public void setContent(byte[] content) throws IOException {

public void setContent(String s) throws IOException {



public void flushBuffer() throws IOException {





public ServletOutputStream getOutputStream() throws IOException {

return stream;

public ServletResponse getResponse() {
return super.getResponse();



public PrintWriter getWriter() throws IOException {

return writer;

public boolean isCommitted() {

return output.size() > 0;



public void reset() {

this.output = new ByteArrayOutputStream(); = new FilterServletOutputStream(output);

this.writer = new PrintWriter(stream);



public void resetBuffer() {



public void writeContent() throws IOException {

String content = getContent();
ServletResponse response = getResponse();
OutputStream os = response.getOutputStream();





private String cleanXSS(String value) {

value = ESAPI.encoder().encodeForHTML(value);

value = ESAPI.encoder().encodeForHTMLAttribute(value);

value = ESAPI.encoder().encodeForJavaScript(value);

value = ESAPI.encoder().encodeForCSS(value);

return value;



The Session Filter code to invoke this MutableResponse is as follows
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws ServletException, IOException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
// do your other stuff here
chain.doFilter(request, response);
MutableHttpResponse mutableResponse = new MutableHttpResponse(httpResponse);

Creating a JCAPTCHA with struts application

JCAPTCHA stands for Java Completely Automated Public Test to tell Computers and Humans Apart.
The open source java framework for captcha definition and integration

1) Add the jcaptcha jar file into the WEB-INF/lib directory of your .war file (or) add the same into the weblogic shared libraries and create an entry in the weblogic-application.xml

Also create an entry in the config.xml file
<module-type xsi:nil="true"></module-type>
2) Create an entry in the web.xml file
<description>passing height</description>
<description>passing height</description>

3) Here is the source code for the servlet. I have not implemented exception handling its up to you to integrate exception handling in this servlet
public class SimpleCaptchaServlet extends HttpServlet {
String sImgType = null;private int height = 0;private int width = 0;
public static final String CAPTCHA_KEY = "captcha_key_name";
public void init(ServletConfig servletConfig) throws ServletException {
// For this servlet, supported image types are PNG and JPG.
sImgType = servletConfig.getInitParameter("ImageType");
sImgType = sImgType == null ? "png" : sImgType.trim().toLowerCase();
if (!sImgType.equalsIgnoreCase("png") && !sImgType.equalsIgnoreCase("jpg")&& !sImgType.equalsIgnoreCase("jpeg")) {
sImgType = "png";
height = Integer.parseInt(getServletConfig().getInitParameter("height"));
width = Integer.parseInt(getServletConfig().getInitParameter("width"));
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
ByteArrayOutputStream imgOutputStream = null;
byte[] captchaBytes = null;BufferedImage image = null;Graphics2D graphics2D = null;
Hashtable<TextAttribute, Object> map = null;Random r = null;String token = null;String ch = null;
Color c = null;GradientPaint gp = null;Font font = null;
if (request.getQueryString() != null&& request.getQueryString().indexOf("CSRF=") == -1) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"GET request should have no query string.");return;
try {
imgOutputStream = new ByteArrayOutputStream();
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
graphics2D = image.createGraphics(); map = new Hashtable<TextAttribute, Object>();
r = new Random(); token = Long.toString(Math.abs(r.nextLong()), 36);
ch = token.substring(0, 6);
c = new Color(0.6662f, 0.4569f, 0.3232f);
gp = new GradientPaint(30, 30, c, 15, 25, Color.white, true);
graphics2D.setPaint(gp);font = new Font("Verdana", Font.CENTER_BASELINE, 26);
graphics2D.setFont(font);graphics2D.drawString(ch, 2, 20);graphics2D.dispose();
request.getSession().setAttribute(CAPTCHA_KEY, ch);
} catch (CaptchaServiceException cse) {
"Problem generating captcha image.");
} finally {
// Set appropriate http headers.
response.setHeader("Cache-Control", "no-store");response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/"+ (sImgType.equalsIgnoreCase("png") ? "png" : "jpeg"));
OutputStream outputStream = response.getOutputStream();
ImageIO.write(image, sImgType, outputStream);
outputStream.close();imgOutputStream = null;aptchaBytes = null;
image = null;graphics2D = null;map = null;r = null;token = null;ch = null;c = null;gp = null;font = null;
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {// Get the request params.
String parmValue = request.getParameter("inCaptchaChars");
String sessionValue = request.getSession().getAttribute(CAPTCHA_KEY).toString();
// Check validity and consistency of the data.
if (captchaId == null || incomingCaptchaId == null !captchaId.equals(incomingCaptchaId)) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"Browser must support session cookies.");
// Validate whether input from user is correct.
boolean passedCaptchaTest = false;
try {
passedCaptchaTest = validateCaptchaWithSession(parmValue,sessionValue);
} catch (CaptchaServiceException e) {e.printStackTrace();}
// Set flag into session.
// Forward request to results page.
if (passedCaptchaTest) {
RequestDispatcher rd = getServletContext().getRequestDispatcher("/");
rd.forward(request, response);
} else {
RequestDispatcher rd = getServletContext().getRequestDispatcher("/");
rd.forward(request, response);
private boolean validateCaptcha(String captchaId, String inputChars) {
boolean bValidated = false;
try {
bValidated = MyCaptchaService.getInstance().validateResponseForID(captchaId, inputChars);
} catch (CaptchaServiceException cse) {}
return bValidated;
private boolean validateCaptchaWithSession(String paramValue, String sessionValue) {
boolean bValidated = false;
if (!paramValue.equalsIgnoreCase(sessionValue)) {
bValidated = false;
} else {
bValidated = true;
return bValidated;

4) In the JSP page
<input type="hidden" name="hidCaptchaID" value="<%= session.getId() %>"/>
<!-- place for simple captcha start-->
<tr><td class="normaltext" width="70%" valign="top">Enter the letters:
<img src="/SimpleCaptchaServlet" align="middle" alt="Enter the characters appearing in this image" border="1"/><a href="/">Click here</a> to re-generate </td>
<td width="30%" valign="top"><input type="text" name="inCaptchaChars"/></td>
<!-- place for simple captcha end -->

5) This is a servlet which generates a 2D image on to the screen.

There is the other way of implementing this captcha using the OWASP simple captcha servlet which you can get it from the OWASP site.
But the image will be very blurred.