Piotr Gabryanczyk’s Blog

Java, Refactoring, AOP, Spring, DDD, TDD, etc.

  • Blogroll

    • I have joined Anti-IF Campaign

Archive for the ‘Uncategorized’ Category

Howto compress or decompress byte array in Java?

Posted by Piotr Gabryanczyk on June 8, 2009

Check this class out:

Compressor.java

import java.io.*;
import java.util.zip.*;

import org.apache.commons.io.IOUtils;

public class Compressor{
    public static byte[] compress(byte[] content){
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try{
            GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
            gzipOutputStream.write(content);
            gzipOutputStream.close();
        } catch(IOException e){
            throw new RuntimeException(e);
        }
        System.out.printf("Compression ratio %f\n", (1.0f * content.length/byteArrayOutputStream.size()));
        return byteArrayOutputStream.toByteArray();
    }

    public static byte[] decompress(byte[] contentBytes){
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try{
            IOUtils.copy(new GZIPInputStream(new ByteArrayInputStream(contentBytes)), out);
        } catch(IOException e){
            throw new RuntimeException(e);
        }
        return out.toByteArray();
    }

    public static boolean notWorthCompressing(String contentType){
        return contentType.contains("jpeg")
                || contentType.contains("pdf")
                || contentType.contains("zip")
                || contentType.contains("mpeg")
                || contentType.contains("avi");
    }
}

Dependencies: Apache commons-io.jar

Posted in Uncategorized | Leave a Comment »

Hamcrest Regex Matcher

Posted by Piotr Gabryanczyk on March 27, 2009

Problem

I could not find a regex matcher in hamcrest, to do ie.
assertThat(selenium.getTitle(), matches("Template T\d{3}"));

It could be that I was not looking well enough or Nat Pryce decided not to include it on purpose. Of’course I saw PatternMatcher, but it lets you build regexes rather then match against them.

Solution

So here you have, enjoy!


public class RegexMatcher extends BaseMatcher{
    private final String regex;

    public RegexMatcher(String regex){
        this.regex = regex;
    }

    public boolean matches(Object o){
        return ((String)o).matches(regex);

    }

    public void describeTo(Description description){
        description.appendText("matches regex=");
    }

    public static RegexMatcher matches(String regex){
        return new RegexMatcher(regex);
    }
}

Posted in Uncategorized | Leave a Comment »

HowTo customize Save As/Open dialog shortcuts in XP using windows registry

Posted by Piotr Gabryanczyk on February 18, 2009

Problem:

I want to add custom shortcuts in Open/Save As dialog box in XP

Manual Solution:

Check this article by Ryan Gordon out if you want to do it manually.

Automatic Solution:

Create custom-save_as.reg file with content similar to the following:

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Comdlg32]

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Comdlg32\PlacesBar]
"Place1"="e:\\piotrga"
"Place2"="e:\\piotrga\\tmp"
"Place3"="e:\\piotrga\\Download"

Then right-click custom-save_as.reg and select "Merge" option.

Now open Save As/Open dialog and enjoy!

Posted in Uncategorized | 1 Comment »

PortSpy in Ruby

Posted by Piotr Gabryanczyk on October 22, 2008

To trace all the traffic between your browser and google run:
ruby portspy.rb 80 www.google.com 80
And then point your browser to
http://localhost:80

Enjoy!

require "socket"
STDOUT.sync = true
STDERR.sync = true

SERVER_PORT, REDIRECT_HOST, REDIRECT_PORT, *rest = ARGV

puts "Forwarding from port #{SERVER_PORT} to #{REDIRECT_HOST}:#{REDIRECT_PORT}"

server = TCPServer.new(SERVER_PORT)

counter = 0
while( session = server.accept)
    counter += 1
    redirect = TCPSocket.new REDIRECT_HOST, REDIRECT_PORT
    puts "#{counter}>OPENING CONNECTION"
    Thread.new(session, redirect, counter) do |s, r, c|
        begin
            req = File.new("data/request-#{c}.txt", "w")
            req.sync = true
            until( s.eof? )
                line = s.readpartial(128)
                puts "\n#{c}>REQUEST:'#{Regexp.escape(line)}'"
                r.write line
                req.write line
                r.flush
            end
            s.close_read
            req.close
            r.close_write
            puts "\n#{c}>CLOSING REQUEST SOCKET:"
        rescue => e
            puts "\n#{c}Error #{e}\n#{e.backtrace}"
            exit -1
        end
    end

    Thread.new(session, redirect, counter) do |s, r, c|
        begin
            resp = File.new("data/response-#{c}.txt", "w")
            resp.sync = true
            until( r.eof? )
                line = r.readpartial(128)
                puts "\n#{c}>RESPONSE:'#{Regexp.escape(line)}'"
                resp.write line
                s.write line
                s.flush
            end
            puts "\n#{c}CLOSING RESPONSE"
            r.close_read
            resp.close
            s.close_write
        rescue =>  e
            puts "\n#{c}Error #{e}\n#{e.backtrace.join "\n\t"}"
            exit -1
        end

    end
end

Posted in Uncategorized | Tagged: , | Leave a Comment »

Creating presentations online

Posted by Piotr Gabryanczyk on June 25, 2008

