Taboo-breaker: 10 Hints for Reducing the Pain in Your Hands

  1. Use a splitted/ergonomic keyboard to reduce the bending of the wrist (I could recommed you a relative cheap one). And place the keyboard in the correct high, so that the elbow forms a right angle (or more than 90°). Avoid steep angle of the keyboard – see picture below where I used an additional stick in the front to flatten the angle. And don’t forget to sit in a correct position.
  2. Some people have better results with ordenary, thick keyboards, but some with thin
  3. Prefer skype or telephon over emails and use voice recognition for emails
  4. Use pads before the keyboard to put your thumb and your ball of the thumb there (and your elbows). But don’t use these pads while active writing. Avoid too high armrests – they should be adjustable.
  5. Use a joystick or an other mouse replacements if you have problems with the right index finger or arm. And if you have money you could buy a tablet pc (or palms that support handwriting recognition)
  6. Avoid cold hands e.g. use cropped gloves
  7. If you have to implement an algorithm use a pencil and a paper (and you brain of course) for the initial version
  8. Hack into the keyboard like a pianist (not ‘pressing’ but accelerate your fingers before) and avoid long nails (I guess the most programmers havn’t this problem ;-))
  9. Streching and relaxation of arms and hands (thumb!) every hour. While this procedure you should relax your eyes and you could use a finger trainer from guitarists.
  10. Less programming i.e. read a good book or look videos/DvDs or meet your friends in reality 😉

erg-kb1

5-Line-Replacement of Apache Ant

rm -rf build/
mkdir build
jars=$(find ./lib/ -iname "*.jar" | tr  '\n' ':')
find ./src -iname "*\.java" > files.txt
$JAVAC_CMD -d build/ -cp $jars @files.txt

Okay, it is a very very unfair blog title – only an eye catcher!

But now you can bookmark this useful code snippet to compile your project without installing ant or even an IDE.

… and you could say: “Hey man – this is not platform independent!”.
But then I would say: “Oh yes it is! For windows you should install cygwin of course!”

Keep smiling 😉

Update: on windows with cygwin you have to replace the colon : with a semicolon ;

Hints for Mavenization of Java Web Applications

I discovered that it is not that easy to transform a web application from a native eclipse/netbeans project to a maven project.

Here are some hints which can make your life easier:

  1. To create the project structure for the web application use this command:
    mvn archetype:create -DgroupId=de.mycompany.app123 -DartifactId=mywebapp -DarchetypeArtifactId=maven-archetype-webapp
    Be sure you replaced the 2.3 header with
    <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    this was helpful for fixing this issue:
    "The selected Java EE version does not support selected JavaServer Faces version" + restart netbeans!
  2. To use jdk 1.6 do
    <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.0.1</version>
    <configuration>
    <source>1.6</source>
    <target>1.6</target>

    <encoding>UTF-8</encoding>
    </configuration>
    </plugin>
    Maybe for you it is necessary to use tomcat 5.5 for myfaces 1.1. Therefor you probably have to change the <source> element to 1.5 … Here you can determine the class format version
  3. use
    <repositories>
    <repository>
    <id>java.net</id>
    <name>java.net</name>
    <url>http://download.java.net/maven/2/</url&gt;
    </repository>
    </repositories>
    for the missing dependency in hibernate org.hibernate:hibernate:jar:3.2.1.ga: javax.transaction:jta:jar:1.0.1B
  4. All libraries which you need at compile time but not on the server (like the following) should get an scope=provided
    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
    <scope>provided</scope>
    </dependency>
  5. All libraries which you need for your tests (e.g. junit or hsqldb) should get an scope=test
    <dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.1.102</version>
    <scope>test</scope>
    </dependency>
  6. If your tests are temporarly broken or if you want to speed up testing do:
    <plugin>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.4.3</version>
    <configuration>
    <skip>true</skip>
    </configuration>
    </plugin>
    (See this post for a better solution.)
  7. To invoke the tomcat plugin (‘mvn tomcat:run’) the following code can be necessary
    <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>tomcat-maven-plugin</artifactId>
    <configuration>
    <url>http://localhost:8080/webapp/</url&gt;
    </configuration>
    </plugin>
    This plugin uses tomcat5.5, to use tomcat 6.0 compile it for yourself or run the project from within your IDE with maven plugins.
  8. To invoke the jetty plugin (‘mvn jetty:run’) the following code can be necessary
    <plugin>
    <groupId>org.mortbay.jetty</groupId>
    <artifactId>maven-jetty-plugin</artifactId>
    <version>6.1.10</version>
    </plugin>
  9. You get an exception like the following in NetBeans??
    [ERROR]Runtime Exception thrown during execution
    [ERROR]null

    Solution 1 -> use external maven (command line)
    Solution 2 -> try to recompile the project from command line
    Solution 3 -> try to recompile another maven project + restart the IDE (works only sometimes)

  10. if you want to mavenize jar files -you can use this
  11. to set up you own maven repository you can try this tutorial
  12. And last but not least: Be Warned!

