Calculate Time Spans by Quarters of an Hour With SQL

Suppose you have a database table containing two fields ‘start’ and ‘end’ of type timestamp denoting the starting time and ending time, respectively, of some time span. You can calculate the positive time span between these two points in time rounded to the nearest quarter of an hour with the following SQL snippet:

SELECT
 ABS(EXTRACT (HOUR FROM table.end - table.start) + 
 (ROUND((EXTRACT (MINUTE FROM table.end - table.start))
 / 15) * 0.25))
FROM 
 schema.table

For example, this yields for the time span 10:30 – 12:00 a duration of 1.5 hours.

Veröffentlicht unter Did you know? | Verschlagwortet mit , , | Hinterlasse einen Kommentar

Failing Fast With Guava’s Preconditions

One of the many Good Programmer’s mantras is to always have your input data checked against invalid values. So we decorate our public interfaces with assertions or intricate if-then-else constructs checking all possible combinations of the input data, throwing around Exceptions and assembling meaningful error messages. … Or we skip erecting this line of defense altogether when the next release date comes frighteningly close.

To fail fast and early during program execution is a good thing so as we get notice about a bug as close to the place where it originated as possible. A bug that only materializes late in some remote corner of my code base which is totally unrelated to the bug’s original place of birth is a lot harder to track down and eliminate than a bug that directly calls attention to itself with a noisy Exception directly when it first appeared.

So we should continue (or begin?) adding sanity checks for input parameters to our public methods. Yet oftentimes these tend to grow and clutter our ‘real’ code, and sometimes these checks even consume more lines-of-code space than the actual productive code they are protecting from harm. Such constructs make it easy to detect errors early on. But they make it even harder to undistractedly read through a piece of code.

Here is where Google’s general utility library Guava (formerly known as Google Collections) enters the scene. Besides bringing a whole bunch of utility goodness to the public, it also offers one particulary useful class to the interested programmer helping her alleviate the above mentioned problems with sanity checks:

com.google.common.base.Preconditions

This class provides a collection of static utility functions which you can use to write your parameter checks in a very concise way. They remove all the clutter as all conditional logic and Exception throwing is neatly tucked away in their method bodies.

For example, the following code

if (divisor == 0) {
    throw new IllegalArgumentException("Divisor must not be zero!");
}

can be compacted with Preconditions as below

import static com.google.common.base.Preconditions.*;
...
checkArgument(divisor != 0, "Divisor must not be zero!");

Writing sanity checks with Preconditions thus becomes very similar to writing JUnit assertions. Note that similar to JUnit’s assertTrue() method, with these check*()-functions you declare what you are expecting to be true, while the original if-condition will check for the negative of this expectation.

Null checks with Preconditions can even be used for invocation chaining as each null check function returns the instance of the checked object if it is non-null. So instead of writing

if (text == null) {
    throw new NullPointerException("The given String is null.");
}
if (text.length() > 20) {
    throw new IllegalArgumentException("The given text is too long: " + text);
}

you can write the following

checkArgument(checkNotNull(text).length() <= 20, "The given text is too long: %s", text);

which has the same effect.

For the most common types of Exceptions which are generally used for sanity checks, class Preconditions provides a function throwing that particular Exception when the predefined condition is not met. So, checkArgument() throws IllegalArgumentException, checkState() throws IllegalStateExceptions, checkNotNull() throws NullPointerExceptions, and checkElementIndex() and checkPositionIndex() throw IndexOutOfBoundsExceptions.

So as a conclusion, using the checks offered by Guava’s Preconditions class will help you keep your sanity checks as compact as possible and makes writing them a breeze.

To assert or not to assert

Then there are the well-known assert statements introduced by Java 1.4. They share the same properties as Guava’s Preconditions in that they make for a more compact code without too much clutter. So why not use them all over the place?

Assertions have been added to the Java language to provide a means to check particular internal preconditions that have to be fulfilled in a system. By that, they are very similar to the above mentioned sanity checks, yet they serve a slightly different purpose. Assertions are meant to support the software development process until to the point a piece of software is finished and can go into production. Assertions are usually inactive by default and have to be explicitly enabled during development time with Java’s -ea command line switch. Given that, using assertions for checking input parameter values of public interfaces is a bad idea. When not explicitly switched on, users of a library will not be informed of having used invalid parameter values when the underlying sanity checks are implemented using assertions. This will effectively render all your checks useless for the users of your code when they forget to enable Java’s assertion feature.

