Friday, May 15, 2015

Mark IV Special Coffee Maker API implementation

In his book "UML for Java Programmers", Robert C. Martin (from Object Mentor) explains an object oriented software design problem: Writing an implementation of the software for the fictional Mark IV Special Coffee Maker. The solution must use the low-level API of the hardware that controls the different parts of the machine, which is provided as the CoffeeMakerAPI Java interface. Robert also published the complete Mark IV Special Coffee Maker chapter for us.

I am not here to give another solution for the problem. Instead, I wrote the CoffeeMakerGUI application, that contains a CoffeeMakerAPI implementation that lets you to manually test your solution by using a simulated Coffee Maker machine:


To compile it using a Java compiler, you need the CoffeeMakerAPI Java interface (given in the mentioned chapter) and also the following interface:

   public interface CoffeeMakerImpl {
      void createComponents(CoffeeMakerAPI api);
      void pollComponents();
   }

You can run the application without parameters, and a help message will be printed, but to test your solution you have to connect it with CoffeeMakerGUI, and to do it you must pass as the first argument of the program a class implementing the above CoffeeMakerImpl interface and having a default constructor. So the command to run it could be, for example:
java CoffeeMakerGUI MyCoffeeMakerImpl

The program will instance that passed class and will call to createComponents passing a reference of the CoffeeMakerAPI implementation. Then, it will call to the pollComponents periodically to "wake up" your implementation.

Thanks to Uncle Bob for publishing that interesting problem and solution!

Sunday, December 28, 2014

Simple JavaScript function to compare and sort localized strings

A recurring problem in JavaScript is sorting localized strings, that is, strings having characters from outside of the ASCII [A-Za-z] range, like for example the Spanish characters áéíóúüñ (and their uppercase equivalents).

For this problem I wrote the JavaScript function getLocaleStrCmpFn, which returns a function to compare and sort strings depending on the order given as parameter, for example, to sort an array of strings having Spanish characters you can do:

var ordES = ['AaÁá','Bb','Cc','Dd','EeÉé','Ff','Gg','Hh',
'IiÍí','Jj','Kk','Ll','Mm','Nn','Ññ','OoÓó','Pp','Qq',
'Rr','Ss','Tt','UuÚúÜü','Vv','Ww','Xx','Yy','Zz'];
var fnES = getLocaleStrCmpFn(ordES);

var arr = ['Álamo','abedul','Arce','abeto','Castaño','acacia'];
arr.sort(fnES);

Other ways to do it are the localeCompare function with additional non-standard arguments or the future JavaScript Internationalization API, but both are not supported in many versions of major browsers, so the locale-str-cmp.js solution is an easy way to sort strings for a specific locale or to create custom comparison functions. What do you think?

Thursday, November 13, 2014

Program to draw Tangram figures in SVG

The Tangram is an ancient Chinese game consisting in 7 geometrical flat pieces which must be put together to form a given figure, usually printed in paper. The solution for a given problem can be in another page, for example, this is how you form a square with the Tangram pieces:


I wrote a program in Perl called draw-tangram to create images of Tangram figures. To create a figure you need to write a description of the position of the pieces in a text file, in a simple format created for the program. Then you can choose to create images for the problem or the solution. For example:


To make this figure I first wrote the following instructions in a text file:

<3/4> a-b-c-d-a <0,6,4,2> [1,1,1,1];
<3/4> b-e-f-c-b <7,6,3,2> [0:1,1,0:1,1];
<3/4> f-g-h-f <3,6,1> [1,0:1,1];
<1/2> h-i-j-h <4,7,2> [2,0:2,2];
<1/2> i-k <7> [1];
<1/2> k-l-m-k <7,5,2> [1,1,0:1];
<1/2> k-o-n-k <3,5,0> [2,2,0:2];
<1/2> n-q <1> [0:1];
<1/2> q-s-r-q <1,4,7> [0:1,2,0:1];

Numbers between < and > are angles and numbers between [ and ] are lengths. The program helps you to create this because without parameters it prints the names of the points of the figure. To run the program you need Perl installed, and then you can write, for example:

perl draw-tangram.pl figure.txt

