An Introduction to Checkstyle


Checkstyle is a tool that can be used by developers in order to help teams follow coding conventions on a Java project. I recently used this whilst developing a Battleships game in Java with a group of others as part of a university module (maybe a post for another day?..).

Why use Checkstyle?


Coding conventions and standards are a way to ensure that code is formatted consistently across a project, team or organisation. The benefits of using them are pretty well known and well documented but it essentially comes down to making the code more readable and accessible to yourself and other developers.

Checkstyle helps developers to follow a coding convention by pointing out errors or warnings within the IDE based on an XML configuration file that you provide in the project. The configuration file’s format is well documented, easy to read and easy to edit. On our project we chose to base our standards on Google’s guidelines (google_checks.xml) which we then adapted to suit our own coding style (checkstyle.xml). We also used Travis CI to build our project each time someone pushed new code and if compilation and tests passed then we would get a notification in our team’s Slack channel, similarly if anything went wrong we would get a notification to let us know we needed to fix something. As we were using Checkstyle with the Maven plugin this meant that if code was committed which didn’t comply with our standards then the build would fail1.

How to install & use Checkstyle


Installing and getting Checkstyle to work with Maven initially took a few attempts and gave quite the headache but I put that down to my lack of experience with Maven and in the end it was worth it. I’m hoping that by documenting the process here others will be able to save time by not having to follow my process of trial and error!

Maven

In the pom.xml put the following block of code into the <plugins> section.

<plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-checkstyle-plugin</artifactId>
	<version>2.17</version>
	<executions>
		<execution>
			<id>validate</id>
			<phase>validate</phase>
			<configuration>
				<encoding>UTF-8</encoding>
				<configLocation>checkstyle.xml</configLocation>
				<consoleOutput>true</consoleOutput>
				<failsOnError>true</failsOnError>
				<linkXRef>false</linkXRef>
			</configuration>
			<goals>
				<goal>check</goal>
			</goals>
		</execution>
	</executions>
	<dependencies>
		<dependency>
			<groupId>com.puppycrawl.tools</groupId>
			<artifactId>checkstyle</artifactId>
			<version>7.6</version>
		</dependency>
	</dependencies>
</plugin>

Note – the configLocation field can be removed and Checkstyle will use the default config (sun_checks.xml) but as mentioned earlier on our project we used a custom configuration and simply named it “checkstyle.xml” in the root of our project.
It’s also worth mentioning the dependencies section where we explicitly tell Maven to use version 7.6. Without this section Maven will use version 6.11.2. This was something I only solved recently but it prevented us from using some of the newer checks available during development.

After setting up the configuration file (or choosing to use the default) running ‘mvn validate’ in the command line should give you the following output.

...
[INFO] --- maven-checkstyle-plugin:2.17:check (validate) @ Battleships ---
...

Below that line you will see a list of errors or warnings if your code does not follow the defined convention.

That’s it, your project is now set up to run Checkstyle with Maven!

Eclipse

There is also an Eclipse Checkstyle Plugin available for Checkstyle which will allow Eclipse to display errors and warnings to the user in the ‘problems’ tab. This makes it easy for developers to see jump to the offending pieces of code and fix it to comply with the coding standards in the configuration file.

Checkstyle throwing a variety of errors in Eclipse.
Checkstyle throwing a variety of errors in Eclipse.

Happy Coding!


1 The severity of “non-compliance” could be configured to either throw a warning or an error based on which rule had been broken. For example a line length of greater than 100 may throw an error but an extra whitespace somewhere may just cause a warning.

 

An Introduction to MuleSoft Anypoint Studio

What is Anypoint Studio?


Anypoint studio is a tool for building integrations & APIs for systems. it is based on eclipse (the popular open source Java IDE) so provides a familiar environment for many. It is a graphical tool which has a low learning curve and makes it easy to build integrations. Connectors, as the name suggests, are the part in a “flow” which actually connects to a system and extract or import data. There are many built-in connectors such as Salesforce, databases, ftp and even Facebook & Twitter. It is also possible to download more that have been built by the community from the Anypoint Exchange or develop your own if what you need isn’t available. The following guide shows just how quick and easy it is to create a MuleSoft application which grabs data from a system and transforms it before sending it to a different system.

Creating a basic app – Salesforce to HTTP


Mule Anypoint – Salesforce Flow