So, when should we use assertions and when should we write sanity checks with Preconditions? There is a general rule of thumb that can be applied for answering this question. Java’s assert keyword should only be used in places where there is no ‘user data’ to be checked. User data in this respect means data that is fed in by users of your public interfaces. As soon as you have to handle data that is passed in by callers of your public or protected methods, you should not use assert. If on the other hand you are working with purely private data (such as internal counters or index pointers) you should use assertions.

To boil it down, assert is for private purpose only. Exceptions may be made if you have public and protected interfaces that are unlikely to be used by external users, such as classes providing internal implementations. But note that even your team members working on the same code base as you count as external users in this context. They too want to be informed about an incorrect usage of your interfaces without having to remember enabling the assertion feature.

Veröffentlicht unter Java and Quality, Java Basics | Verschlagwortet mit , , , | Hinterlasse einen Kommentar

Mock SMTP-Server für Unit-Tests

Die meisten Enterprise-Anwendungen müssen mittlerweile in der Lage sein, E-Mails an Benutzer zu versenden. So ist es beispielsweise beim sog. Double Opt-in-Verfahren notwendig, dass der Benutzer einen Link aufruft, dem ihm zuvor per E-Mail zugesendet wurde, um so die Authentizität seiner E-Mail-Adresse zu gewährleisten. Dies ist ein gängiges Verfahren, das häufig nach der Registrierung eines Benutzers über eine Weboberfläche eingesetzt wird.

In immer größer werdenden Anwendungen spielen auch automatisierte Tests eine immer größere Rolle, da nur so dauerhaft und mit vertretbarem Aufwand eine hohe Qualität der Anwendung sichergestellt werden kann. Um den oben beschriebenen Workflow automatisiert zu testen, ist es sinnvoll auch den korrekten Versand der E-Mail und den darin enthalten Link zu prüfen.

Dumbster ist ein simpler SMTP-Server unter der Apache License 2.0., der sich einfach in einen automatisierten Test integrieren lässt und mit dem es anschließend möglich ist, den korrekten Versand von E-Mails innerhalb eines Unit-Tests zu prüfen. Der folgende JUnit-Test soll dies verdeutlichen:

public class UserServiceTest {

	private UserService userService;

	private SimpleSmtpServer smtpServer;

	@Before
	public void init() {
		userService = new UserService();
		smtpServer = SimpleSmtpServer.start(44444);
	}

	@After
	public void tearDown() {
		smtpServer.stop();
	}

	@Test
	public void testCreateUser() {
		userService.createUser("dumbster.test@oio.de");

		// Wurde die Double-Opt-In-Mail beim Anlegen des Benutzers korrekt versendet?
		SmtpMessage smtpMessage = ((SmtpMessage) smtpServer.getReceivedEmail().next());
		assertEquals("dumbster.test@oio.de", smtpMessage.getHeaderValue("To"));
		assertEquals("Account aktivieren", smtpMessage.getHeaderValue("Subject"));
		assertEquals("Bitte bestätigen Sie...", smtpMessage.getBody());
	}
}

Mit dem Aufruf von SimpleSmtpServer.start(44444) wird der SMTP-Server gestartet und nimmt anschließend alle E-Mails entgegen, die über SMTP an localhost auf Port 44444 gesendet werden. In diesem Beispiel wird davon ausgegangen, dass beim Anlegen eines Benutzer über userService.createUser(...) eine Aktivierungsmail an die übergebene E-Mail-Adresse gesendet wird, die anschließend geprüft werden muss. Auf die empfangenen Nachrichten des SMTP-Servers kann über smtpServer.getReceivedEmail() zugegriffen werden. Damit ist es unter anderem möglich die Empfänger-Mail-Adresse, den Betreff und den versendeten Text zu prüfen.

Veröffentlicht unter Java and Quality | Verschlagwortet mit , , , , , | 2 Kommentare

jshint-eclipse: JavaScript Code Quality Plugin for Eclipse

