girlcoderuk











I have been reading a lot of blogs all about why you should not use TDD and why it is a bad idea. I would like to put forward my viewpoint on the arguments.

Premise: TDD restricts your design abilities.
If you believe this then you do not get TDD or Agile development. Early in your Agile life you should have been to a sprint planning meeting, writing cards and then ripping them up… TDD is the same, if you get down the path and find it going the wrong way. Rip it up, start again. That goes for TDD tests as well as code. Software is an organic construct TDD is designed to keep it tame and not a huge lumbering beast destroying your city. If the design changes it makes sense to change the test as well.

Premise: We have legacy code which do not have tests.
Well you are in a bad way, however that is not the end of the world. Each time you get a bug, write a test to prove when the bug is gone. Not only does this prove that the bug is gone it also prevents regression and the bug reappearing in the future. As the bugs get squashed you get new tests and the coverage of the legacy code improves. This follows one of the other agile methods which is when you touch a piece of code you always leave it in a better state than when you found it, if you are working under the hood of the ecommerce module and you see a nasty if then else mess clean it up, if you see repeated code extract it. Over time your code is cleaner and you can then add tests around any new code until you have more coverage.

Premise: it takes longer to write tests before why can’t I add them after?
You are working in a business. There is never time for code cleanup, you will never get the chance to add the tests after. If you write the tests up front using BDD style naming you can also show the results to the business owner who can see you have produced their request and can prove it. Simple to sign off and any smart head of business will start to push other devs to follow your lead as they know that your code is fit for purpose.

Premise: Sometimes the design changes after you have started meaning changing the tests
What’s wrong with that? Isn’t that the idea for Agile development, tests are never immutable, sure you need to be sure that a change to a test is justified (you have added new functionality or made a new field mandatory breaking older tests that now need updating)
It’s more a way of making you think about the change you are doing, and the design you are using. Is it fit for purpose?

These are just my views and I am sure that everyone has different feelings about TDD and Agile development. As with most Agile methodologies it is a guideline not a rule,



This article is designed to fill a gaping hole in the Examples for Spring / Hibernate configuration and that is for Standalone Applications.

Usually all the demonstrations are for Web applications or J2EE applications, so this one is for a simple Command Line Application. I use Intellij Idea and Maven but i hope it works as easily if you are using Netbeans or Eclipse.

Ok Lets start out Easily:

Create a new Maven Project with no Archetype

<?xml version=”1.0″ encoding=”UTF-8″?>
<project xmlns=”http://maven.apache.org/POM/4.0.0″
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”>
<modelVersion>4.0.0</modelVersion>

<groupId>com.github.theresajayne.standaloneexample</groupId>
<artifactId>standaloneExample</artifactId>
<version>1.0-SNAPSHOT</version>
</project>

Idea will have created the pom file but nothing else do under src/main/java add a package for your system (mine is com.github.theresajayne/standaloneexample) and create a main class under there to match your project name

package com.github.theresajayne.standaloneexample;

public class StandaloneExample {
}

now lets return to the pom file, We need to add the Spring, Hibernate and MySQL libraries to the project and then rebuild to make it download all the dependencies. This is a simple copy/paste task so my complete pom file is below.

<?xml version=”1.0″ encoding=”UTF-8″?>
<project xmlns=”http://maven.apache.org/POM/4.0.0″
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”>
<modelVersion>4.0.0</modelVersion>

<groupId>com.github.theresajayne.standaloneexample</groupId>
<artifactId>standaloneExample</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<spring.version>3.2.3.RELEASE</spring.version>
<hibernate.version>4.2.2.Final</hibernate.version>
</properties>

<dependencies>
<!– Spring –>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>

<!– Hibernate –>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>

<!– Others –>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
</dependency>

</dependencies>

</project>

Now we have the project building lets add some configuration files.

under src/main/resources we need to make the spring configuration  file. So create spring-config.xml

<?xml version=”1.0″ encoding=”UTF-8″?>
<beans xmlns=”http://www.springframework.org/schema/beans” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xmlns:context=”http://www.springframework.org/schema/context” xmlns:tx=”http://www.springframework.org/schema/tx”
xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd “>
<context:annotation-config/>
<context:component-scan base-package=”com.github.theresajayne.standaloneexample”/>

