Archive for the ‘programming’ Category

Why Git Rocks

Tuesday, September 29th, 2009

Well, it just does.

Maven cheatsheet

Tuesday, January 6th, 2009

Search for maven artifacts


http://maven.ozacc.com/
http://www.mvnrepository.com/

Create a new project (standard application)


mvn archetype:create -DgroupId=com.mycompany.app -DartifactId=my-app

Create a new project (web application)


mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-webapp -DgroupId=com.mycompany.app -DartifactId=my-webapp

Resolve all dependencies


mvn dependency:resolve

Resolve all dependencies & their source attachments


mvn dependency:sources

Analyze dependencies


mvn dependency:analyze

Generate Ant build files


mvn ant:ant

Remove target directory & all build data


mvn clean

Compile


mvn compile

Build the package (JAR is the default)


mvn package

Only compile the unit tests


mvn test-compile

Compile & execute unit tests


mvn test

Compile & execute a single test


mvn -Dtest=MySingleTest test

Copy all the dependencies to target/dependency


mvn dependency:copy-dependencies

Assemble a package with all dependencies included


mvn assembly:assembly -DdescriptorId=jar-with-dependencies

Assemble a package with the sources


mvn assembly:assembly -DdescriptorId=src
mvn source:jar
mvn source:test-jar

Skip the tests when packaging


mvn -Dmaven.test.skip=true ...

Install an external jar into our local repo


mvn install:install-file -DgroupId=javax.transaction -DartifactId=jta -Dversion=1.0.1B -Dpackaging=jar -Dfile=/path/to/file

VCS Checkin


mvn -Dusername=username -Dpassword=password -Dmessage="Some message" scm:checkin

Prepare a release


mvn release:prepare

Translate 1.5+ project with retrotranslator


mvn package retrotranslator:translate-project

Crashing Javac

Sunday, January 4th, 2009