The flow that we will create will return data from Salesforce (Accounts in our example) to the browser in JSON when visiting http://localhost:8081/salesforce.demo

  1. Create a new Mule project (File -> New -> Mule Project).
  2. In the right panel search for “HTTP” and drag the result across into the main area, do the same for “Salesforce”, a “DataMapper” and a “Logger” so it looks like the image above. We now have the basic outline of our flow so it’s time for some configuration.
  3. First click on the HTTP connector that we have put in the flow and click the plus next to connector configuration in the panel at the bottom. Enter “salesforcedemo” in the base path field and click ok. Note – If you are running something else on port 8081 then you will need to  change that setting to a different port.
  4. Create a (free) developer Salesforce account, add some Account records and then do the same as above with the Salesforce connector, choose basic authentication, enter your account credentials (you will need to request a security token in Salesforce and enter that) and test connection. Assuming it succeeded, hit okay twice and back in the bottom panel next to operation choose “Query” from the drop-down box and enter the following: SELECT Name,Phone,Type FROM Account.
  5. Next we need to look at the DataMapper which takes data in one format and converts it into a different format as it says on the tin. In our case we want to transform the Salesforce data we have received into a JSON format and output that to the browser. In the configuration for this component we have 2 parts – Input & Output. The input side should automatically detect the Salesforce object we are grabbing but we will need to configure the output. Next to Type choose JSON, select From Input -> Copy Structure. Then click Create Mapping.
  6. In the logger configuration simply enter #[‘Sending to browser’] in the Message field.

Finally run the application by right-clicking the project in the left hand side browser -> Run-As -> Mule Application. When you see the word DEPLOYED in your console that means your application should now be running and if you visit http://localhost:8081/salesforcedemo you should retrieve a JSON view of all the accounts in your Salesforce environment.

 

How to mass unfollow on Twitter!

Yesterday, I wanted to unfollow everyone on an old account on Twitter. When searching Google for a tool to do this for me I found the ones that existed either weren’t very good or wanted a fee to do it (the tools that required a fee had many other options and features such as only unfollowing people who aren’t following you). After trying a couple of the tools I still had not managed to unfollow all the users I was following so decided to try and find my own solution and here it is:

1) Login to Twitter and click Following.

2) Scroll down to the bottom until everyone your following has loaded (Tip: press the end button to get to the bottom quicker).

3) Open up your browser console (CTRL + SHIFT + J for Chrome).

4) Copy & Paste the following Javascript and hit enter:

var el= document.getElementsByClassName('button-text unfollow-text');
for(var i=0; i<el.length; i++){
    el[i].click();
}

5) Wait a second or two depending on how many users you are following.

Done!

Apps for Good

 

Today I spent my time reviewing and discussing mobile application ideas from 1000’s of school children, from 213 schools (and counting!) across the country. The scheme is called Apps for Good and is run with the intention of teaching 10-18 year olds problem solving, basic programming, and creativity among other skills through technology.

How does it work?


The schools involved are provided with the course content, training and connections with the “Expert volunteers”. From here the children will split up into groups and have to come up with an idea for a unique mobile application. From this idea they will make a video pitch , a slideshow describing the idea and wireframes showing how they intend the application will look and be navigated. The groups are then able to have a session with an “Expert” which consists of a video call over Skype where the idea can be screened, questions can be asked and feedback can be given.

The groups can then submit their app ideas to Apps for Good who will then begin to filter through the ideas narrowing them down from hundreds to just 6. The groups behind the six ideas are then invited to London to give a Dragons Den style pitch to judges. The winning idea will then be fully produced and made available on the app store!

Previous winning apps can be seen here.

How can you get involved?


There are many ways to get involved in Apps for Good, the most accessible way would be by becoming an Expert like myself. There are many different areas to pick from in terms of what your area of expertise are from technically feasibility to user experience. Once you have successfully signed up you will begin to receive session requests which is where you would spend an hour of your time on Skype talking to a group who would like some advice, and feedback on their ideas. If you are an employee or member of a corporate partner of Apps for Good you may get the chance to have a session of reviewing all the apps submitted.

The most valuable way of getting involved would be to spread the word and let as many people you know about the scheme including schools, organisations and people in the mobile/technology industry.

For more information on getting involved visit: Get Involved.


Overall, Apps for Good is a great programme for bringing better and more technology education into schools. I had a great time seeing the ideas that some of the groups had come up with and how enthusiastic and passionate they were about them!

Java Sudoku Solver

I have just uploaded a program I wrote a couple of weeks ago to GitHub. The program is a sudoku solver which I wrote in Java. I am also posting the source code below.

Usage
The program reads the sudoku from a text file called “Sudoku.txt”. Which should be formatted like so:

860020000
000700059
000000000
000060800
040000000
005300007
000000000
020000600
007509000

Where the 0s are the blanks in the given puzzle. The program will then print the solution to the command line.
When input the puzzle above:

Sudoku Solver

Here is the source code:

import java.util.Scanner;
import java.io.File;

public class SudokuSolver
{
  public static void main(String[] args) throws Exception
  {
    Scanner fileScanner = new Scanner(new File(&quot;Sudoku.txt&quot;));

    int[][] sudoku = new int[9][9]; //Will hold the puzzle in a 2D array.
    //We will use this variable to hold the next line of the puzzle, then parse
    //each digit on that line.
	String line = fileScanner.nextLine();

    //Loops round placing the digits into the correct place of the array.
	for (int y = 0; y &lt; 9; y++)
	{
	  for (int x = 0; x &lt; 9; x++)
	  {
        //Gets the digit converts it from a char to an in and places it in the array.
        sudoku[y][x] = Character.getNumericValue(line.charAt(x));
        //At the end of each line we load the next line, but check there is a next
        //line before trying to load it so the program does not crash.
	    if (x == 8 &amp;&amp; fileScanner.hasNextLine())
		{
		  line = fileScanner.nextLine();
		}
	  } //for x
    } //for y

    //The recursive function that actually solves the sudoku (starting at 0,0)
    solve(sudoku, 0, 0);

  } //main

