Owner 1.0.3 what’s new? Part 1: variable expansion
0 Comments Published February 4th, 2013 in Java, OWNER APIIn the last blog post I introduced what is the OWNER API and how to use it.
Basically it is tiny library that helps reducing the Java code to read the configuration for your application from Java Properties files. You can find full documentation here. Version 1.0.0 was having the very basic features, and now I’m adding new things that may return useful without compromising its simplicity and compactness.
Yesterday I have released version 1.0.3 which includes some new features that I want to introduce in some short blog posts.
On this weekend I set up the continuous integration on CloudBees and I noticed that compiling with JDK 6 there was a compilation error, since I was using JDK 7, so I decided that the fix was worthing another release, so that if somebody is using JDK 6 won’t have any problem.
So, what’s new then?
First of all, the OWNER library is now available on Maven Central Repository, and this will ease the job of people willing to try it, since now it only requires few lines to configure your project to use it, and I tried to improve the documentation. Unfortunately, publishing the library on Maven Central Repository required me to buy an internet domain name and use it for the groupId of the library. This may have broken the backward compatibility if someone started to use this library. I apologize for that.
The first thing I want to point out, is something I always missed in Java Properties files. A “variable expansion” mechanism.
For example, imagine your application having a configuration file like this:
server.host=myhost.com
service.url=http://${server.host}/some/endpoint
application.path=${HOME}/myapp
application.data=${application.path}/data
application.logs=${application.path}/logs
With plain Java properties file, the job to replace the variables is left to you. With Owner API, you can create a Java interface to map the above configuration and have all the variables resolved:
public interface MyAppConfig extends Config {
@Key("server.host")
String host();
@Key("service.url")
URL serviceURL();
@Key("application.data")
File appData();
@Key("application.logs")
File appLogs();
}
// then use it with:
MyAppConfig cfg = ConfigFactory.create(MyAppConfig.class, System.getenv());
The System.getenv() is used to resolve the ${HOME} system environment variable. In the same way you can pass other properties files too, like System properties or any other class implementing java.util.Map, see ConfigFactory.create(). I called this technique “importing properties”, since you specify some Properties or Maps during the creation of the Config object.
More details can be found on the README file on github: variables expansion and importing properties.
I’ll write more about what’s new in the next blog post.
Introducing OWNER, a tiny framework for Java Properties files.
5 Comments Published December 27th, 2012 in Java, OWNER API, SoftwareI never liked to create “wrapper” classes for properties files. Do you know… those classes like:
public class MyAppConfig {
private static Properties p = ...;
public static String serverName() {
return p.getProperty("server.name");
}
public static int serverPort() {
return Integer.parseInt(p.getProperty("server.port"));
}
....
}
There’s nothing really bad about those classes. Only that they don’t do actually anything useful; plus, you need to keep things in sync with the properties file associated.
So, I always preferred to directly use Properties.getProperty() and pass a config properties to objects:
public class MyBusinessClass {
private final Properties conf;
public MyBusinessClass(..., Properties conf) {
this.conf = conf;
}
public void doSomething() {
String serverName = conf.getProperty("server.name");
int serverPort = Integer.parseInt(conf.getProperty("server.port"));
}
}
99% of the times, you need a configuration setting in a single point. So that’s good enough, and I don’t have to write (and keep in sync) a class that I can spare.
But… what about this?
public interface MyAppConfig extends Config {
@DefaultValue("foobar.com")
@Key("server.name");
String serverName();
@DefaultValue("80");
@Key("server.port");
int serverPort();
...
}
Add to this, a smart -annotation based- configuration loading:
@Sources({"file:~/.myapp.config", "file:/etc/myapp.config", "classpath:foo/bar/baz.properties"})
public interface MyAppConfig extends Config {
...
And a simple instantiation:
MyAppConfig conf = ConfigFactory.create(MyAppConfig.class);
And you have OWNER. A little configuration framework based on Java properties.
BSD license.
Credits to Google GWT, that does similar things with i18n.
Ssh “Write failed: Broken pipe”
0 Comments Published November 17th, 2012 in Errors, Linux, OSX, Unix
I started to get this error “Write failed: Broken pipe” when I was leaving the terminal alone.
Since plumbers are still expensive, despite the crisis, I decided to fix the pipe by myself.
Very easy, just add the following line to /etc/ssh/sshd_config:
ClientAliveInterval 60
This will send a “keep-alive” packet from the server to the terminal client every 60 seconds so that the connection doesn’t get dropped.
If you can’t fix it on the server, for example if you don’t have administrative rights, you can fix your client to send the “keep-alive” packet to the server every 60 seconds, adding this line to ~/.ssh/config
ServerAliveInterval 60
It’s also possible to specify the ServerAliveInterval at the ssh command line:
$ ssh -o ServerAliveInterval=60 user@sshserver
More info about ClientAliveInterval and ServerAliveInterval can be found typing at the command line:
$ man 5 sshd_config $ man 5 ssh_config $ man ssh
Another reference here.
Your pipes should be safe now, and the plumbers out of business.
Today I updated mac ports and a new error started to show up at the command line saying that the __git_ps1 command is not found.
This is because I added the git branch in my bash prompt long time back and in last update of git-core port they moved the __git_ps1 bash functions to a separate script.
To fix it, you just need to include following lines in your .profile (or .bashrc):
if [ -f /opt/local/share/doc/git-core/contrib/completion/git-prompt.sh ]; then
. /opt/local/share/doc/git-core/contrib/completion/git-prompt.sh
fi
It worked for me.
Depending on your git installation, this file may be located elsewhere; find command should help in this case.
Update 30-03-2013:
They changed the location of those files again. Super!
now they are here:
/opt/local/share/git-core/contrib/completion/git-completion.bash /opt/local//share/git-core/contrib/completion/git-prompt.sh
just include them.
Hope they won’t change the paths again soon :)
It’s a couple of days I’m experiencing my macbook pro being more unstable (than usual). This morning I noticed that the cpu temperature was around 80˚C (using iStat Menus) and I notice that the process coreserviced was taking 80% CPU, and after that there was pentabletdriver with another 20%. I thought that it was a funny coincidence that this started to happen right after the release of Mountain Lion, so I thought that this may be the chance to upgrade, even though I can’t find a single feature in Mountain Lion that I really need.
First, I tried the oldest and most effective strategy to solve computer problems, the reboot, but it didn’t help.
So, I googled around and I found many people complaining the same behavior, but nothing to solve the problem in my case.
At the end I did this: from spotlight I opened the Activity Monitor and I forced-quit the coreserviced and the pentabletdriver, and immediately the cpu returned idle, but after that the menu bar disappeared so I thought it would be a good idea to shutdown the laptop and reboot (CTRL+Eject button). After the reboot, things went fine, but I had already purchased Mountain Lion, so… good for you Apple, you got my 15 euros.
How to switch the primary display on OS X
1 Comment Published July 9th, 2012 in Apple, Hardware, OSXI purchased an awesome 24″ LCD Monitor by Asus, I didn’t spend much (except for the Apple Mini DisplayPort to HDMI cable). The problem with OS X, is that once you have such a wonderful display you want to use it fully, and the Apple operating system works against you. In fact, by default the monitor enters as “secondary monitor” so you need to drag applications into it, and you don’t have the dock and the menubar there. This would be fine, if only the way to switch the primary monitor was easy to find.
I wanted to use the big monitor as primary monitor, and I couldn’t find how. I looked around on internet without any luck. I purchased an application, Multimon, from the App Store, but it wasn’t much of an help; $10 wasted.
At the end I found how to use the external monitor as Primary Display. Here it is how:
- Open ‘System Preferences’. I do that from spotlight (cmd+space then type ‘system preferences’)
- Choose Displays, and select the Tab ‘Arrangement’, you’ll see something like this:
- You see that the menu bar is set on the little display (the one of the MacBook). The menu bar also identifies the ‘Primary Display’, which also gets the Dock. All you need to do, to switch the primary display is to drag the menu bar on the other display. It is also written in the dialog, but who see that? After dragging the menu bar, the representation becomes like this:

