What’s the fuss with Java 8 Optional?

I’ve been asked several times lately by colleagues what the Optional<T> is good for, so today some more basic stuff.

You can use the Optional class is as an elaborate null check like

  Optional<String> optionalString = Optional.ofNullable(someString);
  if(optionalString.isPresent()) {
    String string = optionalString.get();
  }
 
  // Or worse
  // String string = optionalString.orElse(null);
  // null check here

but most of the time, a computed value based on a possible null input value is much more interesting. Here comes map and flatMap.

If the optional value is present, map is used to compute a new value (which is turned into an optional), flatMap has the same purpose but is meant for computations that already return an Optional, otherwise you would end up with an Optional<Optional<T>>:

// Compute the length of a string which could be null
int length = Optional.ofNullable(someString).map(String::length).orElse(0); // Which value is used as default is surely debatable

Here’s a real world example from biking. Spring framework supports Optional request parameters and path variables since 4.1, so i can write a controller method that takes two optional range variables (start and end) like this:

I can use these two parameters to filter a map containing LocalDates as keys without null checks like so:

bikes
    // Stream the bikes 
    .stream()
    // and flatMap (concat) their periods into a new stream
    .flatMap(bike -> bike.getPeriods().entrySet().stream())
    // we're only interested in periods before 1.1 of the current year
    .filter(entry -> entry.getKey().isBefore(january1st))
    .filter(entry -> {
	final int year = entry.getKey().getYear();	    		
        // No need for null checks, the optional parameters are mapped to booleans
        // if the values are present, check if the current year is after start respectivly before end
        // otherwise the interval is open and i can map them to true
	return yearStart.map(v -> v <= year).orElse(true) && yearEnd.map(v -> year < v).orElse(true);
 
        // Using possible null values the the filter would look like
        // (yearStart == null || (yearStart <= year)) && (yearEnd == null || (year > yearEnd))
    })

Now, it’s actually debatable which expression brings the intention more clearly, but i like the fact that i just can use the parameters as is.

Another interesting Optional method is filter. It takes a predicate and turns a non-empty optional into an empty optional if the predicate doesn’t match. I use it for example for an “default if blank string method”:

/**
 * Returns {@code defaultValue} when {@code value} is empty or blank.
 * 
 * @param value A string
 * @param defaultValue A default value when the input string is empty.
 * @return value or defaultValue
 */
public static String defaultIfBlank(final String value, final String defaultValue) {
    return Optional.ofNullable(value).filter(Strings::isNotEmpty).orElse(defaultValue);
}
 
/**
 * @param value Value to be checked if empty
 * @return True if trimmed value is not empty
 */
public static boolean isNotEmpty(final String value) {
    return !value.trim().isEmpty();
}

Do you have interesting use cases for Java 8s Optional?

| Comments (2) »

15-Apr-15


Destroying what you love to do…

This is probably gonna be an exceptional personal post.

I love coding. I live and breath this. My mind is a bastard, it seldom sits down and does nothing. There are endless possibilities out there, coming to it through my wonderful timeline, blogs, reddit and more. New technologies i want to learn, new things i want to try out. I often have this feeling that Fabian pointed out:

Also, isn’t it cool, getting up as early as possible with lots of ☕️☕️☕️ and pulling all-nighters, either private or at work? I mean, all the rock stars are doing it.

Lately i’ve found myself in the weird position of being Prokurist in a small company doing many other things than coding and at the same time drowning in stuff that just “needs to be done” because no one else cares or is able to do, or tasks which are merely a draft on a whiteboard (if any).

Then there’s is this thing: I’m turning 36 this year and more and more, I’m feeling like having a bad midlife crisis since about last year which i don’t want to smother by buying stuff or pouring alcohol down my throat. I’m struggling to put myself in a position where i have the feeling to stay relevant in geezer town.

And first and foremost, I am a father of two great kids. I don’t want to be one of those parents who barely sees their kids. I’m so happy and proud that we have a great relationship and i want it to stay that way.

I got this email recently from a person i only met years ago on the internet, telling me how impressed he is with the stuff i’ve achieved and how he is wondering from where “persons like me” (whatever that is) take the strength to manage all this.

Honestly, i don’t know. When i’m with my family or creating stuff for dailyfratze.de or the various parts of my biking project i feel great. I also feel great doing housekeeping with my wife or dull work at work, but more often than not, at the times where there isn’t stuff to do, there’s no rest for me. Feeling physically and psychically exhausted, my brain keeps wandering.