Read the following hints if you are an IDE-guy

  • Install the NetBeans plugin. Installation of this is easy -> Options->Plugins->Install Maven Plugin. To use this plugin simply open the pom.xml directly.
  • Installation of the EclipsePlugin:
    • install tomcat 6.0 server (>6.0.16)
    • you will need WTP >2.0.2
    • add http://m2eclipse.sonatype.org/update/ to your update pages; I didn’t tried q4e
    • and install m2eclipse
    • select the necessary packages (scm and mylyn didn’t worked for me …)
    • if not already done add a jdk as default virtual machine to eclipse
    • specify the same java exe in the eclipse.ini file:
      -vm
      C:\Program Files\Java\jdk1.6.0_07\jre\bin\javaw.exe
    • restart eclipse

Some people want to avoid the stuff related to IDEs – they can!

  • Install maven2
    • Under debian you can simply ‘apt-get install maven’.
    • Under windows you have to add the bin folder of maven to the PATH variable.
  • Type the following in the root directory
    1. mvn install
    2. mvn tomcat:run
  • Then go to http://localhost:8080/yourapp/ with you favorite firefox 😉

Now, my two questions to the readers are:

  • How can change the default tomcat-users.xml under target/tomcat? (for the command ‘mvn tomcat:run’)
    If I would require the user to login (security-constraints in the web.xml) I cannot login …
  • How can I use a master (or parent) module with web applications? I need an example! I already have one for a desktop application.

Skip Executing the Tests of Mavenized Projects

In my project I want to skip that the tests are running on every execution. I know this is not ‘good style’, but I want to execute the tests when I want. I do not recommend this technic on you build server …

One way to achieve this behaviour is to disable the tests in the

<build><plugins>

</plugins><build>

section via

<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.4.3</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>

But now even if we want to run the tests explicitly they will be skipped. Is there a solution for this?

I found a better and very simply solution for NetBeans. Right click the mavenized project in NetBeans, then click on Actions. Now click on an entry; e.g. Run project and select “Skip tests”. This cheat you can apply on all the listed actions (even customized one …).

Do you have a more IDE-independend solution for this?

My stony way to find a ruby on the rails

Ruby is a great language. All can be expressed so short and readable. That’s one side.

The other side is: you have to learn a lot of exceptions to common stuff that you already learned in another languages (In my case Java).

So today I will explain things where it took me a lot of time to understand how to do this and what ruby (and rails) does. Let us start with the very basics: installation and then the pure ruby language.

Setup MySql

If you use debian as OS it is quite simple to install mysql:

sudo apt-get install mysql-server

Then create a database with the following lines

mysql -u root -p
type the following in the mysql shell:

CREATE DATABASE mydb;
GRANT ALL PRIVILEGES ON mydb.* TO 'admin'@'localhost' IDENTIFIED BY 'admin' WITH GRANT OPTION;
FLUSH PRIVILEGES;
quit;

Later on you can log into the mysql database via
mysql -u admin -p
[now type the password ‘admin’]

SHOW TABLES FROM mydb;

I suggest you to use http://www.squirrelsql.org/ to view and even manipulate the database. The nice thing about this java program is: you can simply install the jdbc drivers for your database (e.g sqlite or mysql) and after configuring them you can browse the databases in a nice way!

Install Ruby and Rails

To be independend from Java or if you don’t want to use JRuby you have to install ruby on your machine:

sudo apt-get install ruby libzlib-ruby rdoc irb

Now install gems …

sudo apt-get install rubygems
sudo gem install mysql

… and rails

sudo apt-get install rails

Create a Skeleton Application

Optionally install NetBeans 6.1 (and Java >1.5 before) to get some handy functionality.

Be sure that you choose a package with rails or install the rails plugins via: Tools->Plugins.

Now you should able to create a rails application: New Project->Ruby On Rails Application. Click Next and choose your ruby system. (Or do ‘rails testapp’ on the command line).

