Piotr Gabryanczyk’s Blog

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

  • Blogroll

    • I have joined Anti-IF Campaign

How to download JavaDocs or sources in Maven 2?

Posted by Piotr Gabryanczyk on June 25, 2009

Problem

You want to download javadocs for your depenencies into local repository to be able to use them ie. in IntelliJ.

Solution


mvn dependency:resolve -Dclassifier=javadoc
mvn dependency:resolve -Dclassifier=sources

Enjoy!

Posted in java | Tagged: | 2 Comments »

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 »

ANT script good practices – few thoughts

Posted by Piotr Gabryanczyk on September 15, 2008

In general scripts should be treated as first class citizens, so they need to be simple, modular, clean, easy to read and understand and loosely coupled.

Here are some techniques which should help with it:

All the OO principles apply!

When you need custom functionality for your project i.e. custom make step – do not bloat the common files with conditional logic. Extract common stuff to macrodefs and create separate files and/or targets for custom functionality in local project directory. Basically all the OO principles apply!

Break it down and modularize

You wouldn’t like to have just one big class in your project – do the same with ant script, break it down and modularize

Stop writing generic ant targets parametrized by global properties

Replace them with macrodefs. See:
http://ant.apache.org/manual/CoreTasks/macrodef.html

Stop using global properties

Don’t use them, unless they are really global i.e. project.name, project.version. In general they are evil as global variables and singletons are. See:
http://blogs.msdn.com/scottdensmore/archive/2004/05/25/140827.aspx
http://www.cs.usfca.edu/~wolber/courses/110/lectures/globals.htm

Use convention over configuration design paradigm.

What does it mean? Basically this:
Instead of writing (unneccessary abstraction and complexity):

<property name="project.dir" value="${basedir}"/>
<property name="test.result.dir" value="${project.dir}/build/testresult"/>
<javadoc dest="${test.result.dir}>
...

We would write:

<javadoc dest="build/testresult">
...

Simpler and more readable!
See more here:
http://en.wikipedia.org/wiki/Convention_over_Configuration

Use maven-like project directory structure

This supports convention over configuration approach and simplifies your build scripts.

project
- src
  +- main
     +- java
     +- config
     +- scripts
     +- ...
  +- test
     +- java
     +- config
     +- ...
- lib
  +- compile
  +- runtime
     +- spring-2.0.jar
     +- jakarta-commons
        +- commons-io.jar
        +- commons-???.jar
     +- ...
  +- test
- ant (contains common ant tasks - it should be symbolic link as this scripts should be shared)
  +- ant-common.xml
  +- ant-test.xml
  +- ...
- target ( temporary directory, only RW area of the project, equivalent to build)
- modules (if the code contains modules build separately like c++)
  +- SomeNativeLib
      +- src
      +- lib
      +- ...
  +- OtherJavaModule
      +- src
      +- lib
      +- ...
- build.xml

Enjoy!

Posted in java, programming | Tagged: , | 3 Comments »

Programming for Stone Age

Posted by Piotr Gabryanczyk on August 5, 2008

I liked this post of Conan so much that I wanted to share it:
Programming for Stone Age

Enjoy!

Posted in agile | 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 »

Rejsy morskie, wolne koje – twoja-zaloga.pl

Posted by Piotr Gabryanczyk on June 4, 2008

Pracuje wlasnie nad projektem:
http://twoja-zaloga.pl

O co chodzi?

Strona pozwala zeglarzom na znalezienie ciekawego rejsu. Dla kapitanow
to mozliwosc opublikowania ogloszenia o rejsie i znalezienia
brakujacych zalogantow.
Wpisalem juz tam kilka swoich rejsow, oraz kilka rejsow znalezionych w
sieci :)
Czekam na Wasze wpisy!:)

Za darmo???

Ogloszenia sa oczywiscie bezplatne, jednak zachowuje sobie prawo do
ich usuniecia jesli beda lamac zasady dobrego smaku lub agresywnie
reklamowac prywatne firmy. Pewnie wprowadze sekcje ogloszen
komercyjnych jesli bedzie takie zapotrzebowanie.

Dlaczego?

Sam jestem zeglarzem i szukam czasem rejsow lub zalogantow… :) Tak!
Ta strona jest glownie dla mnie i takich jak ja :) )

Beta

Strona nie jest jeszcze piekna(czeka na grafika – moze ktos z Was chce
sie tego podjac?) i jest w wersji beta. Nie mniej jednak zawiera juz
sporo rejsow, ktore odbeda sie tego lata i na ktore mozna sie
zapisac.

Co Wy na to?

Chcialbym was prosic o komentarze, co Wam sie podoba, a co nie. Czy w
ogole taki website bylby Wam przydatny.

Piszcie na:
uwagi@twoja-zaloga.pl

Posted in sailing | Tagged: , , , , , | 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 »