Now the primary monitor is the external one.
When the external monitor gets disconnected, the MacBook display returns to be the primary one. If you have much stuff on the desktop, it gets a little bit messed up, but you can rearrange that automatically, right-clicking on the desktop and doing a Clean-Up By Kind or by Name.
Notice that if you have a MacBook earlier than 2010, like me, the Mini DisplayPort doesn’t transport the audio signal, which has been added only later; so your external display will be mute.
Last advice: once you have a big external monitor, you’ll probably want to buy a Apple Wireless Keyboard and the Magic Trackpad. Both strongly recommended. (For the Apple guys: for this recommendation you owe me some gift!)
This would be the final result [1]:

Notes:
- Beer not included.
I always found Dashboard pretty useless, and I just notice it exists when by mistake I press some key which switches the desktop to it. So, here is how to get rid of it; I write this post mainly for future memory for myself.
From this article:
$ defaults write com.apple.dashboard mcx-disabled -boolean YES $ killall Dock
to re-enable it:
$ defaults write com.apple.dashboard mcx-disabled -boolean NO
Less is more.
How to query HTTP:BL for spamming IP addresses
1 Comment Published April 18th, 2012 in Internet, Java, Software, WebIf you don’t know Project Honey Pot, go and have a look.
They offer a service for querying IP addresses and check if they are listed in those involving in spamming or threatening activities. So, if your visitor has a black listed IP you can block him from accessing or doing something sensitive.
Since it is missing a Java library to use the service, I implemented a Spike following the HTTP:BL API specifications.
This is not production code, is just some (ugly) code I wrote to test how it works.
import static java.lang.Integer.parseInt;
import static java.lang.System.out;
import java.net.InetAddress;
import java.net.UnknownHostException;
// see: http://www.projecthoneypot.org/httpbl_api.php
public class HttpBlackListChecker {
public static void main(String[] args) throws Exception {
if (args.length == 0) help();
String ip = args[0];
out.println("Querying HTTP:BL for IP: " + ip);
String reversed = reversed(ip);
// get your own key at http://www.projecthoneypot.org/httpbl_configure.php
String accessKey = "abcdefghijkl";
String domain = "dnsbl.httpbl.org";
String lookup = accessKey + "." + reversed + "." + domain;
out.println("Lookup for: "+ lookup);
try {
String addr = InetAddress.getByName(lookup).getHostAddress();
translate(addr);
} catch (UnknownHostException e) {
out.println("The IP specified is not listed in HTTP:BL");
}
}
private static void help() {
out.println("Please specify an ip address to check");
System.exit(1);
}
private static void translate(String addr) {
String[] split = split(addr);
out.println("Response Code: " + addr);
out.println("Result: " + (split[0].equals("127") ? "found" : "error"));
out.println("Days since last activity: " + split[1]);
out.println("Treat score (0..255): " + split[2]);
out.print("Type of visitor: ");
int type = parseInt(split[3]);
switch (type) {
case 0:
out.println("Search Engine");
break;
case 1:
out.println("Suspicious");
break;
case 2:
out.println("Harvester");
break;
case 3:
out.println("Suspicious & Harvester");
break;
case 4:
out.println("Comment Spammer");
break;
case 5:
out.println("Suspicious & Comment Spammer");
break;
case 6:
out.println("Harvester & Comment Spammer");
break;
case 7:
out.println("Suspicious & Harvester & Comment Spammer");
break;
default:
out.println("Unknown");
break;
}
}
private static String reversed(String ip) {
String[] split = split(ip);
String reversed = null;
for (String chunk : split)
reversed = (reversed == null) ?
chunk :
chunk + "." + reversed;
return reversed;
}
private static String[] split(String ip) {
return ip.split("\\.");
}
}
This code won’t work if you don’t request an API key from here and replace it at line #16.
Sample output specifying one spamming IP (91.207.8.78):
Querying HTTP:BL for IP: 91.207.8.78 Lookup for: abcdefghijkl.78.8.207.91.dnsbl.httpbl.org Response Code: 127.1.61.5 Result: found Days since last activity: 1 Treat score (0..255): 61 Type of visitor: Suspicious & Comment Spammer
Notice that some ISP DNS server redirect to a “courtesy page” of the ISP itself, when you specify a non-existent host. In this case you’ll get some wrong repose code when the IP is not listed. You’ll see “Result: error” in the output, instead of “The IP specified is not listed in HTTP:BL”. The fault in this case if of your ISP.
I personally always felt bad about the fact that we have to provide a shell script which runs the executable jar file. It would be nice if we could provide a self contained executable in a single file, right?
I just discovered a trick which works on unix, but it can possibly be adapted on Windows.
Ingredients:
- a jar
- a bash script
Let’s start with the jar. Create an HelloWorld.java file:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
I like to indicate the Main Class in the manifest, so we create a MANIFEST.MF:
$ echo Main-Class: HelloWorld > MANIFEST.MF
now, let’s put the jar together:
$ javac HelloWorld.java $ jar -cvmf MANIFEST.MF hello.jar HelloWorld.class
You can try it:
$ java -jar hello.jar
It should print “Hello World!”. No surprise.
Now, let’s create, once and for all, the bash script “stub.sh”
#!/bin/sh java -jar $0 $* exit
Now let’s put together our self-executable java program:
$ cat stub.sh hello.jar > hello.sh $ chmod +x hello.sh
And now we can run it!
$ ./hello.sh Hello World!
Cool uh?
I think, you can create a stub.bat on Windows; possibly you should just replace the first line with “@echo off” and the “$0 $*” with “%0 %1 %2 %3 %4 %5…”. It should work. Don’t ask me to test the Windows version. I’m allergic.
Update:
A shorter version of the stub script:
#!/usr/bin/java -jar
For windows, this should translate to stub.bat:
@java -jar %0 %1 %2 %3 %4 %5 exit
For windows, depending on what you use to concatenate files (copy /b should work) make sure there is a newline between the end of the stub.bat and the beginning of the jar file. I didn’t test on Windows, but I’m pretty sure it will work. Let me know, if otherwise.
OSX, Internet Sharing interfere with the standby sleep on MacBook Pro
1 Comment Published April 16th, 2012 in Apple, Errors, Hardware, Internet, Opinions, OSX, SoftwareYesterday I noticed that when I close the lid of my MacBook Pro the light in front of the case was not indicating that the computer was going to sleep normally. Still the fans were running and when I opened the lid, I saw that it was not resuming from sleep properly, presenting a strange behavior: it asks for a password for a second or so, then the screen goes black again, and I need to turn it on manually pressing the light buttons (fn+F1/F2) then the screen appears again.
I debugged the problem and I discovered the cause.
The cause is that I enabled “Internet Sharing” from the “Sharing” item in the “System Preferences”. Basically I am sharing the WIFI internet to set of devices connected to the Ethernet.
If the WIFI is enabled (and connected) and the Internet Sharing is enabled, my MacBook hangs while doing the sleep process.
After resetting the SMC and trying several times to close all possible apps which may interfere, I finally found that the Internet Sharing is affecting this behavior.
Another workaround I found is to disable the WIFI. In this way the “Internet Sharing” is also disabled and the problem doesn’t happen anymore.
I reported the bug to Apple, and I hope they will have a look and try to solve it. To me, it is obviously a BUG in the Internet Sharing feature, which by the way it’s superb.
Search
About