You will get a list of created files. To quickly navigate to a file in NetBeans press ALT+SHIFT+O (Oh not zero) and type in the name. Now I will go through some of the generated files:

app/controllers/application.rb

This is the base class for all of our controllers. To study the Model-View-Controller pattern visit wikipedia. In our controllers we put in all of our application logic. For example the password encryption when one of our user logs in.

app/helpers/application_helper.rb

In this helper modul we define some convinient methods for our view

test/test_helper.rb

With this class it is easy to test the implemented (helper) methods. Read “Agile Web Development with Rails” to be surprised that unit and even integration tests are very easy (and fast) to write.
config/database.yml
The generated content looks like:
development:
# your database server:
adapter: mysql
encoding: utf8
database: mydb
username: admin
password: admin
timeout: 5000
# necessary if you are on debian:
socket: /var/run/mysqld/mysqld.sock

config/routes.rb
Here you will define later more fine grained navigation rules for the pages of your web application.

In NetBeans (with rails of course) database-migrating is very easy: right click the project->Migrate Database->To [misc] Version or Clear…

Start the web server with F6 in NetBeans or type

ruby script\server

Then go to http://localhost:3000/ with your browser and you should see ruby’s welcome page.

Now we want to replace the index.html with an erb (like jsp) file. To do this we will remove the public/index.html file and do

script/generate controller home index

add the following to the routes.rb

map.home '', :controller => 'home', :action => 'index'

To add some more functionality to our rails application there are a lot of plugins available. One of them is the restful_authentication, where a tutorial plugin (or here) exists which itself references to a bunch of other useful plugins. Check them out!.

Now some comments on setting up the restful_authentication plugin: Add the following resource to your repositories if you need this plugin (and others from the author):

script/plugin source http://svn.techno-weenie.net/projects/plugins/script/plugin install restful_authentication

or simply do

script/plugin install http://svn.techno-weenie.net/projects/plugins/restful_authentication/

On my machine it took a lot of time and finished with an timeout error so I did:

sudo apt-get install git-corecd vendor/plugin && git clone git://github.com/activefx/restful_authentication.gitmv restful-authentication/ restful_authentication/ && cd ../..

Now generate the necessary classes:

script/generate authenticated user sessions --include-activation --stateful

My (unsorted) Comments