I just came across a great tool:

http://280slides.com

Enjoy!

Posted in Uncategorized | Leave a Comment »

Charts embedded in the web page?

Posted by Piotr Gabryanczyk on June 4, 2008

Colleague of mine showed me the following flash lib which does it really nicely. No programming needed. You just provide simple xml, and it works!
http://www.maani.us/xml_charts

Posted in Uncategorized | Tagged: , | Leave a Comment »

When to start using TDD?

Posted by Piotr Gabryanczyk on April 22, 2008

The sooner the better!
Guys from Sabre have started teaching TDD to students at The Jagiellonian University.

Great idea!
If anyone needs a volunteer to teach TDD in London – I’m in!

Here is the link to Bartosz’s post about their TDD project in Krakow.

Posted in Uncategorized | Tagged: , | Leave a Comment »

Jak zwinny jest twoj zespol? – wyniki

Posted by Piotr Gabryanczyk on March 19, 2008

Oto oczekiwane wyniki ankiety Jak bardzo Agile jest twoj zespol?:
pobierz wyniki ankiety w postaci pdf

Nie podejmuje sie analizy, poniewaz ani probka nie byla reprezentatywna, ani ankieta nie byla stworzona przez specjaliste. Cel zostal jednak osiagniety – ankieta pokazuje, ze wiele zespolow stosuje praktyki agile na codzien!

Wyglada na to, ze jest jeszcze kilka rzeczy, nad ktorymi mozemy popracowac, np. Continuous Integration, czy Unit Testing, jedank ogolnie wyniki sa zachecajace. Czekam rowniez na wasze opinie!

Ankieta ta miala rowniez nieoczekiwane konsekwencje, w postaci naglosnienia tematu agile na forum pl.comp.programming. Jak sie okazuje, istnieje wiele stereotypow o agile, z ktorymi trzeba sie bedzie uporac, zanim uda sie przekonac srodowisko programistyczne w Polsce do stosowania agile. Ta dyskusja to tylko poczatek. Czekam na wiecej!

Jesli ktos jest nadal zainteresowany zainteresowany wypelnieniem ankiety, zapraszam tu:
Jak bardzo Agile jest twoj zespol?

Posted in Uncategorized | 1 Comment »

assertEquals with Map argument !?!?!

Posted by Piotr Gabryanczyk on October 3, 2007

Problem

Have you ever struggled with:
assertEquals(map1, map2) ?

I did! :( It is almost impossible to figure out how elements differ, especially if they look the same and are of different type. Or if there is more than 5 of them.

Solution

Print out different elements, i.e.
assertEquals(differenceToString(map1, map2), map1, map2) .

 1     public static String differenceToString(Map m1, Map m2) {
 2         StringBuffer buf = new StringBuffer();
 3         for (Object k : m1.keySet()) {
 4             if (!m2.containsKey(k)) {
 5                 buf.append("M2 does not contain " + k + "\n");
 6             }
 7             if (!m2.get(k).equals(m1.get(k))) {
 8                 buf.append( String.format("m1(%s)=%s,%s != m2(%s)=%s,%s\n", k, m1.get(k), m1.get(k).getClass(), k, m2.get(k), m2.get(k).getClass()));
 9             }
10         }
11         for (Object k : m2.keySet()) {
12             if (!m1.containsKey(k)) {
13                 buf.append("M1 does not contain " + k + "\n");
14             }
15         }
16         return buf.toString();
17     }
18 

Enjoy!:)

Posted in Uncategorized | Tagged: | Leave a Comment »

@Configurable without Spring in 10 minutes

Posted by Piotr Gabryanczyk on December 1, 2006

Why

I was asked recently to remove Spring from my project… I know, I know one step forward two steps back… I wasn’t happy at all. It was because Eclipse was crashing when two plugins had its own copy of spring library… Good excuse to remove Spring…

Problem

We are heavily using @Configurable and AspectJ so we needed some mechanism which could replace spring aspect in injecting dependencies.

How

Just look below:

 1 @Aspect()
 2 public class ConfigurableHackAspect {
 3     private static Map<String, Object> beanMap = new HashMap<String, Object>();
 4
 5     public static void registerBean(String id, Object bean){
 6         beanMap.put(id, bean);
 7     }
 8
 9     @After("@within(com.xyz.common.ConfigurableHack) && execution(*.new(..))")
10     public void afterConstructor(JoinPoint jp){
11         for(Field f : getAllFields(jp)){
12             if (f.isAnnotationPresent(InjectDependency.class) && beanMap.containsKey( f.getName())){
13                 try {
14                     f.set(jp.getTarget(), beanMap.get(f.getName()));
15                 } catch (IllegalAccessException e) {
16                     throw new RuntimeException(e);
17                 }
18             }
19         }
20     }
21
22     private Field[] getAllFields(JoinPoint jp) {
23      return jp.getTarget().getClass().getFields();
24     }
25 }

Example usage

 1 class XYZ{
 2      3     @InjectDependency public IMarketDataSupplier marketDataSupplier;
 4      5 }
 6 

Summary

It is not perfect as it requires injected field to be public, but it does the job and is good enough for 10 minutes… :)

Posted in annotations, aop, aspectj, java, spring | 2 Comments »