Piotr Gabryanczyk’s Blog

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

  • Blogroll

    • I have joined Anti-IF Campaign

Anemic Domain Model – resources

Posted by Piotr Gabryanczyk on December 13, 2012

Fowler about the problem:
http://www.martinfowler.com/bliki/AnemicDomainModel.html

Hibernate:
http://wrschneider.blogspot.com/2005/01/avoiding-anemic-domain-models-with.html

Double Dispatch
http://stackoverflow.com/questions/227856/how-to-avoid-anemic-domain-models-and-maintain-separation-of-concerns
http://www.c2.com/cgi/wiki?DoubleDispatchExample

Posted in refactoring | 2 Comments »

Learn Russian with russian-lessons.co.uk

Posted by Piotr Gabryanczyk on May 8, 2011

I just finished my new project http://www.russian-lessons.co.uk.
It took me 2 days and it’s been done entirely with html 5.

If you want to learn Russian in London check it out!

Posted in Uncategorized | Tagged: , , , | 1 Comment »

Converting Maven pom.xml to SBT

Posted by Piotr Gabryanczyk on November 14, 2010

Add this task to your project class.
Run reload, then pom2sbt.
Copy the output to the project file and enjoy!

lazy val pom2sbt = task {
    val deps = XML.load("pom.xml") \\ "dependencies"
    deps \"dependency" foreach( (dependency:Node) => {
      val groupId = (dependency \ "groupId").text
      val artifactId = (dependency \ "artifactId").text
      val version = (dependency \ "version").text
      val scope = (dependency \ "scope").text
      val classifier = (dependency \ "classifier").text
      val artifactValName: String = artifactId.replaceAll("[-\\.]", "_")

      print("val %s = \"%s\" %% \"%s\" %% \"%s\"".format(artifactValName, groupId, artifactId, version))
      scope match  {
        case "" => print("\n")
        case _ => print(" %% \"%s\"\n".format(scope))
      }
      None
    } )
    None
  }

Posted in Uncategorized | Tagged: , , , , | 1 Comment »

How to resolve java dependency from the command line without maven

Posted by Piotr Gabryanczyk on September 26, 2010

Problem

I want to be able to download java library and it’s dependencies using simple command-line tool i.e.
ivy.sh resolve jetty jetty 5.1.10

Solution

  • Download Ivy. Ivy understands maven repositories and can do the job for you.
  • Create a script ivy.sh in ivy installation directory with the following content:

    cd=`dirname $0`
    if [ "$1" == "resolve" ]; then
            shift
            echo "Resolving $1 $2 $3"
            java -jar $cd/ivy-2.2.0-rc1.jar -retrieve ./[artifact]-[revision]-[type].[ext] -dependency $*
    fi

  • Make your script executable:
    chmod a+x ivy.sh
  • Add it to the path ie. ~/.bash_profile
    export PATH=$PATH:/where/you/have/ivy.sh

Enjoy!

Posted in Uncategorized | 1 Comment »

Gradle Cobertura Integration Revisited

Posted by Piotr Gabryanczyk on April 17, 2010

Problem

I’d like to run cobertura coverage report using gradle in a non intrusive way similar to maven.
I just want to do this:

gradle cobertura


and in my script:

apply from: 'cobertura.gradle'

Current solution

There is a great solution to this problem here. It works, but is not as unintrusive and not as easy to use as I would like it to be.

My solution

This works for Gradle version 0.9-preview-1.

cobertura.gradle:

logger.info "Configuring Cobertura Plugin"

configurations{
  coberturaRuntime {extendsFrom testRuntime}
}

dependencies {
  coberturaRuntime 'net.sourceforge.cobertura:cobertura:1.9.3'
}

def serFile="${project.buildDir}/cobertura.ser"
def classes="${project.sourceSets.main.classesDir}"
def classesCopy="${classes}-copy"


task cobertura(type: Test){
  dependencies {
    testRuntime 'net.sourceforge.cobertura:cobertura:1.9.3'
  }  

  systemProperties["net.sourceforge.cobertura.datafile"] = serFile
}

cobertura.doFirst  {
  logger.quiet "Instrumenting classes for Cobertura"
  ant {
    delete(file:serFile, failonerror:false)
    delete(dir: classesCopy, failonerror:false)    
    copy(todir: classesCopy) { fileset(dir: classes) }

    taskdef(resource:'tasks.properties', classpath: configurations.coberturaRuntime.asPath)
    'cobertura-instrument'(datafile: serFile) {
      fileset(dir: classes,
              includes:"**/*.class",
              excludes:"**/*Test.class")
    }
  }
}

cobertura.doLast{
  if (new File(classesCopy).exists()) {
    ant.'cobertura-report'(destdir:"${project.reportsDir}/cobertura",
            format:'html', srcdir:"src/main/java", datafile: serFile)

    ant.delete(file: classes)
    ant.move(file: classesCopy, tofile: classes)
  }
}


And then your build.gradle could look like that:

apply plugin: 'java'
apply from: 'cobertura.gradle'
...

Posted in Uncategorized | Tagged: , , | 3 Comments »

How to run a system command in Erlang?

Posted by Piotr Gabryanczyk on April 2, 2010

Problem

I would like to be able to run ie. ls -al / from erlang and process the results using erlang. ie.

Files = cmd:run("ls -al /").

Solution

-module(cmd).
-export([run/1, run/2, test/0]).

run(Cmd) -> 
	run(Cmd, 5000).
	
run(Cmd, Timeout) ->
	Port = erlang:open_port({spawn, Cmd},[exit_status]),
	loop(Port,[], Timeout).
	
loop(Port, Data, Timeout) ->
	receive
		{Port, {data, NewData}} -> loop(Port, Data++NewData, Timeout);
		{Port, {exit_status, 0}} -> Data;
		{Port, {exit_status, S}} -> throw({commandfailed, S})
	after Timeout ->
		throw(timeout)
	end.

test() -> 
	shouldReturnCommandResult(),
	shouldThrowAfterTimeout(),
	shouldThrowIfCmdFailed(),
	{ok, "Tests PASSED"}.

shouldReturnCommandResult() ->
	"Hello\n" = run("echo Hello").

shouldThrowAfterTimeout()->
	timeout = (catch run("sleep 10", 20)).
	
shouldThrowIfCmdFailed()->
		{commandfailed, _} = (catch run("wrongcommand")),
		{commandfailed, _} = (catch run("ls nonexistingfile")).

Posted in Uncategorized | Tagged: , , | 8 Comments »

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: | 3 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 | 11 Comments »

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 | 7 Comments »

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 | 3 Comments »

 
Follow

Get every new post delivered to your Inbox.