It seems that lately I have been crashing javac… :-(


An exception has occurred in the compiler (1.6.0_10-rc). Please file a bug at the Java Developer Connection (http://java.sun.com/webapps/bugreport)  after checking the Bug Parade for duplicates. Include your program and the following diagnostic in your report.  Thank you.

java.lang.NullPointerException
  at com.sun.tools.javac.comp.Check.checkCompatibleConcretes(Check.java:1215)
  at com.sun.tools.javac.comp.Check.checkCompatibleSupertypes(Check.java:1567)
  at com.sun.tools.javac.comp.Attr.attribClassBody(Attr.java:2674)
  at com.sun.tools.javac.comp.Attr.attribClass(Attr.java:2628)
  at com.sun.tools.javac.comp.Attr.attribClass(Attr.java:2564)
  at com.sun.tools.javac.comp.Attr.visitClassDef(Attr.java:525)
  at com.sun.tools.javac.tree.JCTree$JCClassDecl.accept(JCTree.java:575)
  at com.sun.tools.javac.comp.Attr.attribTree(Attr.java:360)
  at com.sun.tools.javac.comp.Attr.attribStat(Attr.java:397)
  at com.sun.tools.javac.comp.Attr.attribClassBody(Attr.java:2697)
  at com.sun.tools.javac.comp.Attr.attribClass(Attr.java:2628)
  at com.sun.tools.javac.comp.Attr.attribClass(Attr.java:2564)
  at com.sun.tools.javac.main.JavaCompiler.attribute(JavaCompiler.java:1036)
  at com.sun.tools.javac.main.JavaCompiler.compile2(JavaCompiler.java:765)
  at com.sun.tools.javac.main.JavaCompiler.compile(JavaCompiler.java:730)
  at com.sun.tools.javac.main.Main.compile(Main.java:353)
  at com.sun.tools.javac.main.Main.compile(Main.java:279)
  at com.sun.tools.javac.main.Main.compile(Main.java:270)
  at com.sun.tools.javac.Main.compile(Main.java:69)
  at com.sun.tools.javac.Main.main(Main.java:54)

 

The thing mostly annoying about the situation is that it is messing up with my project plan!

From MikTeX to TeXLive

Wednesday, September 10th, 2008

Since I am stuck with Windows, I guess the viable solution for LaTeX is MikTeX. It had served its purpose well, untill recently, when out of a sudden, a XeLaTeX-based project I am working on either could not compile or the resulting PDF was partly unreadable. I reinstalled the whole thing, tried a few quirks but alas!

Then I thought to give TeXLive a try. The documentation, especially as far as installation is concerned, is not good to my taste, but everything went smoothly. As a developer who respects oneself, I already had Perl+Tk installed in my machine, so the GUI installer popped up with no problem and did its job well.

The good news is that now my XeLaTeX project is functional again, out-of-the-box. Good work people of TeXLive!!!

I have been making software for a living for the past decade. But I am just a plain user too. Users demand solutions, meaning things that work; and TeXLive works. This makes me a happy user :-)

Stuck with Windows

Wednesday, September 10th, 2008

For several reasons, I have been stuck with a Windows environment for the past two years. I am trully missing Linux… I recently tried VirtualBox but it crashed a few times and after that suddenly my network settings in the Linux Guest went bad. Since I was out of touch, I tried to re-read some man-pages and figure out how to resolve the issues, but with no luck. The worse is that it drained half of my day and my time is really precious now.

So I am back to Windows only, with cygwin, gnuwin32, console2 and some other handly stuff…

Rise of the Community - Phase Two

Wednesday, September 3rd, 2008

It is a few days ago that I volunteered to maintain scalap. Writing with Scala has been more than fun and I decided it was time to write for Scala. My time is limited, but the barrier has been, at some percentage, a psychological one. Dealing with the very stuff itself, is something to be taken seriously.

Yesterday, I was glad to read, Scala Team’s open request for maintainers from the community. The Scala community has already been very energetic and passionate: No egoisms, eager to provide help in its members, active at reporting bugs and even patches or new implementations. David R. McIver quickly responded and is now probably washing his hands before diving into the pattern matcher.

At these very moments, we are experiencing a new rise of the community!

Enter reflection, meet type unsoundness

Sunday, August 17th, 2008

The theoretically-inclined may judge if the subject correctly characterizes the situation I am about to describe.

At some point while programming a library (in Scala, of course), I thought it would be a nice idea to abstract over some compiler-powered magic regarding the handling of for-comprehensions, and in particular those compiled to foreach() calls. So, I came up with this:


type ForEach[T] = {
  def foreach(f: T => Unit): Unit
}

Now, let’s define a generic function:


def foreachWrapper[T](container: ForEach[T], f: T => Unit) {
  for(value < - container)
    f(value)
}

So, any type adhering to the ForEach structural contract can be passed to foreachWrapper. Of course this is a trivial function, but suffices for the purpose of this post.

Now, we know that Lists and Arrays are specially handled by the compiler when appearing in a for(v <- c) construct, and we deserve the right to believe that this:


foreachWrapper(List(1, 2))

and this:


foreachWrapper(Array(1, 2))

will type-check. And indeed they do, as expected. So our program is correct.

But if we try to run it (see the complete code at the bottom of this post), we get an exception:


java.lang.NoSuchMethodException: [I.foreach(scala.Function1)

Hmmmm.... What the Hack??? The situation is blurred (note that [I is the class of an integer array in Java). But wait a minute!

We know that structural types, implementation-wise, interfere with reflection, and there is where the exception comes from. And this is all because Scala does its best to handle arrays in the most balanced way.. Array(1, 2) is compiled to a respective Java array but Java arrays do not define a foreach method!

As expected, If we force Scala to box the array, using this trick:


def boxMe[T](me: Array[T]): Array[T] = me

then there is no problem at all…

C’est la vie. You get something, you lose something else…

The complete code follows:


object foreach {
  type ForEach[T] = {
    def foreach(f: T => Unit): Unit
  }

  def foreachWrapper[T](container: ForEach[T], f: T => Unit) {
    for(value <- container)
      f(value)
  }

  def boxMe[T](me: Array[T]): Array[T] = me

  def rollIt[T](container: ForEach[T]) {
    println("-- Iterating over: " + container.getClass.getName)
    foreachWrapper(container, println)
  }

  def main(args: Array[String]) {
    val intList = List(1, 2)
    val intArray = Array(1, 2)

    rollIt(intList)
    rollIt(boxMe(intArray))
    rollIt(intArray)  // Exception!
  }
}

Language-Level LazyVals in Scala

Thursday, July 24th, 2008

[This is from http://www.nabble.com/Question-on-lazy-val-td17678892.html]

For what it’s worth, I fast-coded a hack that implements lazy vals at the language level, mimicking the compiler’s implementation. It turns out 120% slower that built-in lazy vals, if using the client HotSpot (default) and 40% slower if using the server HotSpot (java -server).

It does not leak (?) and the memory footprint is worse than the built-in solution.

final class LazyVal[A](f: => A) {
  private[this] var _f = f _
  private[this] var _value = null.asInstanceOf[A]
  def value = {
    if(null != _f) synchronized {
      if(null != _f) {
        _value = _f()
        _f = null
      }
    }
    _value
  }
}

The private[this] things are needed so that field accesses (as compiled by scalac) do not go through methods, although I have noticed that HotSpot is doing a great job even without them.

Re: The Mysterious TreeMap Type Signature

Thursday, January 24th, 2008

[This is a comment on the recent post The Mysterious TreeMap Signature by D. Spinellis, also posted in his blog.]

Recently I had to delve into Java Generics quite deep, since I (as my search concluded) needed to use

public class Foo<t extends Foo<T>>

recursive constructs for a personal project (which by the way are fixed-point equations of the form x=f(x) !). The point is I had to read a lot (including Anglelika’s marvelous contribution) in order to understand what is going on beyond the overhyped and embarassingly simplistic for-each construct.

Unfortunately, it seems the JDK is full of compromises of the kind described in the post. I do not argue that compatibility is a bad issue. I am just concerned with what else will follow in the road to Java evolution, since I do not want to see this wonderful and very pragmatic language become lame.

About five years [correction: after thinking better about it, I believe it is more than six or seven years] ago, I envisioned a merging of the Functional and Object-oriented paradigms. This need had come out my experience in designing and programming. I had next-to-none experience with FOP, but it was too obviously appealing to my brain to ignore it… Today, I would like to experiment with scala a bit, time permitting…

ToString, circular references and Hibernate

Monday, November 19th, 2007

I have been writing some Hibernate code and in order to check what is going on with the mappings and the data they actually retrieve, all my domain objects implement org.ckkloverdos.string.IToStringAware of ckkl-core.

The actual domain model does not matter for this post, but let’s say that two of my classes are Person and Address and the association is such that a Person has one or more Addresses (under the hoods there are 3 tables, 2 for the entities and one join table). Also, an Address object has a reference to the Person it belongs to.

Here is a printout an Addresses list:

ArrayList[
  0=Address(
    name="Some address 1"
    person=null
    addressId=4)
  1=Address(
    name="Some address 2"
    person=null
    addressId=3)
  2=<REF:1>Address(
    name="The Master Address"
    person=Person$$EnhancerByCGLIB$$e8f89ce1(
      addresses=PersistentSet[0=<@REF:1>]
      name="The Master Person"
      personId=1)
    addressId=1)
...
]

So, actually, I can verify that I have one Person (”The Master Person”) to which one Address (”The Master Address”) belongs to. Notice how this Address lists its Person, which in turn has a circular reference to the particular Address.

Do not get confused by the domain object model. It actually does not matter. The idea here is that ToString can correctly report a circular reference in my object graph. It can also index those circular references in order of appearance, so that you will see <REF:1>, <REF:2> and so on, and of course the respective back-references <@REF:1>, <@REF:2> and so on.

<REF:n> marks a reference and <@REF:n> designates a circular (back) reference to the point where <REF:n> appeared. So, at the example above, we mark the particular Address having index 2 in the ArrayList because its object is also used in one of its properties, the Person.

One little bonus, as a side-effect of using the ToString mini-framework, is that I can see what Hibernate does under the hood, by noticing the name of the class

Person$$EnhancerByCGLIB$$e8f89ce1

Well, that’s nice!

Python attributes

Tuesday, November 13th, 2007

I found the recent post of my friend Vassilios Karakoidas about Python rather stimulating, in the sense that it was a good opportunity for me to remember a little python after a long while…

The basic class definition in the above-mentioned post is:

class k:
  i = "foo"
  def get(self):
    return k.i

and the discussion in the post goes about the strange character of that ‘i’ attribute. Let me clarify things a little by providing some facts:

  1. The ‘i’ is defined as a class attribute, meaning that all instances of the class see the same value for ‘i’.
  2. Outside the class definition, you can access ‘i’ by simply typing ‘k.i’ without the need to create a new instance, as in ‘k().i’.
  3. Python gives us the ability to create a new attribute for an existing instance on-the-fly, without having to define it in the class constructor.
  4. If, probably by mistake or (as in the above post) on purpose, and according to fact 3, you decide to create an instance attribute with the same name as the class attribute, then the two ones co-exist and you need to be more precise when trying to access each of them.

With the rules above in mind. let’s play a little:

We print the value of the class attribute ‘i’, directly from the class:

>>k.i
'foo'

We create two instances and try to access the class attribute ‘i’ on both of them:

>> a=k(); b=k(); a.i; b.i
'foo'
'foo'

This is normal behaviour, since the class attribute ‘i’ is visible to any instance of the class. Now the tricky part: What if we try to change the class attribute ‘i’ via one of the instances, let’s say ‘a’:

>>a.i = 'foobar'; a.i; b.i;
'foobar'
'foo'

Oops!!! what hase gone wrong? Did we or did we not change ‘i’? Well, matters are simple. According to fact 3, what we actually did was to create an instance attribute with same name ‘i’ for the instance ‘a’. This creation of course, doesnot propagate to instance ‘b’! Now, for instance ‘a’, the instance attribute ‘i’ shadows the class attribute ‘i’, which of course we have not changed and remains the same:

>> k.i
'foo'

According to fact 4, in order to be able to access both the class attribute and the instance attribute, we just need to be more precise:

>> a.__class__.i
'foo'
>> a.i
'foobar'

And, by the way, did you notice that Python lets you write more that one statement in a line?

Declarative programming with L

Monday, November 12th, 2007

One of the reasons I created org.ckkloverdos.collection.L, is to be able to adopt a more declarative style of programming, since this collection/array wrapper class makes it easy to do some functional-oriented programming.

The other day, I was playing around with the API of Package. At one point, I just wanted to see the loaded packages from my own ckkl-core library. The implementation, using L, is both simple and I believe elegant:

new L(Package.getPackages())
  .selectProperty("name")
  .filterStartsWith("org.ckkloverdos")
  .print();

What would be the alternative in plain-old-Java?

Package[] packages = Package.getPackages();
for(int i = 0; i < packages.length; i++)
{
  String name = packages[i].getName();
  if(name.startsWith("org.ckkloverdos"))
  {
    System.out.println(name);
  }
}

On Open Source Licenses [ckkl-core]

Thursday, October 18th, 2007

The other day, I started releasing my core Java development library, under the name ckkl-core, as an open source project. For that I had to decide on a license and so I asked for the opinions of friends and the open source community in Greece. Combining these with my own findings, here is a list with helpful URLs:

David Wheeler has prepared a nice slide depicting the relationship between several open source licenses. His opinion is that one should go for a GPL-compatible license.

The Software Freedom Law Center, suggest the way to Maintaining Permissive-Licensed Files in a GPL-Licensed Project.

This article (with a second part) explains how to pick an open source license.

You can also try the License Wizard. The first page user interface is a little awkward. Choose Yes, or go directly to the second page :-)

Also, take a look at this quick reference. I find of particular importance their comment:

The most common misunderstanding about software licences is that giving someone else a copy of your source code under a licence restricts what you are allowed to do with your source code. The truth is, if you write some code, and give it to someone else under the terms of Licence X, or publish it so that anyone may use it under the terms of Licence X, that this does not subject you to the terms of Licence X! You are the author of the code, and you hold the copyright, and giving someone permission to use the code does not restrict you to using the code in only the way that they are allowed to use it!

And, of course, you should read what GNU has to say.

By the way, I have chosen the Apache License Version 2.0 for ckkl-core which is:

a collection of Java classes developed for personal projects and research. Its implemented features include but are not limited to Java type handling with aliases and equality testing, easy discovery and accessors for JavaBeans properties, functional-oriented collections (list with map(), filter(), and others), and an API to support an easy toString() implementation even for the most complex cases.

Over the years I have developed a library of, let’s say, personal taste; a library which is my swiss army knife when looking into some new (research) idea. Something I use in order not to re-invent the wheel every time. The source code is currently heavily undocumented and I will be releasing new versions as soon as I can put it into some “eye-friendly” shape (javadocs included). I will do my best on that, time permitting. So, stay tuned !

On Handling Dependent Resources - The Ensure/Create/Test Pattern

Monday, July 16th, 2007

Recently, I had to restructure some resource handling code. The case that I had some resources A, B, C, … and each one depended on some other in order either to be created or to function properly. So I had to devise a way to handle the dependencies and make sure that whenever I used a resource, all its dependencies are met.

I will use a simplistic example to make things clearer. Let’s say we have resource A, which depends on resource B, which in turn depends on resource C. A is created using B and B is created using C. Our code always uses A directly, so we need to make sure that B and C have been created before using A.

My second approach to the solution is a lazy, bottom-up one. Before using A, I need to ensure that it is functioning correctly and of course lazily create it at some point. Also, I assume that we can always have some test functionality to make sure that A is “alive”. For example, for a DB connection we can always issue some test SQL statement (select 1 from dual is common among Oracle developers). In the previous statements, please notice my italics on the three notions: ensure, create, test. So here are my findings:

Client code that uses A:

ensure(A)
  ...do something with A...

The backbone routines:

def ensure(A):
  if A is null:
    create(A)
  test(A)

def create(A):
  dispose(A)
  ensure(B)
  B.create(A)

def test(A):
  ...

Notice that I am also using one more routine, namely dispose. Its role is to safely dispose a resource, meaning that it takes care that the resource is not null, it properly handles exceptions and so on. Of course, as you can understand, there are a lot more details for a production-ready code and the routines admit variations…Also, in the generic case, we may have a graph of dependencies…

This is how I came to the programming pattern, for which I just chose the name in the title. As I wrote above, this is my second approach. The first was a top-down one . But this will be given elsewhere.

Spring 2.0.1 and BEA WebLogic Server 9.2 Integration

Wednesday, May 9th, 2007

Spring brings the power of POJOs to BEA’s server

Spring 2.0.1 and BEA WebLogic Server 9.2 Integration by Andy Piper and Eric Hsiao, Rod Johnson, Chris Wall — WebLogic Server 9.2 provides a platform for enhanced management, ease-of-use and scalability of Java applications. The Spring Framework enables a simpler, POJO based, approach to Java EE development without sacrificing the power of the platform. This article describes the synergy of these two systems, and introduces the Spring on WebLogic kit.