"Thoughts about technology, code, life and diverse and occasionally related matters"
A blog by Luigi R. Viggiano
Follow me
Archives
Categories
- Android (3)
- Apple (29)
- Books (7)
- Eclipse (14)
- Errors (5)
- Firefox (7)
- Git (3)
- Hardware (18)
- Horror Code (8)
- Internet (21)
- Java (104)
- JavaScript (9)
- Life, universe and everything (45)
- Lifehacks (26)
- Linux (52)
- Opinions (26)
- OSX (11)
- OWNER API (2)
- Python (1)
- Software (33)
- Speeches and Conferences (8)
- Unix (5)
- Web (23)
- Windows (19)
Tag Cloud
Android apple architecture Bash configuration CSS Development Düsseldorf Eclipse Git Google Hardware hdr How-To howto Java JAXB job Karmic Linux lion MacBook music Open Source Opinion OSX os x patterns Pitfalls Practices Resume Security Software Suspend TDD Testing tip tonemapped Tricks Ubuntu unix video Web Workaround XML
WP Cumulus Flash tag cloud by Roy Tanck and Luke Morton requires Flash Player 9 or better.
Blog License
Blogs I like
Books on the desk
Friends' Blogs
- Antonio Terreno & Valter Bernardini
- Bruno Bossola
- Daniele Galluccio
- Domenico Ventura
- Ed Schepis
- Fabrizio Gianneschi
- Luca Grulla
- Luigi Zanderighi
- Marcello Teodori
- Mida Boghetich
- Muralidharan Chandrasekaran
- Piero Ricca
- Renzo Borgatti
- Simone Bordet
- Simone Bruno
- Uberto Barbini
- Valvolog
- Webtide blogs (Greg Wilkins & Jan Bartel)
Links


