Then you can open the generated SVG file in a web browser to see the result. After that, you can use a program for editing vector graphics like Inkscape if you want a PNG or JPEG image. Enjoy it!

Sunday, June 15, 2014

CSV calendar generator

csv-cal.c is a command-line calendar program written in C to generate files in format CSV (Comma-Separated Values). The output of the program can be redirected to a .csv file ready to be opened in a spreadsheet application like LibreOffice Calc in order to format and print the calendar as you like.
The program allows to choose the first month to show, how many months and how many columns to show. The first day of the week can be set to Sunday or Monday and the names of the months and the days of the week can be changed. For example, to generate a calendar for the year 2014 starting the weeks on Monday and using Spanish names, you can type:
csv-cal -m 2014 "do,lu,ma,mi,ju,vi,sá" "Enero,Febrero,Marzo,Abril,Mayo,Junio,Julio,Agosto,Septiembre,Octubre,Noviembre,Diciembre" >2014.csv
To run it you need first a C compiler to generate the executable file, and then you need to know how to execute it from the command-line console. Executing the program without parameters will print a help for the different options that it supports. Enjoy!

Thursday, February 28, 2013

Simple Java Swing JSON formatter

Most of web developers that are using AJAX to retrieve data from the server will be using the JSON lightweight format (instead of XML) to encode the data. To help them with this, the web development consoles in all web browsers are capable to show a hierarchical view of received JSON data, and this is usually fine, but when the size of the data grows or its hierarchy becomes complicated, you need to copy the data out to study it. More specifically, I usually need to compare the differences in the responses of different calls to the server.

The problem here is that JSON data is generally encoded in a very long string without line breaks, so you must format the JSON first. Many online JSON formatters exist, but I just needed a simple non-remote tool to format large JSON strings, leaving each element in its own line and ordering the properties of the objects, so I wrote a little Java Swing program, JsonFormatter.java, helped by the json-simple Java toolkit. To use this program you need to download the json-simple JAR file in order to compile and run the program (see below), and do Ctrl+V/Ctrl+A/Ctrl+C to process the JSON text, along with a text editor capable of doing diff comparisons, like Vim. Use it!

To compile this program using the javac compiler, after putting the json-simple JAR file in the same directory (for example the 1.1.1 version), type: javac -cp json-simple-1.1.1.jar JsonFormatter.java

Then you could build a JAR file to run it easily, just typing: jar cfm json-formatter.jar MANIF-ADD.MF JsonFormatter*.class, where the MANIF-ADD.MF is a text file with the following two lines (ensuring that last line ends with a return):
Main-Class: JsonFormatter
Class-Path: json-simple-1.1.1.jar


After that, you only need the two JAR files, and to run it, if the double click doesn't work, you can type: java -jar json-formatter.jar

Sunday, January 13, 2013

Modern 10 PRINT ASCII-Art labyrinth generator

After reading a Slashdot post about the 10 PRINT one-liner maze generator, I spent many days thinking about how a simple random sequence of / and \ could make those labyrinths.
Anyone who tried to generate labyrinths from a program knows that it isn't an easy task, so I immediately wrote a program to test if that algorithm could be so good, and I got this output:
/\////\\//\/\//\\\\\/\//\\
\////\\\///\/\////\/\\/\/\
/\\/\\\///\/\/\///\/\/\/\\
/\/\\\\\//\/\\\\/\\\\//\\\
///\/\\\/\\///\/\/////////
/\//\/\//\\/\///\\\/\/\/\/
\////\\\/\/\\\\\/\/////\\/
/\//\/\/////\\//\/\\///\\\
\\\\///\\/\/\/\/\\//\\/\\\
///\\/\\//\\\\/\///\\/\\\\
Well, that wasn't exactly what I expected, and I quickly realized that there was a problem with the fonts, so I made some tests trying to change many parameters of the text in a word processor, without success. Modern "\" and "/" characters are not designed for such effect! And the separation of lines was also a problem.

Anyway, I was not satisfied yet, so I studied how to design a program to represent, generate and print such maze using horizontal and vertical characters, learning in the way a lot about this thing. Today I would like to publish my little program 10print.c for anyone interested. This was the result:
   |  ___  |   |   |   |  _______  |   |  ___  |  __
 | | |  ___|___|___|___|___  |  ___| | | |  ___|___ 
 |___| |   |   |   |  _______|___  | | | | |  ___  |
