Build WAR file with Maven and deploy with Ant

Minimalistic Ant script for Tomcat war file deployment.

This script first does a mvn clean and mvn install on the defined maven project. It then connects to the provided server, stops the running Tomcat, uploads the newly created .war file to the Tomcat’s webapp directory and starts the Tomcat again.

How to use

  • Adjust the property values in ant/build.xml to your needs
  • cd ant
  • Run ant

This script can be extended to support backing up any existing .war files, log files etc.

Alternative execution of mvn clean install

or under Windows

 

Stylight – Munich, Germany, Frontend Software Engineer interview

Pinterest layout

This coding-challenge was part of the interview process with Stylight (Munich, Germany) for a software engineer (frontend) role. Time frame was about 2 days.

Problem Statement

The problem statement can be found at here.

Pinterest layout

Examples illustrating a Pinterest like layout.

Example 1: CSS Only

Example 1

How to use

Include the neccesary Stylesheet file:

<link rel="stylesheet" type="text/css" href="styles.css" media="screen">

Include a simple div to hold the mosaic:

<div id="mosaic-container">

Demo

Demo Example 1

Example 2 & 3: JavaScript Example 2 & 3 implement a similar Pinterest layout as Example 1, but instead of using a pure CSS solution, they make use of pure JavaScript (except for the header and navigation controls). jQuery is not required.

Example 3 also includes a different header and provides a responsive navigation. That is, when the view port decreases in size, the top navigation disappears and a mobile friendly slide out navigation becomes available (see Example 3 illustration or test it using the available Demo Example 3).

Example 2
Example 3

How Mosaic works

The images are positioned dynamically by iterating through them and placing them at the bottom of whichever column has the shortest height at the moment. The column's height is then increased by the image's height (and some margins).

How to use Mosaic

Since Mosaic is purely JavaScript based, you only need to include the mosaic.js file:

<script type="text/javascript" src="mosaic.js"></script>

Include a simple div to hold the mosaic:

<div id="mosaic-container"></div>

Initialise Mosaic with an array of image paths:

<script>
  var mosaic = new JSMosaic('mosaic-container',['images/1.jpg','images/2.jpg','images/3.jpg','images/4.jpg','images/5.jpg','images/6.jpg', 'images/7.jpg','images/8.jpg','images/9.jpg','images/10.jpg','images/11.jpg','images/12.jpg']);
</script>

Public methods

addImage(path)

path

Type: String

path of image to add.

Demo

Demo Example 2

Demo Example 3

Full code
https://github.com/lucaslouca/pinterest-layout/

 

ThoughtWorks ‘Trains’ coding challenge

This coding-challenge was part of the interview process with ThoughtWorks for a software developer role. Time frame was about 3 days.

Trains

Commuter railroad service for the towns in Kiwiland.

Problem Statement

The local commuter railroad services a number of towns in Kiwiland. Because of monetary concerns, all of the tracks are 'one-way.' That is, a route from Kaitaia to Invercargill does not imply the existence of a route from Invercargill to Kaitaia. In fact, even if both of these routes do happen to exist, they are distinct and are not necessarily the same distance!

The purpose of this problem is to help the railroad provide its customers with information about the routes. In particular, you will compute the distance along a certain route, the number of different routes between two towns, and the shortest route between two towns.

Input

A directed graph where a node represents a town and an edge represents a route between two towns. The weighting of the edge represents the distance between the two towns. A given route will never appear more than once, and for a given route, the starting and ending town will not be the same town.

The towns are named using the first few letters of the alphabet from A to E. A route between two towns (A to B) with a distance of 5 is represented as AB5. A directed graph is represented by a list of routes, with each route as a separate line.

Available Actions - Compute the distance along a certain route. If no such route exists, output 'NO SUCH ROUTE'. Otherwise, follow the route as given; do not make any extra stops! - Compute the number of different routes between two towns. - Compute the shortest route between two towns.

Example Input & Output

Below follows an example with input data, actions performed and expected output result.

Sample Input:

AB5
BC4
CD8
DC8
DE6
AD5
CE2
EB3
AE7

Actions:

The distance of the route A-B-C.
The distance of the route A-D.
The distance of the route A-D-C.
The distance of the route A-E-B-C-D.
The distance of the route A-E-D.
The number of trips starting at C and ending at C with a maximum of 3 stops.  In the sample data below, there are two such trips: C-D-C (2 stops). and C-E-B-C (3 stops).
The number of trips starting at A and ending at C with exactly 4 stops.  In the sample data below, there are three such trips: A to C (via B,C,D); A to C (via D,C,D); and A to C (via D,E,B).
The length of the shortest route (in terms of distance to travel) from A to C.
The length of the shortest route (in terms of distance to travel) from B to B.
The number of different routes from C to C with a distance of less than 30.  In the sample data, the trips are: CDC, CEBC, CEBCDC, CDCEBC, CDEBC, CEBCEBC, CEBCEBCEBC.

Expected Output:

Output #1: 9
Output #2: 5
Output #3: 13
Output #4: 22
Output #5: NO SUCH ROUTE
Output #6: 2
Output #7: 3
Output #8: 9
Output #9: 9
Output #10: 7

Implementation

Requirenments

  • JDK 1.8
  • Gradle

Run JUnit Tests

To run the existing JUnit tests using Gradle, execute the following commands

$ cd path/to/Trains
$ gradle test

JUnit tests are located under /src/test/java.

Properties

Output messages are both availabe in English and German, depending on the system's default locale. The messages are available in the trains.properties and trains_de.properties file, respectively, and can be found under /src/main/resources/com/lucaslouca/.

Build

The project is a Gradle project. To build, open up your Terminal and fire up the following commands:

$ cd path/to/Trains
$ gradle build

You should see a 'BUILD SUCCESSFUL' message when everything went well. When the build completed succesfully, the program will be named Trains.jar and can be found under /build/libs/ in the Trains project directory.

Usage

Run the program as follows:

$ java -jar Trains.jar path/to/graph.txt path/to/commands.txt

Example

MacBook-Pro:Trains lucas$ java -jar build/libs/Trains.jar ../../graph.txt ../../commands.txt 
9
5
13
22
2
3
9
9
7
7

Import Project with an IDE

Import Project with IntelliJ IDEA

To import the project using Eclipse, do the following: - File -> New -> Project from Existing Sources from the main menu. - Browse to the project directory and click OK. - Select Gradle as build tool and click Next. - Specify Gradle home and make sure the Gradle JVM is set to version 1.8.x. - Click Finish.

Import Project with Eclipse

To import the project using Eclipse, do the following: - File -> Import... -> Gradle -> Gradle Project from the main menu. - Click Next. - Click Browse... for the Root Directory. - Select and open the Trains project. - Click Build Model. - Select all projects. - Click Finish.

Notes: - You may need Gradle Integration for Eclipse - Make sure to replace apply plugin: 'idea' with apply plugin: 'eclipse' in the build.gradle file located in project's root directory.

JavaDoc

JavaDoc can be found in the here.

Important Classes & Interfaces

Main

The Main class is the main entry point of the application. It contains a main() method whose signature looks like this

public static void main(String args[])

which the runtime system calls when the program starts. The main() method then calls all the other methods required to run the application. It takes two arguments. The first argument is the path to the file containing the Town Graph, while the second argument points to the file containing the commands we want our application to execute.

LLDirectedGraph<T>

LLDirectedGraph represents a generic directed graph. It provides basic functionality for adding nodes and edges as well as methods for computing the shortest path (Dijkstra) and distance between nodes.

LLTownMap

The LLTownMap interface represents a map that stores towns using a LLDirectedGraph underneath. It wraps the functionality of LLDirectedGraph and provides methods for accessing it using the town names.

LLTown

Model representing a town.

LLRailRoadServiceImpl

LLRailRoadServiceImpl implements the LLRailRoadService interface. It makes use of LLTownMap. Although most of the functionality in LLRailRoadServiceImpl is cascaded to LLTownMap, the idea of providing LLRailRoadServiceImpl, is to separate the functionality between a service system and a map. That is, LLRailRoadServiceImpl could be expanded to support further functionality such as requestClosingHours() or nextTrainDepartureTime() without the need to modify the LLTownMap.

LLCommand

Interface defining a command that can be executed by calling its execute() method. A typical command would be calculating the distance of a route.

LLCommandFactory Interface that defines which functionality an LLCommand factory must provide.LLCommandFactory provides functionality for creating new commands that implement the LLCommand interface.