Often those professional achievements are not a result of too much strength but from an imposter syndrome. The mere facts should and do tell me that i am good at what i’m doing, but even at the age of nearly 40 i have a hard time believing it and one of the ways i’ve “learned” to prove this to myself is just being better, learn more, do more.

So, why this posts title? I need to reduce the amount of coding that leaks into my life. Dramatically. I want the weekends to feel like weekends again, not just like any other week day. The most effective (and probably also the most efficient) way for me to stay relevant is doing less, not more. Do i want to define myself as an overworked coder, pouring coffee (or what ever else legal drug is available) or do i want to be a father of a family and software craftsman doing the right stuff?

My twitter bio says “Father of two, Husband, Geek, Programmer, Biker.” for about 2 years now. It’s about time to order those priorities in real life that way again.

How do you set your priorities? Which persona do you want to be? Is your online persona much different than your real life self? Really, i’d love to hear from any of you.

| Comments (4) »

14-Apr-15


JavaLand 2015 result: JavaFX 3d mosaic for dailyfratze.de

JavaLand 2015 resulted in a sweet little toy project for me (See my little reviews of the conference itself here: 24.3, 25.3 and 26.3, JavaLand 2015 was one of the best conferences i attend. Lots of fun, lots of good talking, i really enjoyed it).
Wolf Nkole Helzle had this My-Matrix project going on there and i thought, well, this year i’m doing Daily Fratze for ten years and i alone will have 3650 pictures of myself uploaded to the internet by August and in sum there are over 50.000 images right now, that should be a pretty good idea, creating an interactive mosaic as well (Adastra has already created a beautiful mosaic on her 8th anniverary).

As i don’t want to share the images anywhere else but only in my own daily picture project i had the opportunity to learn some more stuff which you can find here.

The basic idea for this mosaic generator is: Create an accurate color matching algorithm as readible as possible. Lukas Eder had this nice article on dzone why It’s Okay to Stick With SQL and i wanted to see how far can i get with SQL for my goal.

This project includes:

  • Flyway for creating and migrating databases (i didn’t want to run sql-scripts myself)
  • Flyway and jOOQ maven integration for effortless generating dao code at compile time
  • jOOQ in common for all database access
  • An CIE94 color distance algorithm
  • JavaFX 3d for creating a spherical image wall. Kudos and thanks to José Pereda for inviting me and giving me a real great introduction not only to his cool JavaFX presentation tool (which gives live coding a whole new dimension), but also to JavaFX 3D. Next time i try to be not that shy, but was too impressed by this massive Java knowledge all around me.

Also personal thanks to mentioned Lukas Eder, maybe you didn’t notice but you encouraged me a lot in what I am doing at the moment.

You’ll finde the complete source code for this project at github:

dfx-mosaic @ github.

So, how far did i come? Far! First have a look at the JavaFX application, selecting the tiles and rendering them on an image wall and me exploring the scene:

Mosaic generation is done in two steps: Create a database of images including their average color (Average color defined by the arithmetical average of all rgb values in an image). You gotta love Java 8s stream for how simple such things have become:

And then (for example):

Those list of images records: Just put them in a SQL database. I choose H2 for simplicity and i’ve gotta say, Flyway and jOOQ are really a dream time. I used this tutorial and had my Records and DAOs in no time.

I like jOOQs batch api, way easier then to this by hand:

create.batchInsert(records).execute();

Writing the CIE94 color distance was the hard part, making it usable inside an H2 database is really easy:

create.execute("create alias if not exists f_CIE94_color_distance deterministic for \"de.dailyfratze.mosaic.images.CIE94ColorDistance.compute\"");

I’d prefer having this done also in migration, but the referenced method must be defined at runtime, so no chance here.

The basic idea for my mosaic algorithm is selecting the source image with the least color distance which has not been used in box of 10 by 10 tiles. I could have come up with a more performant algorithm but that would have been as easy as just iterating the tiles of the target image and just selecting it (the variable tiles contains all selected tiles so far):

SQL checked by the compiler, correct in statement, calling stored procedures. All there, readable and really easy to use.

The JavaFX 3d application is nearly identical to the VideoWall on Stack Overflow but serves me well for further experiments.

I plan to arrange the images by year on the z-axis (done, see below), create some dialogs for choosing creating and choosing libraries, settings for tile size and such. If i should have to much time on my hand, i’d love to see touch support, a Raspberry Pie and a touch screen for doing some kind of installment on my 10th anniversary of daily self portraits.

