Above, Below, and Beyond Tech Talk

by Rahel Lüthy

May 13, 2015

Java 8 Unsigned Int

When I recently profiled one of our applications, it turned out that a lot of memory was wasted on a huge number of long primitives. They were used to represent IDs, which were originating from a 3rd party text file. Someone must have loved huge numbers, so they chose an ID format that didn’t fit into an int.

Well, while being huge, the IDs were at least always positive. So I was confident that some data massage would allow me to squeeze them into primitive int values eventually. It took me by surprise that Java 8 actually supports unsigned primitives out of the box. Guess we all missed that while wrapping our heads around lambdas and streams, right?

Here’s how it works:

public class UnsignedIntTest {

    @Test
    public void roundTrip() {

        // compile error: 2^32 - 1 is too large for an int
        // int intValue = 4294967295;

        long longValue = (long) Math.pow(2, 32) - 1;
        String longValueAsString = String.valueOf(longValue);

        int unsignedInt = Integer.parseUnsignedInt(longValueAsString);

        long result = Integer.toUnsignedLong(unsignedInt);

        assertEquals(longValue, result);

    }

}

March 22, 2015

JavaFX 3D Line

I have no experience in 3D programming whatsoever. Last week, I took my first steps in JavaFX 3D, but hit a wall when I wanted to draw a line between two points: There is no Line shape! The only out-of-the-box Shape3D classes are Box, Cylinder, Sphere, and MeshView – wow…

Well, it shouldn’t be too difficult to connect the points with a slender cylinder, right?

I was wrong, it took me an embarrassingly long time to get the trigonometry right :-)

Here’s my magic crutch:

public Cylinder createConnection(Point3D origin, Point3D target) {
    Point3D yAxis = new Point3D(0, 1, 0);
    Point3D diff = target.subtract(origin);
    double height = diff.magnitude();

    Point3D mid = target.midpoint(origin);
    Translate moveToMidpoint = new Translate(mid.getX(), mid.getY(), mid.getZ());

    Point3D axisOfRotation = diff.crossProduct(yAxis);
    double angle = Math.acos(diff.normalize().dotProduct(yAxis));
    Rotate rotateAroundCenter = new Rotate(-Math.toDegrees(angle), axisOfRotation);

    Cylinder line = new Cylinder(1, height);

    line.getTransforms().addAll(moveToMidpoint, rotateAroundCenter);

    return line;
}

To illustrate what’s going on, I created a 2D representation of all individual steps, starting off with the creation of the cylinder. By default, its center is placed at the origin:

The moveToMidpoint transformation moves its center to the final location (the yellow midpoint in the above image):

And finally, the rotateAroundCenter transformation corrects the cylinder’s direction:

Obviously, the tricky part is finding the proper axis and angle of rotation. Both are calculated relative to the yAxis because of the cylinder’s initial direction. The axisOfRotation must be perpendicular to the plane defined by the yAxis and the diff vector. To find such a perpendicular vector, we can (by definition) calculate the cross product of the two vectors. In the 2D case, the result is equivalent to the z-axis, but in 3D it may be tilted.

The angle is calculated based on the dot product (aka scalar product) of the two vectors, which is defined by

A • B = |A| |B| cos(alpha)

If A and B are both unit vectors, this becomes

A • B = cos(alpha)

which we can resolve to

alpha = acos(A • B)

That’s it!


February 27, 2015

Scala Gems #9: Regex Extractors

Suppose you have a simple date string: "2015-02-27"

Regular expressions allow to parse the date and extract parts thereof[^1]: (\d\d\d\d)-(\d\d)-(\d\d) defines a pattern which matches the digits and defines capturing groups for the year, month, and day parts.

In Java, a simple example usage would look like this:

Pattern pattern = Pattern.compile("(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)");
Matcher matcher = pattern.matcher("2015-02-27");
while (matcher.find()) {
    System.out.println("Year: " + matcher.group(1));
    System.out.println("Month: " + matcher.group(2));
    System.out.println("Day: " + matcher.group(3));
}

Accessing the groups by index is rather awkward and error prone. Luckily, Java 7 introduced support for named groups:

Pattern pattern = Pattern.compile("(?<year>\\d\\d\\d\\d)-(?<month>\\d\\d)-(?<day>\\d\\d)");
Matcher matcher = pattern.matcher("2015-02-27");
while (matcher.find()) {
    System.out.println("Year: " + matcher.group("year"));
    System.out.println("Month: " + matcher.group("month"));
    System.out.println("Day: " + matcher.group("day"));
}

That’s better, but I personally don’t like how the group names pollute the pattern. Regular expressions are hard to read already, the Java escape characters add yet more clutter, and the additional ?<group> constructs are a kiss of death.

Let’s look at how the same problem can be tackled in Scala:

According to the docs, the canonical way to create a Regex is by using the method r, which is provided implicitly for strings:

val Date = """(\d\d\d\d)-(\d\d)-(\d\d)""".r

Note the triple quotes, which allow to use the backslashes without further escaping. While this is nice, the true advantage of Scala is that regular expressions can be used as extractors in a pattern match. The pattern stays plain and simple, and yet we have all the freedom to name groups as we please:

"2015-02-27" match {
  case Date(year, month, day) =>
    println(s"Year: $year")
    println(s"Month: $month")
    println(s"Day: $day")
}

Look ma, no clutter! [^1]:Yes, using java.time.format.DateTimeFormatter would be easier in this simple case.


Older Posts » Archive