LLRailRoadServiceCommandFactory This class implements the LLCommandFactory interface. It provides methods for creating concrete command implementations of the abstract type LLAbstractRailRoadServiceCommand. The LLRailRoadServiceCommandFactory gets initialised with an LLRailRoadService, which it sets as receiver in LLAbstractRailRoadServiceCommand instances:

LLCommandFactory commandFactory = new LLRailRoadServiceCommandFactory(service);

Classes inheriting from LLAbstractRailRoadServiceCommand are commands that implement the LLCommand interface but are specifically implemented for the LLRailRoadService. An example would be the LLDistanceCommand.

LLCommandProccesor

LLCommandProccesor executes LLCommand commands. The LLCommandProccesor gets initialised with an LLCommandFactory.

LLCommandProccesor processor = new LLCommandProccesor(commandFactory);

The LLCommandFactory will then be used by LLCommandProccesor to create LLCommand objects for a given input. LLCommandProccesor can take and execute a single command in the form of text:

String result = processor.run("distance;A;D"); // compute distance between node 'A' and 'B'

or run all commands contained in a text file:

String result = processor.runAll("/Users/lucas/commands.txt"); // execute all commands in commands.txt

Available commands

  • distance;[TOWN 1];[TOWN 2]; ... ;[TOWN N] - Compute distance of route. Example:
distance;A;B;C
  • count_routes_with_max_hops;[START TOWN];[DESTINATION TOWN];[MAX HOP COUNT] - Count routes with maximum number of hops. Example:
count_routes_with_max_hops;C;C;3
  • count_routes_with_hops;[START TOWN];[DESTINATION TOWN];[HOP COUNT] - Count routes with exact number of hops. Example:
count_routes_with_hops;A;C;4
  • count_routes_with_max_distance;[START TOWN];[DESTINATION TOWN];[MAX DISTANCE] - Count routes with maximum distance. Example:
count_routes_with_max_distance;C;C;29
  • length_of_shortest_path;[START TOWN];[DESTINATION TOWN] - Compute length of shortest path between node. Example:
length_of_shortest_path;A;C
  • shortest_path;[START TOWN];[DESTINATION TOWN] - Compute shortest path between nodes. Example:
shortest_path;B;B

LLPropertyFactory

Provides static methods for global access to the application's properties.

Sample Data

Sample data for a graph and commands can be found here.

Full code
https://github.com/lucaslouca/Trains

 

Understanding the contentOffset and contentInset properties of the UIScrollView class

In order to better understand the purpose of these two properties, it is important that we understand the contentSize property. The scroll view must know the size of the content view. This is important because the size of the content view can be larger than the visible area (example: screen) and the scroll view needs to know when to stop scrolling.

Take a look at the image bellow. The content view is marked using ‘#’ where as the scrollable area (example: screen) is marked using ‘-‘:

contentOffset
As you can clearly see, the content that we want to display in the scroll view doesn’t entirely fit in the scrollable area so we need to scroll in order for us to view the content.

The Apple documentation describes contentOffset as follows:
var contentOffset: CGPoint
“The point at which the origin of the content view is offset from the origin of the scroll view.”

In other words it defines the point in the content view that is visible at the top left of the scroll view bounds. We can use this property to scroll programmatically .

So for example:

contentInset
The Apple documentation describes contentInset as follows:
var contentInset: UIEdgeInsets
“The distance that the content view is inset from the enclosing scroll view.”

In other words it is the distance that the content view is inset from the enclosing scroll view (padding). So, if you want to add more scrollable space at the bottom or at the top, you can use the property contentInset.top and contentInset.bottom, so you can add some extra space without changing the content size. It is important to note that through the contentInset we add more scrollable space. So an contentInset.top = 10 will add an extra space of 10 at the top. One way to think of it is “how much to shift the content down the scroll view when we’re scrolled all the way to the top”. When we scroll down this padding also scrolls along with the rest of the content.

References
Creating and Configuring Scroll Views

UIScrollView Class Reference

 

Landscape launch image on iPhone

In this article I will describe how to add landscape launch images to your iPhone app. Landscape launch images are only supported on iPad apps (Apple Documentation).

Bellow I have listed the steps in order to circumvent this issue and add landscape images to your iPhone app.

Step 1: Add the Landscape Launch image(s) to your project

