Possible replacement for GLYPHICONS: Font Awesome

During the last couple of months most of my interfaces were based on Twitter-Bootstrap. I was generally satisfied, it was extremely easy to use and extend, however, during my latest search for scalable GLYPHICONS this happened:

GLYPHICONS

The glyphicon-halfings coming with Twitter Bootstrap are distributed under the same license as Twitter Bootstrap itself (Apache 2.0: http://www.apache.org/licenses/LICENSE-2.0) which allows you almost everything other than removing the copyright stuff at the top of the relevant source files.

OK, so?
These icons are coming as a non-scalable png. In case if you want bigger, HUGE icons, you have to use GLYPHICONS, not the Halfings, which forces you to include the CC-BY license and the reference to glyphicons.com on every page using GLYPHICONS.

As GLYPHICONS states, it is completely free,

meaning:

Free for both personal and commercial use.

meaning:

GLYPHICONS FREE are released under the Creative Commons Attribution 3.0 Unported (CC BY 3.0). The GLYPHICONS FREE can be used both commercially and for personal use, but you must always add a link to glyphicons.com in a prominent place (e.g. the footer of a website), include the CC-BY license and the reference to glyphicons.com on every page using GLYPHICONS.

Source: http://glyphicons.com/glyphicons-licenses/

FontAwesome

You know what are Webdings, do you?

Webdings is a TrueType dingbat font developed in 1997. It was initially distributed with Internet Explorer 4.0, then as part of Core fonts for the Web, and is included in all versions of Microsoft Windows since Windows 98. Most of the glyphs have no Unicode character equivalents.

As you probably figured out, Font Awesome is actually a font, … an iconic one! Why this is so awesome? Because they will look nice and scale properly on all sizes, because… they are fonts. This basically solved all the problems arising around scaling.

What’s with the licensing?

In nutshell, you can use the Font Awesome icons without any link-back to the original site – as the original author of Font Awesome specified the level of contribution in the last point of the copyright stuff above.

Anyway, Leaving a respectful message in human.txt won’t hurt.

Stats

Finally, the numbers! (These statistics are pretty much pointless due to the fact that browser cache exists but anyway):

File FontAwesome GLYPHICONS
index.html 297 B 231 B
bootstrap.min.css 103 KB 103 KB
bootstrap-responsive.min.css 16.5 KB 16.5 KB
glyphicons-halflings.png 12.5 KB
font-awesome.min.css 15.4 KB
fontawesome-webfont.woff?v=3.0.1 28.7 KB
Total 163.89 KB 132.23 KB

My index pages look like:

for Font Awesome:

<html>
    <head>
        <link href="assets/css/bootstrap.min.css" rel="stylesheet" />
        <link href="assets/css/bootstrap-responsive.min.css" rel="stylesheet" />
        <link href="assets/css/font-awesome.min.css" rel="stylesheet" />
    </head>
    <body>
    <h1><i class="icon-play"></i> hello!</h1>
    </body>
</html>    

for GLYPHICONS:

<html>
    <head>
        <link href="assets/css/bootstrap.min.css" rel="stylesheet" />
        <link href="assets/css/bootstrap-responsive.min.css" rel="stylesheet" />
    </head>
    <body>
    <h1><i class="icon-play"></i> hello!</h1>
    </body>
</html>  

BriteSnow on Jetty – Quick Start Guide

Being a developer on a Java JEE project, words like increased productivity, faster development time, lightweight *, were always encouraging to me. I heard somewhere about BriteSnow company and their open-source products (they host them on github, which is very nice!) so I decided to give a shot to these tools and try to find out, could I really speed up the development process of an enterprise-size project.

Note that the first part of this guide is intended to provide a summary about (Brite)Snow configuration. Take it as a reminder or a cheat sheet. More detailed scenarios including persistence will follow soon and will reference this guide as a starting point.

Setup

Snow arrives through the following maven dependency. We are going to use the latest stable version, for experimental versions see their Maven section.

<dependency>
  <groupId>com.britesnow</groupId>
  <artifactId>snow</artifactId>
  <version>2.0.0</version>
</dependency>

For the beginning create a standard servlet descriptor web.xml, in src/main/webapp/WEB-INF:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
    <display-name>
        SnowApplication
    </display-name>
    <servlet>
        <servlet-name>
            snowServlet
        </servlet-name>
        <servlet-class>
            com.britesnow.snow.web.SnowServlet
        </servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>
            snowServlet
        </servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

Note that the official documentation goes with servlet version 2.4 instead of 3.0.

Snow also requires a properties file snow.properties to be present in the src/main/webapp/WEB-INF directory which in my case looks like:

# The Application Guice Modules (1 or more, comma seperated)
snow.webApplicationModules=org.example.britesnowdemo.AppConfig

This may seem to be a bit tricky but it’s something similar when you configure a Jersey application through annotations. Except that in Jetty you can use the @ApplicationPath, but in this case you have to point to your application class in a separate config file (which is probably not as good as having only an annotation, but anyway..).

Beware, I made a mistake here! The documentation clearly says:

Note: The first Google Guice module defined in the snow.webApplicationModules property (here the only AppConfig ) specifies the base package from where Snow scans classes for Snow method annotations (e.g., @WebGet, @WebModelHandler, …) to do the appropriate “Web bindings.” So, make sure that the first Guice module is at the root package of your application.

First I placed the AppConfig into org.example.britesnowdemo.config (because I felt that should be OK, since I pointed to the right class in snow.webApplicationModules), sadly this made BriteSnow to answer with 404 to every request I made. So remember: your snow.webApplicationModules class should be always in the root package.

Our Snow application will be configured based on the modules present in this class:

package org.example.britesnowdemo.config;

import com.google.inject.AbstractModule;

public class AppConfig extends AbstractModule {

    @Override
    protected void configure() {
    }
}

For this example I’ll just leave this empty. You will probably have entities in your application, so take a look at the sampleBookmarks AppConfig on their github repository which shows a neat way to autodiscover all your entity classes:

That would be all regarding the configuration. Next thing to do is to create a simple web-service and finally fire some HTTP request.

Web Resources

If you’re already familiar with Jetty then you will find Snow almost identical, meaning web-method discoverage, similar method annotations, path annotations, etc.:

@WebPost("/delete-item-{id}")
public Object aRestGet(@PathVar("id")Long id){
// id == 123
}

while in JAX-SR:

@POST("/delete-item-{id}")
public Object aRestGet(@PathParam("id")Long id){
// id == 123
}

For the sake of simplicity our service will only say hi to us:

package org.example.britesnowdemo;

import com.britesnow.snow.web.param.annotation.WebParam;
import com.britesnow.snow.web.rest.annotation.WebGet;
import javax.inject.Singleton;

@Singleton
public class SnowResource {

    @WebGet("/rest/sayhello")
    public String sayHelloTo(@WebParam("name") String name) {
        return "Hello, " + name + "!";
    }
}

That’s all! Now you can deploy the project with Jersey’s maven plugin:

mvn jetty:run

and fire a HTTP request to the only existing REST resource:

http://localhost:8080/britesnowdemo/rest/sayhello?name=Snow

You can download the full project from https://www.dropbox.com/s/35zr2if2tlvehbb/britesnowdemo.zip.

Web Application with JAX-RS (Jersey) on Glassfish

In this tutorial we create a minimalistic web application by using JAX-RS annotations. Our provider class contains some simple methods, responding to HTTP GET requests:

    @Path("/welcomes")
    public class Resource {

        @GET
        @Path("hello")
        public String hello() {
            return "Hi from REST!";
        }

        @GET
        @Path("short/{name}")
        public String shortWelcome(@PathParam("name") String name) {
            return "Hi, " + name;
        }
    }

To hold the Web Service configurations we need to create a class which extends javax.ws.rs.core.Application:

package com.mycompany.restdemo;

import javax.ws.rs.core.Application;

public class ApplicationConfig extends Application {
}

To map the incoming requests under this application, annotate the class with @javax.ws.rs.ApplicationPath. Finally by overriding the

public Set<Class<?>> getClasses()

method of the javax.ws.rs.core.Application class return the provider class(es). This will make the methods of the provider class visible under rest/welcomes/hello and rest/welcomes/short/name URLs.

package com.mycompany.restdemo;

import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/rest")
public class ApplicationConfig extends Application {
    @Override
    public Set<Class<?>> getClasses() {
        return getRestResourceClasses();
    }
    
    private Set<Class<?>> getRestResourceClasses() {
        Set<Class<?>> resources = new java.util.HashSet<Class<?>>();
        resources.add(com.mycompany.restdemo.Resource.class);
        return resources;
    }
}

Your Web Service is done!

Here is the archive containing this demo project tested in GlassFish 3.1.2. It’s a maven project and you can run it right after extracting (you will need Maven) by executing:

mvn install

in the same folder where the pom.xml file is. This will download the required libraries and deploy the web application under http://localhost:8080/restDemo

restDemo.tar.gz (1.59 KB)

EclEmma: the free Java code coverage tool for Eclipse

Unit testing has a lot of aspects which are more or less equally important but code coverage is something on what you really have to pay attention. Depending on the complexity of our methods, more combinations are possible on arbitrary test inputs. Considering every permutation in some not-so-obvious cases takes some time and effort, and the chance to make a mistake – which will result in an uncovered piece of code – is even higher.

EclEmma is the right tool to measure the coverage of your code and to make sure that every single line is executed properly. It has plenty of useful features from which I’ll present only the Coverage tool. In this post you will:

  • see how to run your unit tests through EclEmma
  • how to interpret the output of the Coverage tool

I’m using EclEmma with JUnit4 but it will run with JUnit3 too. You will find any neccessary information regarding to the installation on EclEmma site: http://eclemma.org/.

So lets take a look at an example from the source of Qt Jambi. QPair of the com.trolltech.qt package is used to hold two generic values. There are 3 methods to test: public boolean equals(Object o), public String toString() and public QPair clone().

I won’t give any detailed explanations about the test methods since the main goal of this post is to introduce EclEmma. However if you are new in unit testing too you could take a look at one of my old posts Unit testing with Qt Jambi. There are a lot of resources about unit testing but that post is directly related with the currently studied examples.

Let’s take a look at public boolean equals(Object o) which is a method to check the equality of two objects (beware, it could be very tricky!). If you can’t access the resource above, don’t worry the code is reproduced here:

    /**
     * Returns true if this pair is the same as the other pair. If any
     * of the first or second members are null the result is false regardless.
     * @param The other parameter
     * @return True if they are equal.
     */
    @Override
    public boolean equals(Object o) {
        QPair<?, ?> other = o instanceof QPair ? (QPair<?, ?>) o : null;
        if (other == null || first == null || second == null || other.first == null || other.second == null)
            return false;
        return first.equals(other.first) && second.equals(other.second);
    }

Our test case for this particular method is:

	@org.junit.Test
	public void testEquals() {
		assertTrue("qp1", qp1.equals(qp1));
		assertFalse("qp2", qp1.equals(qp2));
		assertFalse("qp3", qp1.equals(qp3));
	}

       @org.junit.Before
       public void setUp() {

               qp1 = new QPair<Integer, Integer>(3, 5);
               qp2 = new QPair<Integer, Integer>(5, 3);
               qp3 = new QPair<Integer, Boolean>(1, null);
               qp4 = new QPair<Integer, Boolean>(null, true);	
       }

While the test case is opened, from the Run menu select Coverage As > JUnit Test. The JUnit test starts and EclEmma is calculating some measurable properties of your code. Now you should see something like this:

As EclEmma finished its job you can see the coverage result of your unit test code:

and the code of the tested class too:

But some of the lines appeared in yellow instead of green, what happened? If you take a closer look to these lines EclEmma will tell you that there are some uncovered branches in your code. In this particular case we have 5, 3 on line 79 and 2 on line 81:

Lets take a look again at our test and study it carefully:

	@org.junit.Test
	public void testEquals() {
		assertTrue("qp1", qp1.equals(qp1));
		assertFalse("qp2", qp1.equals(qp2));
		assertFalse("qp3", qp1.equals(qp3));
	}

       @org.junit.Before
       public void setUp() {

               qp1 = new QPair<Integer, Integer>(3, 5);
               qp2 = new QPair<Integer, Integer>(5, 3);
               qp3 = new QPair<Integer, Boolean>(1, null);
               qp4 = new QPair<Integer, Boolean>(null, true);	
       }

Is there any assertion in our test which is running through this if:

               if (other == null || first == null || second == null || other.first == null || other.second == null)

Lets see: the expression inside if will be true iff at least one of those conditions between || is true. Our only assertion which involves null is this one:

               assertFalse("qp3", qp1.equals(qp3));

which is, obviously, won’t cover all the possible candidates in which the above if will be executed. This assertion covers exactly one case. Remember QPair(T, S), and because qp3 was constructed with (1, null) it covers:

               if (other == null || first == null || second == null || other.first == null || other.second == null)

Thanks EclEmma for pointing out this obvious mistake! After adding more assertions to cover all the possible cases you will see something like this:

All branches are covered properly! \o/

Of course this is just one from EclEmmma’s useful features. In case of big projects it is good to see how your overall coverage is forwarding, you can check that too:

As you can see we have a lots of work to do.

This was a very short but fair introduction about EclEmma’s main feature, using it on regular basis to check your unit tests functionality will save you lots of time.

Thank you for your time, comments are welcome, as always!

Generating color palettes – based on the Fibonacci sequence

We are continuously facing with complicated mathematical concepts every day, even without knowing about their existence.

Just take a look at the range of IP addresses. In ideal case an IP address tends to be closer to another IP address even when adding some new addresses between, the concept of the Hilbert curve:

The previous theory is highly applicable from machine point of view, but there are also plenty of theories applicable from human point of view. Maybe the most famous is the Golden Ratio or Divine Proportion:

In mathematics and the arts, two quantities are in the golden ratio if the ratio of the sum of the quantities to the larger quantity is equal to the ratio of the larger quantity to the smaller one.

=====|===
  a    b

meaning, a+b is to a as a is to b. From the machine’s point of view, nothing particularly happens, it’s just a “constant” which values is 1.6180339887… (yes, with quotes, the value of this proportion is an irrational number therefore I’m not sure about using the term “constant” when talking about irrational numbers, if you think otherwise, leave a comment below). However this “constant” is really important when talking about beauty and perfection generally. It appears in everything which is aesthetic to us, humans:


1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, … as you may have already realized, the next number in this sequence should be 55+89=144. The numbers of the Fibonacci sequence, or the Fibonacci numbers. What could be so interesting in this sequence other than describing the growth of an idealized rabbit population?
If you don’t know yet, let me show you. Divide the current and the previous number of the Fibonacci sequence above, starting from the second element, repeating infinite times:

\frac{1}{1} =1\newline\newline \frac{2}{1}=2\newline\newline \frac{3}{2}=1.5\newline\newline \frac{5}{3}=1.66..\newline\newline \frac{8}{5}=1.6\newline\newline \frac{13}{8}=1.625\newline\newline \frac{21}{13}=1.615\newline\newline \frac{34}{21}=1.61904...

As you may have already discovered the results of these iterations are approaching to the value of the Golden Ratio (see above, it was: 1.6180339887…).

The question is appropriate: Is there any way to apply this abstract representation of the golden ration?

Let’s take a look at the hexadecimal representation of a color “from the web”, a0ff11. Each color consist of three components, the red: a0, the green: ff and the blue component: 11. The idea is very simple: increment every component by the elements of the Fibonacci sequence.

The implementation happened in JSP, because everyone needs to know JSP!!1 currently I’m advancing in JSP.🙂
Nothing fancy just a simple opening page to gather the required parameters, like the base color, number of color in the palette and the component which have to be modified:

<html>
<head>
<title>Color Palette Generator</title>
</head>
<body>
	<form action="generator.jsp" method="get">
		<table>
			<tr>
				<td>Base color:</td><td><input name="baseColor" type="text" /></td>
			</tr>
			<tr>
				<td>Palette size:</td><td><input name="sequence" type="number" /></td>
			</tr>
			<tr valign=top>
				<td>Component to modify:</td><td>
				<input type="checkbox" name="red" value="r" />Red
				<br/>
				<input type="checkbox" name="green" value="g" />Green
				<br/>
				<input type="checkbox" name="blue" value="b" />Blue
				<br/>
				<input type="submit" value="Generate" />
				</td>
			</tr>
		</table>
	</form>
</body>
</html>

modifying only by blue component


click to enlarge

Now some green magic:

click to enlarge

…and some red:

click to enlarge

And finally some of the colors I picked up randomly, all three modified components are rendered at once:

#2d9b27


#412c84


#24577b


d5f800

The code itself is quite simple.

<%@ page language="java" import="java.awt.Color,java.util.*"%>
<%!/* Some members of the mighty Fibonacci sequence
	 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987
	 */
	// and some of them what I found useful:

	int fib[] = { 13, 21, 34, 55, 89, 144 };

	//int fib[] = new int[] { 2, 3, 5, 8, 13, 21, 34 };
	//int fib[] = new int[] { 5, 8, 13, 21, 34, 55, 89 };

	public ArrayList generatePalette(Color baseColor, int n, String modifier) {
		ArrayList<Color> colorVector = new ArrayList<Color>();
		colorVector.add(baseColor);
		Color tmp = baseColor;
		for (int i = 0; i < n; i++) {
			tmp = generateColor(tmp, fib[i % 6], modifier);
			colorVector.add(tmp);
		}
		return colorVector;
	}

	public Color generateColor(Color color, int delta, String modifier) {
		int r = -1;
		int g = -1;
		int b = -1;

		if (modifier.equals("r")) {
			r = add(color.getRed(), delta);
			g = color.getGreen();
			b = color.getBlue();
		} else if (modifier.equals("g")) {
			r = color.getRed();
			g = add(color.getGreen(), delta);
			b = color.getBlue();
		} else if (modifier.equals("b")) {
			r = color.getRed();
			g = color.getGreen();
			b = add(color.getBlue(), delta);
		}

		return new Color(r, g, b);
	}

	public String colorToStr(Color color) {
		String r = Integer.toHexString(color.getRed());
		String g = Integer.toHexString(color.getGreen());
		String b = Integer.toHexString(color.getBlue());
		r = r.length() < 2 ? "0" + r : r;
		g = g.length() < 2 ? "0" + g : g;
		b = b.length() < 2 ? "0" + b : b;
		return r + g + b;
	}

	// if > 255 restart from 0
	public int add(int old, int d) {
		if (old + d > 255)
			return old + d - 255;
		else
			return old + d;
	}%>
<%
	String baseColor = (String) request.getParameter("baseColor");
	int colorToInt = Integer.parseInt(baseColor, 16);
	Color newColor = new Color(colorToInt);
	String sequence = (String) request.getParameter("sequence");
	int times = Integer.parseInt(sequence);
	String[] modifiers = new String[3];
	modifiers[0] = (String) request.getParameter("red");
	modifiers[1] = (String) request.getParameter("green");
	modifiers[2] = (String) request.getParameter("blue");
%>
<html>
<head>
<title>Color Sequence Generator</title>
<link rel=stylesheet type="text/css" href="generator.css">
</head>
<body>
	<%
		for (int j = 0; j < modifiers.length; j++) {
			if (modifiers[j] == null)
				continue;
	%>
	<table class="main">
		<tr>
			<%
				ArrayList palette = generatePalette(newColor, times,
							modifiers[j]);
					for (int i = 0; i < palette.size(); i++) {
						String current = colorToStr((Color) palette.get(i));
			%>
			<td class="colorDiv" bgcolor="#<%=current%>"><font
				class="colorName">#<%=current%></font></td>
			<%
				}
			%>
		</tr>
	</table>
	<%
		}
	%>
</body>
</html>