I’ve also included a little terminal application which just writes mosaics to file, the result looking like so:

2014-10-03_mosaic

Compare to the original (taken at Mavericks beach on my trip to JavaOne 2014):

2014-10-03_original

And a screenshot from the JavaFX app with the images spread by year on the z-axis:

mosaic_3d

| Comments (0) »

31-Mar-15


Spring: Provide Interoperability between JMS and Springs simple WebSocket messaging

Nearly 2 years ago, excellent WebSocket Support appeared in Spring 4, easily usable using STOMP over Websockets / SockJS on the client side, backed by a pluggable broker on the server side, which can either be simple broker using scheduled executor services to handle message or a full fledged RabbitMQ or ActiveMQ solution.

Using

@EnableWebSocketMessageBroker

enables the first solution without much fuss, integrating an existing and running ActiveMQ STOMP transport is nearly as easy:

@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
    registry.enableStompBrokerRelay("/topic")
	.setRelayPort(1234)
	.setClientLogin("client-user")
	.setClientPasscode("client-password")
	.setSystemLogin("sys-user")
	.setSystemPasscode("sys-password");
    registry.setApplicationDestinationPrefixes("/app");
}

I’ve already used (and i am using) such a solution in this application, as described here. What you’re doing is not instantiating your own scheduler and transport, but relaying everything to the existing transport which is nice when you don’t want to was resources.

What’s missing here, is some deeper integration.

Using Springs JmsTemplate it’s really easy to send JMS messages and it’s also easy to connect simple beans or services through messages:

Imagine an arbitrary service, not knowing anything about jms:

class SomeCmd {
}
 
public class SomeService {
  public void someVoidMethod(final SomeCmd someCmd) {
    System.out.println("Something incredible");
  }
}

Connecting this to a queue is as easy as:

import javax.jms.ConnectionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.listener.SimpleMessageListenerContainer;
import org.springframework.jms.listener.adapter.MessageListenerAdapter;
 
@Configuration
class Config {
 
  @Bean
  public SimpleMessageListenerContainer someServiceContainer(final SomeService someService, final ConnectionFactory connectionFactory) {
 
    // Create an adapter for some service
    final MessageListenerAdapter messageListener = new MessageListenerAdapter(someService);
    // Connect the method 
    messageListener.setDefaultListenerMethod("someVoidMethod");
    // to a queue	
    final SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
    container.setDestinationName("some.queue");
    container.setMessageListener(messageListener);
    container.setConnectionFactory(connectionFactory);
 
    return container;
  }
}

Sending messages is a onliner:

jmsTemplate.convertAndSend("some.queue", new SomeCmd());

If that method isn’t a void method, the result can automatically be passed to another queue:

class SomeCmd {
}
 
class SomeResult {    
}
 
public class SomeService {
  public SomeResult someNonVoidMethod(final SomeCmd someCmd) {
    return new SomeResult();
  }
}
 
// Change in the config
messageListener.setDefaultListenerMethod("someNonVoidMethod");
 
// And added to the config:
messageListener.setDefaultResponseQueueName("some.response.queue");

What if i want to have the result right available on a web site using WebSockets and STOMP? Although the name sounds similar, the SimpMessagingTemplate has nothing todo with the JmsTemplate, at least not immediately.

As it turns out, it’s relatively simple redirecting the output of bean to the STOMP queue, knowing

Note that the prefix in stomp /queue/ or /topic/ is removed from the string before passing it to ActiveMQ as a JMS destination. Also note that the default separator in MOM systems is . (DOT). So FOO.BAR is the normal syntax of a MOM queue – the Stomp equivalent would be /queue/FOO.BAR

Working with Destinations with Stomp

In the above example

messageListener.setDefaultResponseQueueName("some.response.queue");
// becomes
messageListener.setDefaultResponseTopicName("some/response/topic");

Which means: Everything SomeService#someNonVoidMethod returns is send to a STOMP topic call /topic/some/response/topic.

Nice. But it turns out, SimpMessagingTemplate converts the messages body to a nice, readable JSON format, internally proceeded by Jacksons Object Mapper. Without a custom converter, we’ll end up with a MapMessage. To make the outcome of the topic the same, regardless wether produced using SimpMessagingTemplate or redirecting the outcome from a JMS queue, we need a converter. If you’re using ActiveMQ like i you can use a “Message transformations”, but that has some drawbacks: The connection needs to be opened with a special header and what is worse, the Json generation is based on Jettison (which i cannot link anymore because the Codehause page stopped working) which is basically impossible to customize.