JavaScript has a lot of pitfalls, so it is very important to have a code analysis tool that detects errors and bad programming style.

jshint-eclipse is an Eclipse plugin that uses the static code analysis tool JSHint to analyze your JavaScript sources.

JSHint is a community-driven tool to detect errors and potential problems in JavaScript code and to enforce your team’s coding conventions.
It is very flexible so you can easily adjust it to your particular coding guidelines and the environment you expect your code to execute in.

Weiterlesen

Veröffentlicht unter Eclipse Universe, Java and Quality, Java Web Frameworks | Verschlagwortet mit , , , , , | Hinterlasse einen Kommentar

Confluence: Die Personel Sidebar in den privaten Bereichen ausblenden

In den persönlichen Bereichen kann jeder Confluence Benutzer als Space Administrator fast alles tun und lassen was er will.

Unter anderem ein beliebiges Thema/Layout aktivieren. Bei mir ist es das Documentation Theme. Allerdings durfte ich mich anschließend bei jedem Aufruf meines persönlichen Bereiches von der Personal Sidebar auf der rechten Seite nerven lassen.

Links der Seitenbaum und rechts die Personal Sidebar. Da bleibt nicht mehr viel Platz für Inhalte. Und außerdem: Ich weiß wie ich heiße und wie ich mich im Notfall erreiche!

Diverse Issues um den Status der Sidebar in den Einstellungen zu konfigurieren wurden seiten Atlassian leider nicht berücksichtig. Aber es gibt mehrere relativ einfach Lösung mittels CSS.

Und natürlich kann man die Personal Sidebar jedes mal mit einem Klick ein- und ausschalten. Aber auch das nervt.

Zum einen kann der Space Administrator folgenden CSS Code in die Stylesheets einfügen:

.has-personal-sidebar #content{
  margin-right: 0px;
}
div#personal-info-sidebar {
  display: none;
}

Dabei muss allerdings eine Voraussetzung erfüllt sein:
Die Confluence Administratoren müssen in der Security Configuration folgende Option aktiviert haben: “Enable Custom Stylesheets for Spaces”

Der Haken an der Sache: Jetzt haben wir das andere Extrem erreicht: Es gibt noch immer keinen Schalter mehr für die Sidebar und sie bleibt auf ewig verschwunden. Man sollte also zusätzlich noch einen Link auf die Profilseite anbieten.

Die Alternativen 2 und 3 setzen voraus, dass das HTML Macro aktiviert ist, was eher selten der Fall sein sollte:

Mit folgendem Wiki Markup/CSS Code kann dann a) in der Konfiguration des Documentation Themes oder b) auf einzelnen Seiten die Sidebar ausgeblendet werden:

{html}
  <style>
    .has-personal-sidebar #content{
      margin-right: 0px;
    }
    div#personal-info-sidebar {
      display: none;
    };
  </style>
{html}

Abschließend noch die Quelle: Remove Personal Sidebar from Documenation Theme

Veröffentlicht unter Atlassian Tools | Verschlagwortet mit , , , | Hinterlasse einen Kommentar

Mylyn WikiText – an Open-Source library for handling wiki markup

Mylyn is an Eclipse plugin and framework for task management. It’s subproject – Mylyn WikiText – provides an extensible framework and tools for parsing, editing and presenting wiki markup. It can be used standalone, integrated into your Java application without any dependencies to Eclipse.
WikiText is licenced under the Eclipse Public License Version 1.0 (“EPL”). Weiterlesen

Veröffentlicht unter Eclipse Universe | Verschlagwortet mit , , , , , , , , , | Hinterlasse einen Kommentar

Advancement in HTML Data specifications: New W3C notes

Embedding data / metadata in HTML opens traditional Web 2.0 development to Web 3.0 (aka semantic) technologies.

Well-defined terminologies in form of vocabularies (such as Dublin Core) or full-featured Ontologies (which can be constructed using meta languages such as RDF and OWL) provide the basis for a logically rich interoperability layer in the visible and unvisible Web.

Weiterlesen

Veröffentlicht unter Java Web Frameworks | Verschlagwortet mit , , , , , , | Hinterlasse einen Kommentar