Provide the following images (just copy them to your project):
Default.png (320×480)
Default@2x.png (640×960)
Default-568h@2x.png (640×1136)

Landscape launch image iPhone (640x1136)

Landscape launch image iPhone (640×1136)

Apple doesn’t have landscape launch image for iPhone or iPod, so we need to provide rotated 90 degree of landscape image.

Just for the reference the iPad images would be:
Default-Landscape@2x~ipad.png
Default-Landscape~ipad.png

Step 2: Don’t use asset catalogs

Go to your project’s settings -> General -> Launch Images and choose Don’t use asset catalogs.
Xcode should have automatically detected the images from Step 1. If not select them manually.

References

https://www.idev101.com/code/User_Interface/launchImages.html

 

Implement a Game Center leaderboard (iOS 7)

This tutorial will teach you how to implement a Game Center leaderboard in an iOS 7 app.

Step 1: Importing the GameKit Framework

Assuming you have an existing project you need to import the GameKit Framework. This can be easily done by selecting the project name and under General->Linked Frameworks and Libraries click on the “+” button and search for GameKit.framework. Select the framework and click on “Add“.

Step 2: Create an App ID

Next we need to create an App ID for the app in iOS Dev Center. So, log into your iOS Dev Center account and go to “Certificates, Identifiers & Profiles“. Under “iOS Apps” choose “Identifiers” and click on the “+” button to create a new App ID.

Fill out the App ID Description name and Bundle ID. Game Center should be enabled by default under App Services. When finished click “Continue” and then “Submit”

Step 3: Add the new App in iTunes Connect

Log in into your iTunes Connect account and navigate to “Manage Your Applications“.

Click on “Add New App” (Upper left corner) in order to create a new App.

Fill out the App Information form (Default Language, App Name, SKU Number), select the Bundle ID from Step 2 and click “Continue“.

Select your Availability Date and Price Tier and click “Continue“.

Next you need to fill out Information about the Version such as Version Number, Copyright, etc.

You also need to have a Large App Icon that must be at least 72 DPI, in the RGB color space, and 1024 x 1024 pixels. You can use the dummy icon provided for this tutorial. Screenshots for the 3.5-Inch Retina Display and 4-Inch Retina Display iPhone must also be provided. Screenshots for 3.5-inch iPhone and iPod touch Retina display must be 960×640, 960×600, 640×960 or 640×920 pixels, at least 72 DPI, in the RGB color space, and in the JPG or PNG format. Screenshots for 4-inch iPhone 5 and iPod touch (5th generation) Retina display must be 1136×640, 1136×600, 640×1136 or 640×1096 pixels, at least 72 DPI, in the RGB color space, and in the JPG or PNG format. Again you can use my dummy screenshots: 640×920 and 640×1096. After filling out all the necessary information click on “Save

Step 4: Create a Leaderboard

Back in the App overview click “Manage Game Center“. Next click “Enable for Single Game” to enable Game Center for our new App.
Next we want to setup a Leaderboard by clicking on “Add Leaderboard” in the “Leaderboards” section. Choose single Leaderboard and fill out the Leaderboard Reference Name, Leaderboard ID, Score Format Type, Score Submission Type, Sort Order and optionally Score Range.

The Leaderboard Reference Name is just an internal name. Just name it “Your-App-Name Leaderboard”. The Leaderboard ID is a is a unique alphanumeric identifier. You can use the ID “1”. Score Format Type is just the format that you use to express the score within your game. Choose “Integer”. For the Sort Order choose “High to Low” if you want highest scores displayed first and “Low to High” if you want lowest scores displayed first. The Score Range can be left blank.

Next we need to add a language by clicking on “Add Language“.
Choose English for the Language. The Name is the name of the Leaderboard displayed in Game Center. Set it to “Leaderboard”. Again choose “Integer” for the Score Format. Leave the Score Format Suffix (Singular), Score Format Suffix Plural and Image fields blank. Click “Save” and then “Save” again. After saving click “Done

Step 5: Set the Bundle ID in your project

Go to your Xcode project and open the file named [Your Projet name here]-Info.plist and under Bundle identifier insert the Bundle ID you have created in Step 3.

Step 6: Import the GameCenterManager class files

Next download the GKTapper sample project provided by Apple. We will use the following Class Implementations and Interfaces:

  • GameCenterManager.h
  • GameCenterManager.m
  • AppSpecificValues.h

