Piotr Gabryanczyk’s Blog

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

  • Blogroll

    • I have joined Anti-IF Campaign

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 http://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
Advertisements

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 »

Mocking difficult objects like HttpServletRequest with CGLIB

Posted by Piotr Gabryanczyk on May 19, 2008

Why haven’t I seen this before?
http://www.sixlegs.com/blog/java/concrete-mock-objects.html

Posted in java | Tagged: , , , | 4 Comments »

Encoding in forms sent using POST method

Posted by Piotr Gabryanczyk on May 7, 2008

I struggled a lot with encoding in Tomcat before I found this post on Adam’s Warski blog.

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

How to UnZip archive in Java

Posted by Piotr Gabryanczyk on May 7, 2008

Why am I writing about it?

Because I could not find complete solution for unzipping archive in java.

Dependencies

You will need commons-io.jar from apache commons.

Random thoughts…

It is too small to release it as an open source library, and Apache Commons does not contain such a function, when I am writing it this post. Please feel free to copy/use/modify this code.

public class ZipUtils {
    Logger log;

    public ZipUtils(Logger log) {
        this.log = log;        
    }

    public void unzipArchive(File archive, File outputDir) {
        try {
            ZipFile zipfile = new ZipFile(archive);
            for (Enumeration e = zipfile.entries(); e.hasMoreElements(); ) {
                ZipEntry entry = (ZipEntry) e.nextElement();
                unzipEntry(zipfile, entry, outputDir);
            }
        } catch (Exception e) {
            log.error("Error while extracting file " + archive, e);
        }
    }

    private void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException {


        if (entry.isDirectory()) {
            createDir(new File(outputDir, entry.getName()));
            return;
        }
        
        File outputFile = new File(outputDir, entry.getName());
        if (!outputFile.getParentFile().exists()){
            createDir(outputFile.getParentFile());
        }

        log.debug("Extracting: " + entry);
        BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
        BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));

        try {
            IOUtils.copy(inputStream, outputStream);
        } finally {
            outputStream.close();
            inputStream.close();
        }
    }

    private void createDir(File dir) {
        log.debug("Creating dir "+dir.getName());
        if(!dir.mkdirs()) throw new RuntimeException("Can not create dir "+dir);
    }
}

Posted in java | Tagged: | 7 Comments »

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 »