Posts

Showing posts from March, 2011

Clearing WAR , EAR JAR files for .svn folders and library jars

Big archieve sizes can be annoying. There can be some useless files within a war or jar file. 1. If you uploaded your library files to application server than you do not need to pack them everytime you create application archieve file. 2. There can be subversion folders which do not have a function in runtime. I wrote a basic windows batch file. it uses 7-zip . clearJavaArchieves.bat cd %TEMP% rem "C:\Program Files\7-Zip\7z.exe" d %1 *.jar -r -tzip "C:\Program Files\7-Zip\7z.exe" d %1 .svn -r -tzip rem "C:\Program Files\7-Zip\7z.exe" d %1 WEB-INF\lib -tzip pause paste this code to file. first line is the for the temp files. if you want to clear all jar files within your archieve , and you know what you are doing , delete rem part of line 2 , otherwise you can delete delete line 2. 3rd line deletes all .svn folders within your archieve file. if you donot want to do this , delete line 3. if you want to delete web-inf/lib , delete rem

Determine jar file of a class

We sometimes need to determine from which jar file some particular class comes from. Here I wrote a small method to find out the name of the jar file we are looking for : public static String getJarURL ( Class mclass ) { URL clsUrl = mclass. getResource ( mclass. getSimpleName ( ) + ".class" ) ; if ( clsUrl ! = null ) { try { URLConnection conn = clsUrl. openConnection ( ) ; if ( conn instanceof JarURLConnection ) { JarURLConnection connection = ( JarURLConnection ) conn ; return connection. getJarFileURL ( ) . toString ( ) ; } } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } return null ; } public static void main ( String [ ] x ) { System . out . println ( getJarURL ( java. net . HttpURLConnection . class ) ) ; }   which prints following output : file:/C:/Program%20Files%20(x86)/Java/jre1.5.0_22/lib/rt.jar

Simple Java Exception Handling Tips

Exceptions are errors that occur in runtime , that is , when the application is running. A careful developer should estimate and care about possible runtime errors. Let us give an example : String s = args[0]; int i = Integer.parseInt(s); this piece of code can cause some exceptions. For example args is an array of string. We want to read the first element of this array. What happens if args is null ? What happens if args is empty ? so we need to ensure that the array is not null and not empty.         String s = null ; // initialize s         // check the array is not null or empty         if ( args ! = null && args. length > 0 )             s = args [ 0 ] ;         int i = 0 ;         if ( s ! = null ) // if s is not null we can parse             i = Integer . parseInt ( s ) ;         else { // s is null , so show an error message and exit             System . err . println (             "Invalid argument , should be a valid intege