Try getting started with rails and come back here to read the following comments (or post your own!) if you figured out sth. worth enough to be said for beginners.

  1. For restful_authentication:
    Be sure that you ignore the config/initializers/site_keys.rb in your subversion!! But save it, because you will need it for your application!
  2. If need a login snippet like the one from the authentication tutorial:
    app/views/users/_user_bar.html.erb in your start up weü page app/views/home/index.html.erb
    Use the following line:
    <%= render(:partial => “users/user_bar”) %>
  3. If you need ssh2 try:
    # require ‘digest/sha1’
    require ‘digest/sha2’
    def User.mydigest(str)
    Digest::SHA256.digest(str)
    #Digest::SHA1.hexdigest(str)
    end
  4. What the hell is this string with a colon? I mean the ‘:password’ here:
    update_attributes :password => ‘secure’
    It is called symbol and is the name of a variable e.g. of a class. Where ‘secure’ is the value of the variable password. So with this method call e.g. within the User class you do password = ‘secure’.
    Example:
    var = { ‘a’ => ‘b’, 1 => ‘c’}
    assert_equals(‘b’, var[‘a’])
  5. And what is the :password => ‘secure’ statement?
    This is a key => value expression without the {} braces of the hash (Map in Java) , which are optional if the hash is the last parameter. This is very handy if you have several properties to set.
  6. What is ‘self’? It depends! Read more about self here!
    • global variables begins with @@
    • object variables begins with an @ (All the instance methods of a class can access this variable. So every object has its own set of object variables.)
    • local variable begins with a lower case character (except ‘self’)
    • constant variables begins with an upper case character (except ‘:symbol’)

    Warning: if you don’t add self in front of you object variables, ruby assumes that they are local!?

  7. What is attr_accessor :name? This will create a getter and a setter for the variable ‘name’.
    Or define a setter manually (via operator overloading)
    def volume=(vol)
    leftChannel = self.rightChannel = vol
    end
  8. Where is the constructor of User? Do
    user = User.new
  9. escape html in the view via h(user_input).
    For more security related stuff look here, here and here.
  10. The following line is not always secure (‘mass assignment’)
    User.new(params[:user])
    To make it secure do:
    attr_accessible :name
    Now only the variable name can be change via url parameters.
  11. The following statement is unsecure
    User.find(:all, :conditions => [“name like ‘%#{params[:query]}%'”])
    Use
    :conditions => “name like ?”, ‘%’ + params[:query] + ‘%’
  12. add filter_parameter_logging :password to application.rb
    => all fields with names like “password” will get [FILTERED] in the logs
  13. Rails add a very handy method to objects:
    o.blank?
    An object is blank if it‘s false, empty, or a whitespace string. For example, “”, ” “, nil, [], and {} are blank. Taken from here.
  14. There is no counter++
    Use counter += 1
  15. Swapping variables:
    a, b = b, a
    This work in methods too! E.g. return a pair of variables via
    def meth
    return a, b
    end
    Now call the method
    b, a = meth
  16. if sugar – ‘the other wayround’
    puts ‘hello world’ if str == ‘name’
  17. defined? var
    will return true if there is a field named var
  18. You can use ‘hello’ or “hello”
    The only difference for those strings is the expression evaluation like “#{var}”
    This will work only in “”
  19. comments are like in bash: #
    Or use this to comment several lines:
    =begin
    here is comment
    here too. WARING: =begin and =end has to be the first characters on the lines!
    =end
  20. Default values for method parameters via
    def meth(param=’test’)
    end
  21. def see_how_to_throw
    begin
    # Do something nifty
    raise SomeError, “This is the error message!”
    rescue SomeError
    # This is executed when a SomeError exception is raised
    # to rethrow do
    # raise $!
    rescue AnotherError => error
    # Here, the exception object is referenced from the
    # `error’ variable
    else
    # This is executed only if no exceptions were raised
    ensure
    # This is always executed, exception or not
    end
    end
  22. A very useful tool for testing is autotest:
    gem install ZenTest
  23. It is eays to test with rails! Very easy to write unit and functional testing of your controllers and the pages.
    In NetBeans press ALT+F6 to start them.
  24. use %{ } for xml strings directly unescaped in the code! Very handy.
  25. Time sugar:
    3.minutes + 3.hours
    returns the result in seconds! Much more …
  26. counter ||= 0
    This statement will only be executed if counter is nil. Useful for singletons you think? Use self for this!
  27. Unicode support is not that good. Use Chars instead of the built in String class. Or convert to Chars before working with strings.
  28. Why are there named routes in routes.rb?
    These routes are accessible from the view. E.g. the following line is a named route (map.hello instead of map.resource)
    map.hello ‘/fhello’, :controller => ‘users’, :action => ‘hello’
    So the method hello will be invoke if the user click the link in the view which is generated via <%=hello_url%>
    One special name ‘map.resources’ indicates that rails should create 7 standard routes (4 of them are the CRUD methods). For example map.resources :articles will create the following routes:
    /articles (GET=>shows all, POST=>create a new)
    /articles/new (shows html for new article)
    /articles/1 (GET=>shows the first article, PUT=>update, DELETE=>deletes the article)
    /articles/1;edit
  29. parsing invalid xml with require ‘rubygems’ and require ‘rubyful_soup’. Then do:
    xml_data = Net::HTTP.get_response(URI.parse(url)).body
    doc = BeautifulSoup.new(xml_data)

Testable HibernateUtil

I have seen many projects using the HibernateUtil which was proposed in the docs.

This class is not really testable because for example you cannot configure that it should use the test database. Normally I would suggest you using Spring and avoiding the singleton pattern, but there is a also a simple work around: introduce a setConfiguration and you will have a better HibernateUtil class:

public final class HibernateUtil {
    private static final Class<?> mappedClasses[] = new Class<?>[] { Bla1.class, Bla2.class };
    private static Configuration cfg;
    private static SessionFactory sessionFactory;
    private static final Logger log = Logger.getLogger(HibernateUtil.class);

    /** Returns the configuration object. configure() was already called.  */
    public static synchronized Configuration getConfiguration() {
        if (cfg == null) {
            log.debug("Configuring from annotations");
            AnnotationConfiguration annoCfg = new AnnotationConfiguration();
            for (Class<?> c : mappedClasses) {
                annoCfg = annoCfg.addAnnotatedClass(c);
            }
            cfg = annoCfg.configure();
        }
        return cfg;
    }

    public static void setConfiguration(Configuration config) {
        cfg = config;
    }

    /** Drop and recreate the schema */
    public static void recreateSchema() {
        SchemaExport schemaTool = new SchemaExport(getConfiguration());
        schemaTool.drop(true, true);
        schemaTool.create(true, true);
    }

    /** This method returns a session-factory. */
    public static synchronized SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            sessionFactory = getConfiguration().buildSessionFactory();
        }
        return sessionFactory;
    }
}

