Thursday, September 30, 2010

Pitfalls in replaceAll function of String class

Lets have a look at the replaceAll function.

String s = "Yogesh C:\\test3.xml vaibhav";
s = s.replaceAll("C:\\test3.xml", "test");
System.out.println(s);


You might be expecting that it would replace the string c:\\test3.xml, but it doesn't happens.
Reason :
The regex parser has backslash (\) and dollar ($) as keywords, so it treats it differently.
If your string contains these characters, you can use Matcher.quoteReplacement to skip these characters.

Solution:

String s = "Yogesh C:\\test3.xml vaibhav";
s = s.replaceAll(Matcher.quoteReplacement("C:\\test3.xml"), "test");
System.out.println(s);

Sunday, September 26, 2010

JAVASSIST (Java programming Assistant)

JAVASSIST (Java programming Assistant) is a utility that allows one to inspect, edit and create Java binary classes. It enables Java programs to define a new class at runtime and to modify a given class file when the JVM loads it. Its best feature is its ease of use since it allows developers to fully exploit byte code manipulation with little or no knowledge of byte code, giving them a degree of fine-grained control.

Javassist provides two levels of API: Source level and Byte code level. If the users use source level API, they can edit a class file without knowledge of the specifications of the Java byte code. The whole API is designed with only the vocabulary of the Java language. You can even specify inserted byte code in the form of source text; Javassist compiles it on the fly. On the other hand, the byte code level API allows the users to directly edit a class file as other editors.

Javassist uses the javassist.ClassPool class to track and control the classes being manipulated. Classes loaded in a class pool are represented by javassist.CtClass instances where as fields, methods and constructors are represented by javassist.CtField, javassist.CtMethod and javassist.CtConstructor instances, respectively.

An Example of Javassist

The below example depicts the usage of few of the Javassist basic APIs. All that is required is to just download ‘javassist.jar’ and add the same to the class path.

Wednesday, September 22, 2010

Reflections

Some imports that you may require

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


A generic method which can print any bean class, provided all the getter methods are there.


public static void printObject(Object app) throws
IllegalArgumentException, IllegalAccessException, 
InvocationTargetException
{
    Method[] m = app.getClass().getMethods();
    for(Method method : m)
    {
        if(method.getName().startsWith("get"))
        {
            // if getClass then ignore this method.
            if(method.getName().equals("getClass"))
                continue;
            if(method.getReturnType().isArray())
            {
                System.out.print(method.getName() + "=[ ");
                Object[] values = (Object[])method.invoke(app, null);

                for(Object v : values)
                {
                    System.out.print(v + ", " );
                }
                System.out.print(" ]\n");
            }          
            else
                System.out.println(method.getName() + " = " + method.invoke(app, null));
        }
    }  
}



If you would like to learn more about Reflections, you can visit this link: http://java.sun.com/developer/technicalArticles/ALT/Reflection/

Wednesday, September 8, 2010

Premature end of file when running junits

Problem:

Premature end of file error when running Junits

[junitreport] [Fatal Error] :-1:-1: Premature end of file.
[junitreport] The file /tmp/repository/Yogesh/task2652_story1984/modulesmgr/junit_report/out/xml/TEST-com.coresecurity.ctrlsvc.modules.ModulesImportAndBasicCRUDTest.xml is not a valid XML document. It is possibly corrupted.



Observations:
1) TESTS-testsuites.xml was coming out to be empty.
2) The resulting xml file was getting too large in size.


Solution:
Hibernate logging was enabled which was leading to large size of XML.
We disabled logging in config.xml as given below
Earlier it was true, we made it false




<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<qualifier value ="DataSource" />
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="com.coresecurity.datamanager"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.transaction">true</prop>
<prop key="hibernate.c3p0.min_size">5</prop>
<prop key="hibernate.c3p0.max_size">20</prop>
<prop key="hibernate.c3p0.timeout">300</prop>
<prop key="hibernate.c3p0.max_statements">50</prop>
<prop key="hibernate.c3p0.idle_test_period">3000</prop>
</props>
</property>
</bean>

Thursday, August 12, 2010

Opening IE in existing window problem

Visit this URL

http://support.microsoft.com/?kbid=241911

This tells how to fix, if IE opens in existing window.

Friday, June 25, 2010

Sendkeys

A VB Script to run outlook and send some specified keys to it.

To send Ctrl+n, use "^{n}" as given below, for Alt use %

Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "Outlook"
WScript.Sleep 2500 ' Give Notepad some time to load
WshShell.SendKeys "^{n}"
WScript.Sleep 1000
WshShell.SendKeys "Yogesh_Gandhi@infosys.com"
WshShell.SendKeys "{TAB}"
WshShell.SendKeys "{TAB}"
WshShell.SendKeys "{TAB}"
WshShell.SendKeys "{TAB}"
WshShell.SendKeys "{TAB}"
WshShell.SendKeys " Hi Yogesh, I accept that I am a FOOL ...and you made a fool out of me today ... I don’t think God planted brains in my head!!!!...otherwise I would have checked out the code first! you are great. hats off for you. With Regards"
WshShell.SendKeys "%{s}"

Thursday, June 24, 2010

Quick batch file to check OS version…

How to check the Operation System version
if OS is 32 bit or 64 bit

Quick batch file to check OS version…




@echo off

Set RegQry=HKLM\Hardware\Description\System\CentralProcessor\0

REG.exe Query %RegQry% > checkOS.txt

Find /i "x86" < CheckOS.txt > StringCheck.txt

If %ERRORLEVEL% == 0 (

Echo "This is 32 Bit Operating system"

) ELSE (

Echo "This is 64 Bit Operating System"

)

pause

Saturday, May 22, 2010

use OnClick with caution

JSP Code :

<a href="abc.jsp" onclick='<% session.invalidate(); %>'>LOGOUT</a>


The above statement gets converted to Servlet CODE :
out.write("<a href=\"abc.jsp\" onclick='");
session.invalidate();
out.write("'>LOGOUT</a>");


Conclusion:

What ever scriplet you write in onclick, will get executed every time the JSP is called. Not only on onclick as can be wrongly assumed.

Thursday, May 20, 2010

BUG in struts2

Actually I used

Now, I have specified type as button, so I expected that it will not go to action on click on the button.

But what happens is

when I click on button, it asks if I want to close the window,
Now, even I click NO, it still goes to action specified in form.

Solution : This is a BUG in struts2.

the HTML tag that is generated is something like:

<button type="submit" id="test_0" value="Submit" class="button positive save">Submit</button>

Please note that we have given type=button in s:submit tag, and the HTML generated still contains type=submit.

Can get some information from http://www.ericmmartin.com/struts-2-bug-submit-button-tag-rendering/

Sunday, May 16, 2010

Internationalization tips for JSP

In order to display the complex script characters like Japanese, Chinese, etc in the browser window, the following changes need to be made at the beginning of each JSP file:

<%@ page language="java" 
contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>


Wherever input controls are present, the following additional steps need to be taken:
Add the following code before reading any parameters in the previous JSP file:

request.setCharacterEncoding("UTF-8"); // Set the request encoding



While sending output to a browser:

response.setContentType ("charset=UTF-8");

Saturday, April 24, 2010

OpenDatabase function gives error

Problem:
OpenDatabase function which is a standard function in VB
gives the following error







Solution:
Modify the code to

Set db = DBEngine.OpenDatabase(cd1.FileName)

VB with Access 2000

Problem :
How to make VB 6.0 work with Access 2000



Solution :
Select Microsoft DAO 3.6 Object Library in Project References