<!– JDBC Data Source. It is assumed you have MySQL running on localhost port 3306 with
username root and root as password. Change below if it’s not the case –>
<bean id=”myDataSource” class=”org.apache.commons.dbcp.BasicDataSource” destroy-method=”close”>
<property name=”driverClassName” value=”com.mysql.jdbc.Driver”/>
<property name=”url” value=”jdbc:mysql://localhost:3306/standalone”/>
<property name=”username” value=”root”/>
<property name=”password” value=”root”/>
<property name=”validationQuery” value=”SELECT 1″/>
</bean>

<!– Hibernate Session Factory –>
<bean id=”mySessionFactory” class=”org.springframework.orm.hibernate4.LocalSessionFactoryBean”>
<property name=”dataSource” ref=”myDataSource”/>
<property name=”packagesToScan”>
<array>
<value>com.github.theresajayne.standaloneexample</value>
</array>
</property>
<property name=”hibernateProperties”>
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.hbm2ddl.auto=update
</value>
</property>
</bean>

<!– Hibernate Transaction Manager –>
<bean id=”transactionManager” class=”org.springframework.orm.hibernate4.HibernateTransactionManager”>
<property name=”sessionFactory” ref=”mySessionFactory”/>
</bean>

<!– Activates annotation based transaction management –>
<tx:annotation-driven transaction-manager=”transactionManager”/>

</beans>

This now is all we need on configuration boilerplate code as the rest is all done via annotations.

Now back to the Main class of the application. We start off the file looking like this

package com.github.theresajayne.standaloneexample;

public class StandaloneExample {

public static void main(final String[] args) throws Exception {

}
}

First we need to annotate the whole class with @Component This as you will see will allow us to create the main class using Spring, next we add the main code providing us with the following

package com.github.theresajayne.standaloneexample;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class StandaloneExample {

public static void main(final String[] args) throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext(“spring-config.xml”);
StandaloneExample standalone = ctx.getBean(StandaloneExample.class);
standalone.startStandalone();
}
}

If you are using an IDE you will see the startStandalone() method is currently Red meaning that it is not there, so if you can use your ide tools to create it.

