Thursday, June 11, 2015

Geecon 2015

So last month I've attended Geecon and I really loved it. Geecon is a conference focused on Java and JVM technologies, hosted annually in Cracow (usually).
Geecon had a Steampunk theme
This year’s it was all about microservices, so it’s no surprise that I enjoyed Fred George’s “Challenges in implementing microservices” the most.

In his talk Fred George shared his experiences with replacing monolith applications with microservices. He explained how microservices facilitate a Service Oriented Architecture and “going faster” as shorter reaction time for the whole company.

What was most interesting to me was the comparison of asynchronous and synchronous approaches to microservices. He mentioned his friend Chad Fowler suggests synchronous communication on default mainly because it’s easier for most of the modern programmers. In contrast Fred George believes that asynchronous messaging gives so too much of an opportunity for robustness and graceful degradation to ignore in exchange for simpler implementation.

Sam Newman on the left, Konrad Malawski on the right and Fred George in the middle
Well, Fred George convinced me to his approach. But it might have something to do with him being a really cool guy and his grey, sage-like, hair - he joked about it a little.

Sam Newman's talk on microservices was also very compelling, even though he talked about his book an awful lot. Must have worked, because I got it for myself after the conference. ;)

If you'd like to know how my how my friends at Espeo Software enjoyed the conference you can do so here!

Sunday, February 1, 2015

Creation method in Mongoose.js, alternative to custom constructor or hooks

Creation method or factory method is a neat way of creating objects in the same way by using the object's well-named static method instead of constructor. While similar, creation method should not to be confused with factory method pattern, which involves the concrete implementation of created objects). If you'd like to know more about creation method's benefits and application I highly recommend Joshua Kerievsky's Refactoring to Patterns.

Here's how this alternative to custom constructor or hooks can work in Mongoose. Let's use an Article model in Mean.js app generated by Yeoman as an example:

'use strict';

 * Module dependencies.
var mongoose = require('mongoose'),
 Schema = mongoose.Schema;

 * Article Schema
