My Quotes


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






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 file.java.changed





import org.apache.commons.io.FileUtils;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintStream;

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;
        try{
            encoding="UTF-8";
            rootDir=new File("some directory");
            commentStr = "(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?://.*)";
            fileIterator = FileUtils.iterateFiles(rootDir, extensions, recursive);
            for(;fileIterator.hasNext();){
                inputFile = (File) fileIterator.next();
                fileContent=FileUtils.readFileToString(inputFile, encoding);
                // Open an output stream
                if(changeExt == true){
                    fileExt = inputFile.getName().substring(0,inputFile.getName().indexOf(".java"))+".changed";
                }else{
                    fileExt = "";
                }
                fout = new FileOutputStream(new File(inputFile.getAbsolutePath()+fileExt));
                pout = new PrintStream(fout);
                pout.println(fileContent.replaceAll(commentStr, ""));
                fout.flush();
                fout.close();
                pout.flush();
                pout.close();
            }
        }catch (Exception e) {
             e.printStackTrace();
        }finally{
            rootDir = null;
            fileContent=null;
            dirFiles = null;
            encoding=null;
            fileIterator = null;
            commentStr=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 www.google.com/webmasters/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 on JAVA STRINGS

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 {
    CREATE_USER("create"),UPDATE_USER("update");
   
    private final String token;
    private static Map<String,UserActionMapping> tokenMap;
   
   
    private UserActionMapping(String token){
        this.token = token;
        map(token,this);
    }
     private static void map(String token, UserActionMapping op){
         if (tokenMap==null) tokenMap = new HashMap<String,UserActionMapping>();
         tokenMap.put(token,op);
     }
     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);
             System.out.println(operation);
             switch (operation) {
                 case CREATE_USER:{
                     System.out.println("create user");
                     returnValue= 1;
                     break;
                 }
                 case UPDATE_USER:{
                     System.out.println("update user");
                     returnValue=2;
                     break;
                 }               
             }
             System.out.println ("returnValue="+returnValue);
         }
         return returnValue;
     }
   
   
     public static void main(String[] args) {
         String[] actionMappingOps = new String[]{"create","update"};
         getActionMapping(actionMappingOps);
     }
}

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) {

super(response);

reset();

}

public String getContent() throws IOException {
flushBuffer();

return new String(output.toByteArray());
}

public void setContent(byte[] content) throws IOException {
reset();
stream.write(content);
}

public void setContent(String s) throws IOException {

setContent(s.getBytes());
}

@Override

public void flushBuffer() throws IOException {
writer.flush();

stream.flush();

output.flush();

}

@Override

public ServletOutputStream getOutputStream() throws IOException {

return stream;

}
@Override
public ServletResponse getResponse() {
return super.getResponse();

}

@Override

public PrintWriter getWriter() throws IOException {

return writer;

}
@Override
public boolean isCommitted() {

return output.size() > 0;

}

@Override

public void reset() {

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

this.writer = new PrintWriter(stream);

}

@Override

public void resetBuffer() {

reset();

}

public void writeContent() throws IOException {

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

response.setContentLength(content.length());

os.write(cleanXSS(content).getBytes());

os.close();

}

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);
mutableResponse.writeContent();
}



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
<library-ref>

<library-name>jcaptcha-all-1.0-RC3</library-name>
<exact-match>false</exact-match>
</library-ref> 
Also create an entry in the config.xml file
<library>
<name>jcaptcha-all-1.0-RC3</name>
<target>AdminServer</target>
<module-type xsi:nil="true"></module-type>
<source-path>servers\AdminServer\upload\APP-INF\lib\jcaptcha-all-1.0-RC3.jar</source-path>
<security-dd-model>DDOnly</security-dd-model>
<staging-mode>nostage</staging-mode>
</library> 
 
2) Create an entry in the web.xml file
<servlet>
<servlet-name>SimpleCaptchaServlet</servlet-name>
<display-name>SimpleCaptchaServlet</display-name>
<servlet-class>com.servlet.SimpleCaptchaServlet</servlet-class>
<init-param>
<description>passing height</description>
<param-name>height</param-name>
<param-value>30</param-value>
</init-param>
<init-param>
<description>passing height</description>
<param-name>width</param-name>
<param-value>120</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>SimpleCaptchaServlet</servlet-name>
<url-pattern>/Captcha.jpg</url-pattern>
</servlet-mapping>

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 {
super.init(servletConfig);
// 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) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"Problem generating captcha image.");
return;
} 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.");
return;
}
// Validate whether input from user is correct.
boolean passedCaptchaTest = false;
try {
passedCaptchaTest = validateCaptchaWithSession(parmValue,sessionValue);
} catch (CaptchaServiceException e) {e.printStackTrace();}
// Set flag into session.
request.getSession().removeAttribute(CAPTCHA_KEY);
// Forward request to results page.
if (passedCaptchaTest) {
RequestDispatcher rd = getServletContext().getRequestDispatcher("/Login.do");
rd.forward(request, response);
} else {
RequestDispatcher rd = getServletContext().getRequestDispatcher("/logout.do");
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>
</tr>
<!-- 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.
http://www.owasp.org/index.php/JCaptcha_servlet_example.
But the image will be very blurred.