Next we will create the Dao and allow it to create a table in the preexisting standalone schema in the database (if you have not created the schema then you will need to.

Under the standaloneexample package create a new package called model.beans, then create StandaloneVO inside. Annotate the class as @Entity and @Table(name=”standalone”) within the class add and id with the @Id and @GeneratedValue annotations then add any other fields you wish on your object.remember to make them private with public getters and setters.

package com.github.theresajayne.standaloneexample.model.beans;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;

@Entity
@Table(name=”standalone”)
public class StandaloneVO {

@Id
@GeneratedValue
private long id;
private String name;
private double amount;
private Date created;

public long getId() {
return id;
}

public void setId(long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public double getAmount() {
return amount;
}

public void setAmount(double amount) {
this.amount = amount;
}

public Date getCreated() {
return created;
}

public void setCreated(Date created) {
this.created = created;
}
}

Now add a new package under model called dao, DAO means Data Access Object and these are the methods to execute the CRUD methods (Create Read Update and Delete) , normally you would also have a service layer which would take the VO (value objects) and change them to DTO’s or FBs (Data Transfer Objects or FormBeans) This is a good approach to seperate Database Objects from transient data movement objects so you do not inadvertently alter a record you only wanted to modify on the front end. but as this is an example we will go straight to the DAO layer.

First create an interface StandaloneDao

package com.github.theresajayne.standaloneexample.model.dao;

import com.github.theresajayne.standaloneexample.model.beans.StandaloneVO;

import java.util.List;

public interface StandaloneDao {
public List<StandaloneVO> findAll();

void save(StandaloneVO standaloneVO);
}

Now create the Implementation of the Dao usually called StandaloneDaoImpl

package com.github.theresajayne.standaloneexample.model.dao;

import com.github.theresajayne.standaloneexample.model.beans.StandaloneVO;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Repository
@Transactional
public class StandaloneDaoImpl implements StandaloneDao {

@Autowired
private SessionFactory sessionFactory;

@Override
public List<StandaloneVO> findAll() {
Session session = sessionFactory.getCurrentSession();
return (List<StandaloneVO>)session.createQuery(“from StandaloneVO”).list();
}

@Override
public void save(StandaloneVO standaloneVO) {
Session session = sessionFactory.getCurrentSession();
session.save(standaloneVO);
}
}

Now lets do something with our code….

private void startStandalone() {
StandaloneVO standaloneVO = new StandaloneVO();
standaloneVO.setName(“Test1″);
standaloneVO.setAmount(239.32);
standaloneVO.setCreated(new Date());
standaloneDao.save(standaloneVO);
List<StandaloneVO> result = standaloneDao.findAll();
for(StandaloneVO vo : result)
{
System.out.println(vo.getId()+”:”+vo.getName()+”:”+vo.getAmount()+”:”+vo.getCreated());
}

}

Now each time you run the code there will be a new line to the output….

1:Test1:239.32:2013-07-14 13:22:11.0
2:Test1:239.32:2013-07-14 13:22:21.0

Process finished with exit code 0

Hopefully this article has helped to make setting up Spring and Hibernate easy for Stand Alone Applications.

Source code is available from http://www.github.com/theresajayne/standaloneexample



{August 5, 2012}   Agile BDD/TDD

Lots of people have a strange view about TDD/BDD programming methodology. People tend to write code then write a test for it, this usually doesn’t test fully the code as you are writing the test to match your code.

So for proper Agile Development we start with a test.

[Test]
public void i_should_be_able_to_instantiate_an_organisation()
{
    IOrganisation organisation = Substitute.For<IOrganisation>();
    organisation.IsInstanceOf<IOrganisation>();
}

At This point [Test] IOrganisation and Substitute.For<> are all underlined in red, So this is a failing Test,

So we use NuGet to add Nunit, NSubstitute and Chaining Assertions for Nunit, Then we use Resharper to Alt-Enter on IOrganisation to create a new Interface.

Running the tests now, Pass with a Green Bar.

So, We refactor, Test again and Save the output checking it into source control.

Why Refactor?

Well we want to move the newly created IOrganisation Interface to its own class, or even project.

Once this is done, we write another test.

[Test]
public void I_should_be_able_to_retrieve_the_number_of_salons_in_the_organisation()
{
    IOrganisation organisation = Substitute.For<IOrganisation>();
    organisation.GetSalonCount();
    organisation.Received().GetSalonCount();
}

This one forces the IOrganisation to have a GetSalonCount() method so we add it, then once Green Bar on the test, we Refactor if needed

then Save and check in.

TDD and Agile development means you can do many check ins to your repository per day, the reason is that we can roll back to any previous version easily and every checkin also is guaranteed to run as all test pass before a checkin.

Using this methodology we can write working software quickly knowing that all changes we do result in a passing test and nothing previously written has been broken,

Ron Jeffries has written a good book that covers this method of development, http://my.safaribooksonline.com/book/programming/csharp/0735619492 and I would recommend you try it if you can, and Safari Books online will provide access to it if you cannot find a paper version



{January 20, 2012}   Generic toString() for Java

I found myself needing to retroactively add a toString() method to about 300 classes so that the AOP logging could track the data being passed in to DAOs etc.

So what to do? Spend a day or two trying to shoehorn this into the system class by class ? or work out a way to use one method in all classes?

Obviously wanting more time for blogging , shopping for shoes and doing my make-up  I chose the latter.

So I need to get a toString() that works. the default one for Object prints the class name and the instance id

uk.co.myorg.model.AuditLog@56f967c6

This doesn’t help so we had to move cleverer. either go through a whole class doing a StringBuilder with lines like

result.append(this.getName());

result.append(“\n”);

this was the long way around, so I decided to delve into reflection and do it in a clever way.

    @Override
public String toString() {
StringBuilder result = new StringBuilder();
try {
result.append(this.getClass().getName());
result.append(“\n————————————\n”);
Class c = this.getClass();
Field fieldList[] = c.getDeclaredFields();
for(Field entry: fieldList) {
result.append(entry.getName());
result.append(“:”);
result.append(entry.get(this));
result.append(“\n”);
}
} catch (Exception e) {

}
return result.toString();
}

Now this is nice and compact, and does what it says on the tin.

I now need to have an abstract class that every single class i use extends, oh well not much work saved but a nice concept.



{January 19, 2012}   Wireless Internet

Several years ago I wrote an article to post in the Reading Chamber of Commerce magazine but for some reason they did not publish, So i will attempt to recreate the article here and update it for current information.

Everyone has heard of Wi-Fi,  Motorway services provide it for free, but what are the risks with it. Back in 1997 I took my laptop with a pcmcia wireless network card ran up a piece of software called stumblr and drove round the IDR (Inner Distribution Road) in Reading heading out down Queens Road and back in by Kings Road (the legal/financial area)

In all I found 64 wireless hotspots, 32 of them strangely enough were wide open and unprotected by any security at all.

At the time every company was getting wifi for their employees to use in the office on their laptops, but no-one was securing the connection with WEP (Wireless Encryption Protocol)

As many know, this has since been cracked and even WPA-2 one of the latest encryption methods is crackable in minutes by even a mobile smartphone. It at least deters the opportunist.

People have a problem understanding how Wireless works, they are connected to WiFi but they still cannot get onto the internet, take for instance Wired connections they will plug in the cable and if it doesn’t work they will look at the network configuration or the router to determine what is not working, With wifi, they keep figuratively plugging and unplugging the cable by disconnecting and reconnecting the WiFi.

The WiFi connection you set up with the WPA key is the same as the Cable you plug into your PC. After that you have what is called the TCP/IP protocol  this is what allows you to connect out to the internet, but at its core the internet is machines connected together using an internet address called IPV4  you may recognise it as numbers like 192.168.1.2

but how do you connect to sites like http://www.google.com, We use a system called DNS (Domain Name Services) which is like a large Telephone Book allowing you to look up http://www.google.com and get its phone number (IP address).

There are small ranges allocated for non-routable connections and they are seperated into classes, don’t worry about those they just detail how many digits at the start do not change.

Class A: 10.x.x.x

Class B: 172.16.0.0 – 172.32.255.255

Class C: 192.168.x.x

Well most WiFi systems automatically allocate anyone connecting with an address to allow them to access the internet, To start securing the network you need to stop this happening, TURN OFF DHCP – this is the mechanism used to automatically issue internet addresses, or if you need this on because you have a large network, you could also lock the WiFi to only allow connections from certain machines, whilst this can cause more administration to the IT team it will make the network more secure.

How does this work? Well every network card ever created has an allocated “MAC” address (Media Access Control)  This is a series of digits which uniquely identify any piece of hardware, and most modern routers allow what is called Mac locking meaning if you don’t have the correct network card you cannot connect,  Interestingly enough the new IPV6 which is already starting to replace the old IPV4 due to us running out of addresses on the IPV4 network almost is a mac address and I have seen where some providers are allocating the IPV6 address based on the Mac Address of the connected hardware.

If you exclusively use Mac Locking then you can actually have your WiFi without a password as unless they are on the list they can’t come in.

Further to that all WiFi routers also Broadcast their Ident so you can see the name of the hotspot, You can also turn this off, so unless you know its name you cannot manually connect.

added to that, all routers need to have their default password and name changed and if possible change the ip address it uses.

A hacker will start looking for the router address to be able to try and gain access to the rest of the network by looking for 192.168.1.1 or 192.168.1.254 as this is where they usually reside. Change the default address say go for 192.168.4.20 for the router, so its completely out of the normal addressing range. All of this will help you to secure your network and deter hackers from stealing your ideas and installing nasty software in your connection

So The Suggestions are

  • MAC lock the router
  • Use WPA-2 or better security on the router
  • Change the router password and default ip address
  • Switch off the WiFi Beacon

All of these steps will increase your security in the office, and also at home, many people will implement security at the office that is second to none but they will still have a completely open Netgear router on default IP and password at home,

A last thought, A hacker logs into your network, downloads child porn, plants it on your computer then calls the police. What would that mean to you?



et cetera