Now you can use the following junit (v4) test as a base class for all test classes that will use HibernateUtil:

public class HibernateTestCase {
 protected Logger log = Logger.getLogger(HibernateTestCase.class);
 private Session session;
 private static SessionFactory sessionFactory;

 static {
    // H2 database works only if Bla.id has one of the following annotations:
    // @GeneratedValue(strategy = GenerationType.SEQUENCE) or GenerationType.TABLE
    HibernateUtil.setConfiguration(HibernateUtil.getConfiguration()
     .setProperty("hibernate.connection.driver_class", "org.h2.Driver")
     .setProperty("hibernate.connection.url", "jdbc:h2:mem:bla-test-db2")
     .setProperty("hibernate.connection.driver_class", "org.h2.Driver")
     .setProperty("hibernate.connection.username", "sa")
     .setProperty("hibernate.connection.password", "")
     .setProperty("hibernate.default_schema", "MY_SCHEMA")
     .setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect")
     .setProperty("current_session_context_class", "thread")
     .setProperty("hibernate.cache.provider_class", "org.hibernate.cache.NoCacheProvider")
     .setProperty("hibernate.show_sql", "true"));

  sessionFactory = HibernateUtil.getSessionFactory();
  Session session = sessionFactory.getCurrentSession();

  assertFalse(HibernateUtil.getConfiguration().getProperty("hibernate.connection.driver_class").equals(
				"specify here you driver used in production"));
  // We only need to create the schema for in-memory databases and for newly created databases!
  boolean freshDatabase = true;
  if(freshDatabase) {
  	session.beginTransaction();
  	String CREATE_SCHEMA = "create schema MY_SCHEMA";
  	session.createSQLQuery(CREATE_SCHEMA).executeUpdate();
  	session.getTransaction().commit();
  	session = sessionFactory.getCurrentSession();
  }

  session.beginTransaction();
  HibernateUtil.recreateSchema();

  if (session.isOpen()) {
  	session.close();
  }
 }

 @Before
 public void setUp() throws Exception {
  session = sessionFactory.getCurrentSession();
  session.beginTransaction();
 }

 @After
 public void tearDown() throws Exception {
  session.getTransaction().rollback();
  if (session.isOpen()) {
  	session.close();
  }
 }

 public Session getSession() {
  return session;
 }

 public void commitAndCreateNewSession() {
  session.getTransaction().commit();
  session = sessionFactory.getCurrentSession();
  session.beginTransaction();
 }
}

Security in Java Enterprise

This week I attended the conference “herbstcampus” in Nürnberg (Germany). There were several great sessions and workshops about Java and the like.

One great session was from Arne Limburg from OpenKnowledge about security access controlling and management in Java. In this very clear and unbiased comparison he lists solutions for

  1. user based access control (JAAS)
  2. role based access control (EJB and Spring Security)
  3. access control lists (Spring Security)

They have different advantages and problems. Now the point of this post is that he develops the JPASecurity (Apache 2 license), which solves the problem that you sometimes need to restrict the access on objects (not only on classes).

One example why I think this is a great tool:

With JPASecurity it is possible to receive only those objects from the database (via JPA) which are allowed for the current user. That means it does not load all objects into memory and filters the unallowed. It simply queries only the necessary objects! Get started with his tutorial.

One Interface. Several Implementations. And only one Test? Yes!

Maybe others already use this testing-technique or pattern (Hey, we could call it OISI-test pattern ;-)). But I would like to share this information with you.

It is again my timefinder project where I had this kind of problem. I developed different implementations of the assignment algorithm for my heuristic ‘NoCollisionPrinciple’ which optimizes a timetable for universities. See track2 of the international timetabling competition for more information on that subject.

I created these implementations to compare the quality and performance of the heuristic which uses only the AssignmentAlgorithm interface.

While developing a new implementation the main question for me was:

Should I really write all the test code again?

The answer is simple: Nope!

I put all the test code in one abstract test class called AbstractAssignmentAlgorithmTester which uses only the interface in the normal testing methods (see the additional comments). Later I added the following method:

protected abstract AssignmentAlgorithm createAlgorithm();