var ArticleSchema = new Schema({
 created: {
  type: Date,
 title: {
  type: String,
  default: '',
  trim: true,
  required: 'Title cannot be blank'
 url: {
  type: String,
  trim: true,
  default: '',
  required: 'Url cannot be blank'
 content: {
  type: String,
  default: '',
  trim: true
 user: {
  type: Schema.ObjectId,
  ref: 'User'

mongoose.model('Article', ArticleSchema);

Let's say we'd like article to have an url field, which we'd like to generate from the title. We'd like to avoid copying the url generation code everytime we'd like to create an article. One way to do this is to create a creation method which does that.

Since all static methods have to be defined before the model class is created creating a creation method the following won't work:

/** Schema definition. */

var Article = mongoose.model('Article', ArticleSchema);

ArticleSchema.schema.createInstance = function (user, title, content) {
 return new Article({
  user: user,
  title: title,
  content: content,
  url: title.replace(new RegExp(' ', 'g'), '-')

Instead we can simply fetch the model using mongoose.model. Here's a working example of a creation method:

/** Schema definition. */

ArticleSchema.schema.createInstance = function (user, title, content) {
 var Article = mongoose.model('Article');
 return new Article({
  user: user,
  title: title,
  content: content,
  url: title.replace(new RegExp(' ', 'g'), '-')

mongoose.model('Article', ArticleSchema);

Tuesday, December 23, 2014

Mavenized Java server application and Angular.js frontend application using yeoman

Install yeoman
npm install -g yo

Install generator-angular
npm install -g generator-angular
Create a directory in your project's root (I'll be using 'ui')
mkdir ui && cd $_
While inside ui directory create your app using yeoman and generator-angular. Be sure to run bower install at least once before due to this error.
yo angular your_project_name
Add grunt-cli to your dependencies
npm install grunt-cli --save-dev
In Gruntfile.js change application config, so the application is compiled into java resources:
  // Configurable paths for the application
  var appConfig = {
    app: require('./bower.json').appPath || 'app',
    dist: '../src/main/resources/public'
Grunt will attempt to clean '../src/main/resources/public' each time it builds, but since it's a path outside of our current working directory, we have to force the clean, by adding 'force:true' option.
options: {
    force: true
For example:
// Empties folders to start fresh
    clean: {
      dist: {
        options: {
          force: true
        files: [{
          dot: true,
          src: [
            '<%= yeoman.dist %>/{,*/}*',
            '!<%= yeoman.dist %>/.git{,*/}*'
      server: '.tmp'
Finally add build plugin to pom.xml so the js appliacation and all of its resources are built into your Java resources. Notice that for workingDirectory I'm using my directory's name 'ui'.
                        install node and npm
                        npm install
                        grunt build
                            build --no-color
The build should pass and you can deploy your appliacation to a server container of your choosing. :)
I'm using Spring (along with Spring Boot). A simple controller like this:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

public class BasicController {

    String home() {
        return  "redirect:/index.html";

Should yield a result like this:

I've based this article on Gunnar Hillert's Botanic-ng and my own experimentation.

Saturday, April 7, 2012

Calculating values for bar charts in latex

The bchart package

If you want to add some bar charts to your latex document you might want to use bchart. This pdf by Tobias Kuhn shows some examples of how to use the package. Description taken from that pdf:
bchart is a LATEX package for drawing simple bar charts with horizontal bars
on a numerical x-axis. It is based on the TikZ drawing package. The focus of
this package is on simplicity and aesthetics.
Using the package one can display labels, specify the axis range, bar colors or unit of the values.

Calculating values

Unfortunately the package has a drawback. If you use math expressions they will be calculated for the bars but wont their values won't be displayed. In addition you cannot use \pgfmathparse{} to calculate the value for the chart because it will cause errors in displaying the bars.
\begin{bchart}[min=-100, max=100, step=25, unit=\%, width=\linewidth]

\bcbar[text=should be 100,color=green!40]{123 - 23}
\bclabel{bars group  1}

\pgfmathparse{123 - 23}
\bcbar[text=should be 100 again,color=red]{\pgfmathresult}

\pgfmathparse{123 - 23}
\bcbar[text=should be 100,color=yellow]{\pgfmathresult}
\bclabel{bars group 2}
\pgfmathparse{123 - 23}
\bcbar[text=should be 100,color=red!40]{\pgfmathresult}

\bcxlabel{this does not work properly}
Which yields:
I believe it is due to internal usage of pgfmath of the package. There is a simple solution though, using \\pgfmathsetmacro{}{}:
\begin{bchart}[min=-100, max=100, step=25, unit=\%, width=\linewidth]
\pgfmathsetmacro{\makroName}{123 - 23}
\bcbar[text=should be 100,color=green!40]{\makroName}
\bclabel{bars group  1}
\bcbar[text=should be 100 again,color=red]{\makroName}

\pgfmathsetmacro{\anotherMakro}{23*100 / 123}
\bcbar[text=calculating 23*100 / 123,color=yellow]{\anotherMakro}
\bclabel{bars group 2}
\bcbar[text=as above,color=red!40]{\anotherMakro}

\bcxlabel{this does}
Which yields:

Thursday, April 5, 2012

Setup SQL Server 2012 and Adventure Works cube with Visual Studio 2010

This tutorial will show you how to deploy a cube onto SQL Server 2012 using VS2010 and might help you avoid some of the problems I've encountered. It is complementary with Multidimensional Modeling (Adventure Works Tutorial) and uses its Adventure Works db and cube project.

While this states that it is not possible to deploy a cube using Visual Studio it is no longer true with SQL Server 2012.


Visual Studio 2010 disc or image
Installed Visual Studio 2010
SQL Server 2012 disc or image
Service Pack 1 for VS2010 due to this

Installing SQL Server 2012 or adding required features

Note: Running VS2010 during the installation might cause errors so close it.

Run SQL Server Setup by selecting New SQL Server stand-alone installation or add features to an existing installation from Installation tab of the SQL Server Installation Center. Move through the process up to Installation Type. If you already have an installed SQL Server you would like to use, pick Add features options and select your server instance, like below:
Pick the following features:

Notably SQL Server Data Tools contain Buisness Intelligence Developement Studio (BIDS) for Visual Studio 2010 that will allow you to deploy a cube.
Some of the features might be redundant (I'm particularly uncertain about the Integration Services) but are definitely sufficient for deploying a cube and running some MDX queries.

Complete the installation process. You will be probably required to insert or mount the VS2010 disc or image.

Wednesday, April 4, 2012

MongoDB and distinct values in arrays

This post is a mini-tutorial on how to deal with array fields in MongoDB, specifically arrays of items that may or may not be duplicated.

Let's create a collection of unicorns, smilarly to The Little MongoDB Book examples:
> db.unicorns.insert( { name: 'Playja', loves: ['sweets', 'movies'] } )
> db.unicorns.insert( { name: 'negaPlayja', loves: ['evil things', ], evil: true} )

Find should now return something like this, the _ids will vary :

> db.unicorns.find()
{ "_id" : ObjectId("4f7b80fffbd1718d939a8801"), "name" : "Playja", "loves" : [ "sweets",  "movies"] }
{ "_id" : ObjectId("4f7b8106fbd1718d939a8802"), "name" : "negaPlayja", "loves" : [ "evil things"], "evil" : true }

Adding a value into an array

We've found out that our Playja unicorn also loves playing games, so lets push a new value into our document's loves array:
> db.unicorns.update( {name: 'Playja' }, { $push: { loves: 'playing games' } } )
> db.unicorns.find()
{ "_id" : ObjectId("4f7b80fffbd1718d939a8801"), "loves" : [ "sweets", "movies", "playing games" ], "name" : "Playja" }
{ "_id" : ObjectId("4f7b8106fbd1718d939a8802"), "name" : "negaPlayja", "loves" : [ "evil things" ], "evil" : true }
Using push, we could insert into our the same value multiple times.

Pushing a value if its unique

We have found out that all our unicorns love movies and want to update the whole collection. Unfortunately Playja already has got movies in his loves field. As shown here, we can use addToSet, which won't add a duplicated value to an array:
> db.unicorns.update({}, {$addToSet: { loves : 'movies' } }, false, true)
> db.unicorns.find()
{ "_id" : ObjectId("4f7b80fffbd1718d939a8801"), "loves" : [ "sweets", "playing games", "movies"], "name" : "Playja" }
{ "_id" : ObjectId("4f7b8106fbd1718d939a8802"), "evil" : true, "loves" : [ "evil things", "movies" ], "name" : "negaPlayja" }
The third parameter of update is upsert(false by default). The fourth is multi which makes the query update every document that matches the criteria (false by default meaning that it only updates the first one). You can read more here.

Sunday, April 1, 2012

Installing FANN on Java project and NativeLibrary.loadLibrary problems with 32bit/64bit

If you try to install FANN and get it working with a Java project you might run into a few problems. The whole process is explained on the fannj (the Java binding) project's wiki but not in great detail.

Here is what you need to do:

  1. Get fannj
  2. Store it somewhere and add the jar to your project.
  3. Get FANN
  4. Extract it somewhere.
  5. Either :
    * copy the fannfloat.dll to System32
    * add the following line before you try to use FANN:
     System.setProperty("jna.library.path", [fannfloat.dll dir path]);

Solutions to problems:

No Java Native 
"Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/jna/Platform"
Solution: Download the JNA and add the jar to your project.

Can' find the FANN library
Exception in thread "main" java.lang.UnsatisfiedLinkError: Unable to load library 'fannfloat': The specified module could not be found.
Add the following code after you set the JNA library path, run it:

System.out.println( System.getProperty("jna.library.path") ); //maybe the path is malformed
File file = new File(System.getProperty("jna.library.path") + "fannfloat.dll");
System.out.println("Is the dll file there:" + file.exists());
You can fix the problems if something is wrong with the first two messages easily.
If the code fails with this message:
Exception in thread "main" java.lang.UnsatisfiedLinkError: [ddl path]: Can't load IA 32-bit .dll on a AMD 64-bit platform
then you are probably running a 64bit Java SDK while fannfloat.dll is 32bit. The solution for me was installing additional 32bit Java SDK and choosing it in the build path for my project.