___  | | | | | | | |___  |  _______| | |___| |  ___|
   | |___|___| | |_______|___  |   | | |  ___| |  __
 | |___  |   | | |  ___  |  ___| | |___| |  ___|___ 
 | |  ___| | |___|_______|_______| |   | |___  |  __
___|_______| |  _______________  | | | |_______|___ 
   |   |   | |___  |  ___________| | |_______  |   |
 | |___| | |___  | | |   |   |   | | |   |   | | | |
 | |  ___| |   | |___| | |___| | | | |___|___| | |__
 | | |   | |___|_______| |  ___| | |___  |  ___| |  
 |___| | | |   |   |  ___|_______| |  ___| |  ___|__
_______|___| | |___| |   |   |   | | |  ___|___  |  
   |  ___  | | |  ___| | |___| | | | | |   |   | |__
___| |   | |___| |  ___|___  | | | | | |___|___|___ 
  ___|___|_______| |   |   | |___|___| |  ___  |  __
 |  ___  |  _______| | | | |_______  | |_______|___ 
 | |   | | |  _______| | |_______  | | |  __________
___| | |___| |   |   | |_______  | |___|___________ 
Much better! I haven't read the 10 PRINT book, but I enjoyed a lot doing this. Thank you for give me such an interesting problem!

Wednesday, July 7, 2010

How to run your JUnit 4 tests using the old JUnit 3 GUI runners

Although the usual way for running JUnit tests is inside an IDE like Eclipse or NetBeans, both with an integrated debugger that directly points you to the place where the error is located when a test fails, sometimes can be better a lightweight tool for running your tests.

The popular JUnit testing framework, in its version 3, came with Java-based GUI runners which allowed developers to see the test results in a graphical window instead of having them printed in the text console, so it was nice to run them even without having an IDE.

Instead, the next version of the framework, JUnit 4, didn't come with any GUI runners (for unknown reasons for me, perhaps because the features and API are in constant change or to encourage developers to use IDEs for debugging), so developers not using an IDE now must see the results of their tests in the text console, having to read the large exception's trace output when an error appears, hidding also any other debugging messages added by the developer to catch the bug.

In the first releases of the JUnit 4 series, the JUnit team developed a backwards compatibility feature for allowing the JUnit 4 tests to be run with a JUnit 3 runner, so certain older applications having such a runner could run JUnit 4 test classes just adding to them the following method (changing the SimpleTest.class to the file name in which the code is pasted):

public static junit.framework.Test suite() {
return new junit.framework.JUnit4TestAdapter(SimpleTest.class);
}


For achieving this the JUnit 4 framework provides some code under the old junit.framework package (although the new version uses the new org.junit package to allow coexistence), so the code showed before can be compiled with the JUnit 4 framework and also be able to run in a JUnit 3 runner needing to call the suite() method.

Recently, however, it seems that support for this hack has been reduced as more applications are ported to the new framework version, so you cannot find the JavaDoc documentation of this package in the latest JavaDoc JUnit 4 API link from JUnit main page, but only in the outdated previous version of the JUnit 4 API. Also, if you download the last JUnit 3 version from the old JUnit hosting site at SourceForge, the old GUI runners seem not to run properly, perhaps because of the problem of having both junit.framework versions of the package.

After many days searching around this, I discovered that the people from JUnit 4 Extensions have been maintaining the isolated GUI runners of JUnit 3, so they can coexists with the JUnit 4 packages without problem. By adding their prebuilt junit-ui-runners-3.8.2.jar file to your CLASSPATH environment variable you will be able to run any individual JUnit 4 modified test class in the old Swing GUI runner of JUnit 3 introducing the following command (changing the SimpleTest name to the name of the class test that you want to run):

java junit.swingui.TestRunner SimpleTest


Keep in mind that this is a temporary solution, because JUnit 4 will not support this for a long time (although having a simple standalone GUI runner for JUnit 4 would be much better). Until then, when all those suite() methods will be removed, we can keep using this alternative. Happy testing!