Then I created an almost empty subclass which extends AbstractAssignmentAlgorithmTester for every new implementation. For example this one:

public class KuhnMunkresAlgorithmTest extends AbstractAssignmentAlgorithmTester {
    @Override
    protected AssignmentAlgorithm createAlgorithm() {
        return new KuhnMunkresAlgorithm();
    }
}

Now you can run every single test class which extends the abstract class. In NetBeans you can do this by going to the class and pressing SHIFT+F6. Or simply press ALT+F6 to run all tests.

Another problem I had to solve was the case of a faster approximation algorithm. The quality of the results were not always optimal and so certain tests will fail, even if the algorithm was correctly implemented. The solution is simple: overwrite these failing methods with stub methods to exclude them from the run. For example add the following method to TooSimpleApproxTest:

@Override
public void testCalculate() { /* we will get 6.0 instead of the best minimal total sum = 1.0 */ }
Additional comments:
  • The reason for the ‘strange’ name (…Tester) of the abstract class is that junit shouldn’t execute the abstract class (which would result in an error if we name it …Test). The testing tools testng and junit will hopefully make it easier in the future to test against interfaces and not only implementations. They could support testing abstract classes by looking for sub-test-classes and running all of them instead of the abstract class (and printing an error).
  • You can grab the source (Apache2 licensed) via:
    svn checkout https://timefinder.svn.sourceforge.net/svnroot/timefinder/trunk timefinder
    Look in the package timefinder-core/src/main/java/de/timefinder/core/algo/assignment

    To build it you have to use maven.
    And at the moment it is necessary to check out the latest revision of mydoggy (hopefully 1.5.0 will be released soon).

  • One example for a method in the abstract test class is the following:
    @Test
    public void testAssignmentCalculation() {
     // look in the following matrix for that specific assignment
     // which has the minimal sum. which should be 15.
     float matrix[][] = new float[][]{
       {4, 6, 1, 2},
       {5, 6, 7, 6},
       {7, 4, 5, 8},
       {4, 4, 6, 8}
     };
     // One of the best results is the following assignment:
     // Use the '4' in row_3 (room) and colum_0 (event)
     // Use the '4' in row_2 and colum_1
     // Use the '1' in row_0 and colum_2
     // Use the '6' in row_1 and colum_3
     // Do you find a better one ;-)
     int expResult[][] = new int[][]{{3, 0}, {2, 1}, {0, 2}, {1, 3}};
     int result[][] = algorithm.computeAssignments(matrix);
    
     // resSum should be 15. this is the sum over the assignment entries
     float resSum = AssignmentHelper.calculateSum(matrix, result);
    
     // resSum should be the same as the expected sum:
     float expSum = AssignmentHelper.calculateSum(matrix, expResult);
    
     assertEquals(expSum, resSum);
    }

Mavenized projects in NetBeans 6.1

Some weeks ago I mavenized timefinder to allow developers coding in other IDEs than NetBeans. I am new to all the maven stuff, but NetBeans 6.1 support is good (I have not compared it e.g. to eclipse :-/)

Now I explored a really great feature within NetBeans: you can resolve dependencies very easy: hit ALT+Enter. For example:



and hit "Search Dependency at Maven Repository".

Then choose a repository and hit add. After installing the jar in your local maven repository you will be able to resolve this particular dependency via CTRL+SHIFT+I. That’s it!

One big problems remains: you cannot profile maven projects. So, I thought it would be good to create a separate ‘pure’ NetBeans-Project where I link the source which are already used from the mavenized project. But this isn’t allowed! I don’t know why. So I hacked it under linux. This is straightforward:

create symbolic links from the pure-netbeans project to the mavenized one!

go into the ‘pure’ NetBeans-Project ‘mkdir source && cd source’  then type:

ln -s ../../../timefinder-core/src/main/resources/ core-res
ln -s ../../../timefinder-core/src/main/java/ core-src
ln -s ../../../timefinder-core/src/test/resources/ core-test-res
ln -s ../../../timefinder-core/src/test/java/ core-test-src

After this step right click the pure-project and add the source and test folders to the project



One more reason to do this is that compilation (clean & build; without tests) and
starting (until the first log statement) are slower with mavenized projects.
In my simple project with approx. 100 files you get with jdk 1.6:
     pure project compilation: max. 3 sec
mavenized project compilation: > 15 sec
             pure project run: max. 1 sec
        mavenized project run: > 4 sec

That's why I like the eclipse approach of mvn eclipse:eclipse 😉 but this has other disadvantages ...