So instead, i assume there are ObjectMessages entering my queue (send through JmsTemplate to reach my service) and outgoing stuff should be in form of TextMessages. With that assumption, just use a slightly adapted MappingJackson2MessageConverter:

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.listener.SimpleMessageListenerContainer;
import org.springframework.jms.listener.adapter.MessageListenerAdapter;
import org.springframework.jms.support.converter.MappingJackson2MessageConverter;
import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.MessageType;
 
@Configuration
class Config {
 
  @Bean
  public SimpleMessageListenerContainer someServiceContainer(final SomeService someService, final ConnectionFactory connectionFactory) {
 
  	// Create an adapter for some service
  	final MessageListenerAdapter messageListener = new MessageListenerAdapter(someService);
  	// Connect the method [1]
  	messageListener.setDefaultListenerMethod("someNonVoidMethod");
 
  	// Direct every outcome of "someNonVoidMethod" to a topic, that is 
  	// subscribable via  stompClient.subscribe('/topic/some/response/topic', {});
  	messageListener.setDefaultResponseTopicName("some/response/topic");
  	// and take care of converting someResult to a JSON payload, otherwise we'll end up with a 
  	final MappingJackson2MessageConverter messageConverter = new MappingJackson2MessageConverter() {
  	  @Override
  	  public Object fromMessage(Message message) throws JMSException, MessageConversionException {
  		  return message instanceof ObjectMessage ? ((ObjectMessage) message).getObject() : super.fromMessage(message);
  	  }
 
  	  @Override
  	  protected TextMessage mapToTextMessage(Object object, Session session, ObjectMapper objectMapper) throws JMSException, IOException {
  		  final TextMessage rv = super.mapToTextMessage(object, session, objectMapper);
  		  rv.setStringProperty("content-type", "application/json;charset=UTF-8");
  		  return rv;
  	  }
  	};
  	messageConverter.setTargetType(MessageType.TEXT);
 
  	// [2] to a queue	
  	final SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
  	container.setDestinationName("some.queue");
  	container.setMessageListener(messageListener);
  	container.setConnectionFactory(connectionFactory);
 
  	return container;
  }
}

This creates a configuration for creating a JMS Message Queue who’s outcome is send to a topic in the same format as Springs SimpMessagingTemplate would create, allowing to send messages to an arbitrary service whose return values are in turn passed (among others) to listeners on a WebSocket. This prevents manually connecting return values from a service to SimpMessagingTemplate, for example by injecting SimpMessagingTemplate into the service and manually calling convert and send. The service can therefore be a simple bean, not knowing anything about Spring, Jms, STOMP or Websockets.

| Comments (1) »

03-Mar-15


ALT+Click all the things

Here’s a list of things you can ALT+Click (Option key ⌥ + left mouse button) in Mac OS X:

  • ALT+Click on the WiFi icon in the menubar gives you detailed information about your selected WiFi network
  • ALT+Click on the volume icon in the menubar lets you quickly select audio input and output device
  • ALT+Click on any of the triangles on a tree-ish view (Finder in listmode, IDEs etc.) expands or collapses all subitems
  • If you have multiple Time Machine volumes attached, ALT+Click on the Time Machine icon in the menubar lets you browse other Backups than the default with that spacy interface
  • ALT+Click on the BlueTooth icon shows some information about your device id
  • ALT+Click on the battery icon shows the health of your laptops battery
  • ALT+Click on the maximize icon in the title bar restores the old behavior of Mac OS X to maximize the window to the desktop and not going fullscreen
  • ALT+Click on the notification icon in the menubar toggles “Do not disturb” mode for notifications
  • ALT+Shift+Volume keys changes the volume in ¼ increments or decrements
  • ALT+Shift+Brightness keys changes the brightness in ¼ increments or decrements
  • ALT+Click on the (green) fullscreen button in the title bar of application windows maximizes them “the old way”, that is: maximum size on the screen, not fullscreen. Same effect as double click on the title bar
  • ALT+Click on the Dropbox icon changes the (new) graphical version to the list version showing usage, available space and more (Thanks, Mario)

If you know more, please leave a comment because:

56833531

| Comments (3) »

05-Dec-14