Friday, October 21, 2011

Work-Offline Firefox plugin

As I was going on vacation where there is a limited internet connectivity, I thought it would be great if I could get read some of the webpages offline. But I did not want to save the pages on local manually. I found a good Firefox plugin for it - work offline.

https://addons.mozilla.org/en-US/firefox/addon/work-offline/

Its really useful - when in offline mode, it serves the page if its available in its cache - similar to what is offered by IE's Work Offline feature.
So good for the Firefox lovers.

Friday, October 14, 2011

Compressing and Decompressing String in Java using GZIP streams

Following code can be used to compress or decompress any data in Java using the GZIP streams - java's built in zip streams.
    public static String compress(String str) throws IOException {
        if (str == null || str.length() == 0) {
            return str;
        }
        System.out.println("String length : " + str.length());
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        gzip.write(str.getBytes());
        gzip.close();
        String outStr = out.toString("ISO-8859-1");
        System.out.println("Output String lenght : " + outStr.length());
        return outStr;
     }
    
    public static String decompress(String str) throws IOException {
        if (str == null || str.length() == 0) {
            return str;
        }
        System.out.println("Input String length : " + str.length());
        GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(str.getBytes("ISO-8859-1")));
        BufferedReader bf = new BufferedReader(new InputStreamReader(gis, "ISO-8859-1"));
        String outStr = "";
        String line;
        while ((line=bf.readLine())!=null) {
          outStr += line;
        }
        System.out.println("Output String lenght : " + outStr.length());
        return outStr;
     }
  
     public static void main(String[] args) throws IOException {
        String filePath = ".\response.txt";
        
        String string = getFileData(filePath);
        System.out.println("after compress:");
        String compressed = compress(string);
        System.out.println(compressed);
        System.out.println("after decompress:");
        String decomp = decompress(compressed);
        System.out.println(decomp);
 
      }
     
     public static String getFileData(String filepath) throws FileNotFoundException,
                                                           IOException {
       BufferedReader bf = new BufferedReader(new FileReader(filepath));
       String data="";
       String line;
       while ((line=bf.readLine())!=null) {
         data += line;
       }
       return data;
     }