You can download the modified for iOS 7 files here.

Drag the above files into your project and make sure you check “Copy Items into destination group’s folder (if needed)” and then “Finish“.

Annotate your class in which you want to use Game Center (in my case it is called MyScene), that it conforms to the GKGameCenterControllerDelegate and GameCenterManagerDelegate protocol. So just edit MyScene.h:

Step 7: Adding the code: authenticate the local user

In MyScene.m insert the following code:

This will create a new GameCenterManager object and authenticate the local user with Game Center.

Step 8: Adding the code: submit score to leaderboard

The next thing we want to do is to submit a score to the leaderboard.

Just insert the following code anywhere where you want the score to be submitted to the leaderboard.
reportScore takes two parameters: an int64_t representing the score and a
NSString* representing the leaderboard ID from Step 4.

Step 9: Adding the code: display the highscores/leaderboard

For this step you can insert a button that the user touches in order to display the leaderboard. In the action
you can just insert the following code to display the leaderboard:

Also don’t forget the following GKGameCenterControllerDelegate method to dismiss the Game Center view controller when the user is done interacting with it:

 

Interstitial ads iPhone using the iAd framework

In this tutorial I will briefly explain several methods for adding interstitial ads iPhone in your iOS 7 App using the iAd framework. The example I will be working on is a small game implemented in Apple’s SpriteKit framework.

The tutorial assumes that you have already created a new App in iTunes connect and have already enabled iAd Advertising.

Using the old API

Using the old specification the ADInterstitialAdDelegate protocol must be implemented, lets say by a UIViewController subclass so that your application can respond to changes in an ADInterstitialAd object. An ad object calls its delegate whenever the state of the ad changes.

I will implement this protocol in my ViewController that controls the views/scenes of my game. So the ViewController.h file will look like follows:

In addition I have added a method -(void)showFullScreenAd that can be called from outside the ViewController anytime we want to display a new ad. A typical scenario in my game goes like so:
– The user starts playing the game
– The user either wins or looses
– The GameOver scene gets displayed

So I want my ads to be displayed just before the GameOver scene gets presented. So a typical scenario would be to call the ViewController’s -(void)showFullScreenAd after the GameOver’s scene content gets created.

In my ViewController.m file I have added the following:

and for the protocol and interface implementation the following methods have been implemented:

So every time I call -(void)showFullScreenAd, a new ADInterstitialAd gets created. After the ad object is created, it automatically downloads an advertisement from the iAd App Network. When the ad object finishes downloading the advertisement, it signals your delegate. Your app takes the loaded ad and presents it to the user. The actual process your app uses to present the advertisement varies depending on whether you want to present it modally or as a modeless page.

In this tutorial I will present the Ad as a Page of Content mainly for two reasons:
1. Presenting an Ad Modally using [_interstitial presentFromViewController:self] is deprecated since iOS 7.
2. Presenting an Ad Modally using [_interstitial presentFromViewController:self] doesn’t take into consideration the device orientation. It always displays the add in portrait mode.

So again, I will present my ad as a Page of Content by calling the ad’s presentInView: method as soon as the Ad is loaded.
The good thing about this method is that device orientation is taken into consideration. The downside is that the presented ad doesn’t have a close button and so the user needs to terminate the entire app to get rid of the Ad. I don’t know why the iAd framework would provide something in such a state.

So here is the delegate implementation that also adds a close button and some fancy animations for showing and hiding the ad:

Using the new API

The new API doesn’t require the call of presentInView: or presentFromViewController:. It also does not require the implementation of the ADInterstitialAdDelegate protocol. All we need to do is to call the following implementation of the showFullScreenAd method:

The downside is that the device orientation isn’t taken into account and the ad is always displayed in portrait mode. Also we have no control what so ever what happened with the Ad (finish loading, etc) since no delegate implementation is being done.

References

https://developer.apple.com/library/ios/documentation/iAd/Reference/ADInterstitialAd_Ref/Introduction/Introduction.html

https://developer.apple.com/library/ios/documentation/iAd/Reference/UIViewController_iAd_Additions/Reference/Reference.html

https://developer.apple.com/library/ios/documentation/userexperience/conceptual/iAd_Guide/Full-ScreenAdvertisements/Full-ScreenAdvertisements.html