  //This is a recursive function used to go through each cell and place a valid number.
  //Until they are filled in.
  private static void solve(int[][] sudoku, int cellX, int cellY)
  {
    //If the y value is 9 then the sudoku has been solved.
    if(cellY &gt; 8)
    {
      printSudoku(sudoku);
      System.out.println();
      //System.exit(1); // = This will end the program quicker as it does not have to
      //&quot;go back up&quot; through the levels of recursion, but means the main
      //routine will not continue running.
      //Also if there is more than one solution to the sudoku using this will only print
      //the first solution found.
    }
    else
    {
      //Here we calculate the next digit for the solve routine to try.
      int nextX = cellX;
      int nextY = cellY;
      if(cellX == 8)
      {
        //When at the end of a row add 1 to the row and reset the &quot;column&quot; to 0.
        nextX = 0;
        nextY++;
      }
      else
      {
        nextX++;
      }

      //If the digit was already given to us, we can move onto the next one.
      if(sudoku[cellY][cellX] != 0)
      {
        solve(sudoku, nextX, nextY);
      }
      else
      {
        //Otherwise, starting at 1 through 9 we check if the number is &quot;legal&quot;
        //and if so place that number, and move on to the next cell.
        for(int checkNum = 1; checkNum &lt; 10; checkNum++)
        {
          if(checkSquare(sudoku, cellX, cellY, checkNum)
             &amp;&amp; checkRow(sudoku, cellY, checkNum)
             &amp;&amp; checkCol(sudoku, cellX, checkNum))
          {
            sudoku[cellY][cellX] = checkNum;
            solve(sudoku, nextX, nextY);
          }
        }
        //If we get to here it means in it's current state the sudoku is impossible
        //which means that one of the numbers we &quot;placed&quot; earlier is incorrect.
        sudoku[cellY][cellX] = 0;
      }
    }
  }

  //This method is given a cell location and a number to check, it then checks
  //whether that number is already in the 3x3 square and returns false if so.
  private static boolean checkSquare(int[][] sudoku, int reqX, int reqY, int toCheck)
  {
    int rowY;
    int colX;

    //First we work out which column the &quot;square&quot; belongs to.
    //We take the given x value and if it is below 3 then that means
    //the square we need is in the first column (out of 3). etc.
    if(reqX &lt; 3)
    {
      colX = 0;
    }
    else if (reqX &lt; 6)
    {
      colX = 3;
    }
    else
    {
      colX = 6;
    }

    //We do the same but for the rows. For example if the y value is 5 then
    //the related square would be on the second row.
    if(reqY &lt; 3)
    {
      rowY = 0;
    }
    else if (reqY &lt; 6)
    {
      rowY = 3;
    }
    else
    {
      rowY = 6;
    }

    //We have now defined the square we need to check and have the top left
    //co-ordinate stored in the variables rowY and colX.
    //We now loop round and check each digit in the square, and if a digit matches
    //we return false.
    for(int y = rowY; y &lt; rowY + 3; y++)
    {
      for(int x = colX; x &lt; colX + 3; x++)
      {
        if(sudoku[y][x] == toCheck)
          {
            return false;
          }
      }
    }

    return true; //number not in the square.

  }

  //Checks if a given number is in a given row and returns false if it is.
  private static boolean checkRow(int[][] sudoku, int rowY, int toCheck)
  {
    //loops round each digit in a row.
    for(int x = 0; x &lt; 9; x++)
    {
      //Checks if the given number is the same as the current digit
      //and returns false if so.
      if (toCheck == sudoku[rowY][x])
      {
        return false;
      }
    }
    return true; //the number is not in the row.
  }

  //Checks if a given number is in a given column and returns false if it is.
  private static boolean checkCol(int[][] sudoku, int colX, int toCheck)
  {
    //Loops round each digit in a column.
    for(int y = 0; y &lt; 9; y++)
    {
      //Checks if the current digit is the given digit and returns false if so.
      if (toCheck == sudoku[y][colX])
      {
        return false;
      }
    }
    return true; //the number is not in the column.
  }

  //Prints the sudoku to the screen.
  private static void printSudoku(int sudoku[][])
  {
    //Loops round each digit and prints it.
    for(int y = 0; y &lt; 9; y++)
	{
	  for(int x = 0; x &lt; 9; x++)
	  {
	    System.out.print(sudoku[y][x]);
	    //Starts a new line when at the end of a row.
        if(x == 8)
		{
		  System.out.println();
		}
	  } //for x
	} //for y
  } //printSudoku
} //SudokuSolver