Posts tagged ‘Java’

Testing code with dependency of static methods





The point here is not to discuss if using static methods is good or not. If you prefer just to use dependency injection and pure object orientation instead of static methods, that’s with you.
However sometimes you have to live with code not made by you.
You can see this as “Such nasty code, thanks good the project is almost finishing and I’ll no longer see this code anymore!”
Did you noted the tense? “Almost finishing” it’s not done yet and it’ll depend of you to finish it.
Or you can have a different approach - that’s my favourite:
“This code suchs! Let’s do something better and learn something with that.”

Starting…

That’s the start point:
I have a code with some static methods and I have to test the code that use these static methods from outside classes.

Environment

The environment is: Java, Maven, JUnit4, Mockito and PowerMock (when the magic happens)

Pom.xml

Some configuration is necessary to make use of Powermock:

Pay attention on the version of your Mockito/JUnit/Powermock it’s a bit tricky.

Static file

The static file looks like this:

The piece of code that calls the FileHelper.saveFile(..) is this one:

Testing

Take a look at the code that’s gonna test the Controller…

Important

- Two new annotations on the class level:
@RunWith(PowerMockRunner.class)
@PrepareForTest(FileHelper.class) : Tells to PowerMock what is the class that shoud be static mocked.
- PowerMockito.mockStatic(StaticClass.class) : mocks the class

Uploading files using SpringMVC

A quick setup to upload files using SpringMVC.

Dependencies

I’m using Maven so the very first step is to add some extra dependencies: commons-io and commons-fileupload:

Application Context

Second step is to setup the application context to make usage of multipart feature:

Controller

Third step is to create your controller. Note that there is a new type here: MultipartFile as parameter.

View

And the last step: your JSP page.

Differentiating Object from Data Structure

egg
Let’s start from begin: What is the difference between Object and Data Structure?

From wikipedia a Data Structure is: a data structure is a particular way of storing and organizing data in a computer so that it can be used efficiently.[1][2]

As well as Object is: any entity that can be manipulated by the commands of a programming language, such as a value (computer science), variable, function, or data structure.

Just to put some code in it.

This is a Data Structure:

And this is an Object:

This is how I’m policing myself to code. Letting VOs, DTOs, Entities exactly as a data structure, just with fields, getters and setters. Even constructors I am letting outside it. Maybe I’m exaggerating do not creating the constructors or switching them to static methods into the VOs. However, my experience with this approach tells me that letting them out is more productive specially when we are talking about testable code and isolating responsibilities improving the Single Responsibility Principle.

You may be asking: “Are telling that I’m not more able to create my own Entities directly?

The answer is yes and no. I’ll explain.

To a simple task just create an instance of an Data Structure, you could just call the default constructor.
But to create a more sophisticated instance of that object for some specific porpoise instead of using a static method describing the usage of that as suggested by Uncle Bob Martin on his book Clean Code I suggest you to use an Object to handle the creation of the Data Structure initializing it with the propers values for the specific usage.

Do you disagree? Let your comment down here!

Hibernate - Insert Before Delete


deadlock

Today I faced a problem that I already had faced some time before, but I didn’t documented that in blog entry or even in my “ProblemsThatCanNotBeForgotten.TXT”. So that’s the time for that.

The problem is: I have an entity called Team who has a List of Players (other entity). I’m trying to move an Player from one team to the other at the same transaction. Follow some code:


Original Team.java

After load this Entity by the JPA/Hibernate engine and have the tables created this is the structure and the indexes created:


table_team_player_one2many

The Problem

As happens in the real world some teams wants to trade their players, so the software has to be able to transfer one player from one team to another.
The code wich do this is very simple, just remove a player from one collection’s player team from the seller team and then insert the remove player to the buyer team.
After the transfer, the application apply this changes on the Database with merge(entity) call.


Call that merge a Team

Doing this a message telling that it’s impossible to insert a duplicate row blows up on the console.

This is because Hibernate does the INSERT statement BEFORE the DELETE.

After looking at Internet I didn’t find anything to solve that. Just a workaround that fixes that. But as I said, it’s a workaround.

Solving (woking it around)

To solve that problem I changed the reference from Team to Player from @OneToMany to @ManyToMany. The problem with this approach is that I lose the rule in the DB that has the control over the unicity of a player belonging to just one Team.

This is how the code and the table at the DB look like:


New Team.java


table_team_player_many2many

Table without the constraint

Faces config editor with problems to load the designer view on Eclipse


45687289

After create a maven project directly on Eclipse and setting JavaServer Faces Facet for that project I faced a problem that the visual editor of the faces-config files didn’t load it. Just the XML view was OK.
Surfing on the Internet I have found some tips about that, one of them was to include the JSF Facet. It can be found here and here. But it didn’t solve my problem. What realy solved that was to include a line directly into the .settings/org.eclipse.wst.common.component file.
Follow bellow my .settings/org.eclipse.wst.common.component file in two versions, the first one with out the visual jsf config editor working and the second one with it running OK.
Note that the only thing that has changed was the inclusion of the one line in the wb-module.


Version 1: Not working


Version 2: Working!

Jersey, Maven and Spring





Recently I needed to work on a project where all the communication between fron and backend was done usin HTTP requests. At the beginning we considered to use Servlet with some helpers wich acted as a clue mapping the URL’s parameters to a Map object. Internally this Map was “injected” in all resource classes.

It was a solution to be considered but how it was the very first idea that the team had, we decided to discard it.

As required by the client we had to use Maven and Spring. However all others libraries we could decide and bear with it.

So, the second idea was to use RESTful simply to facilitate the job of mapping the parameters coming from the URL and the internal code.

We researched the first lib Jersey since it is the standard implementation of the JSR-311 we also researched the Restlet API.
We decided to go again the ideology to refuse he first option at this time. We studied both of them.
Both frameworks had unique aspects and a vast documentation. Each one with their singularities, for instance on Restlet it is necessary to configure the “routes” in a subclass of Application.

But the main reasons that made us to decide to use Jersey were:

  1. Be the standard implementation of the specification
  2. Less bureaucracy on the implementation of the resources
  3. Almost natural integration with Spring for classes and resources(Request, Response, ServletContext) injection.

This “walk through” has the objective to exemplify how to create a simple application using: Spring, Maven and Jersey made simple.

Setup

  1. Include the entry for the jersey-spring repository in the pom.xml file.

  2. Include the libs as dependencies: jersey spring
  3. Configure the web.xml file

It’s time do code!

  1. Configuring the Spring (applicationContext.xml)
  2. Create applicationContext.xml file on META-INF directory of your app. This code tells to Spring engine to that com.mng.jerseydemo package is available for dependency injection. Follow a model of this file:

  3. Create the first resource.

  4. At this snipped there are some annotations between then:

    1. @Path
    2. This is the URL pattern that will be handled by the class (resource). It can be informed variables following the model: {valiableName}. For instance: @Path(”/user/{username}/{password}”).

    3. @Autowired
    4. Injects an object from the variable type.

    5. @GET
    6. Response request made via GET. There are also: @POST, @PUT and @DELETE that can be used at the same way then @GET.

    7. @Produces
    8. Inform the return type of a method. This annotation can be informed for a method as well as for a class together with @Path.
      If specified at the class all methods inside this one without a specific @Produces will follow the @Produces of the class.

    9. @PathParam
    10. Translate mapped variables from a URL to an object. This will be mapped to a variable informed at the signature of the method.

Getting access

To get access to a resource just created you can use your own browser (Chrome or Firefox) with then is easy to test the “verb” GET.
However, if you are in the “X” world (Linux, Unix or even Mac OS) relax, take a cup of tea and use cUrl.
In a fast and simple way this is how you can use to test all the verbs available (GET, PUT, POST and DELETE) through the parameter: “-X” informing the method to be used.

And with the “-F” parameter you can specify the key value parameters for the POST method (@QueryParam).

Controlling domain data with Hibernate and Enum

It is common to have a field into the table that his domain is no bigger to created a domain table just for that field and let it “free” as a String is a bit insecure.

A possible solution - if possible in your company - could be the creation of a big table for all simple domain data such as: gender(M/F) conditional(Yes/No) and so on.

But talking about Hibernate and Java (1.5+) we could use a more sophisticated solution such as Enuns.

Let’s start our sample defining the Enum and the Client class:


Client class


Gender enum

The annotation @Enumerated has just one param and it can had two values:

  1. EnumType.ORDINAL
  2. EnumType.STRING

The difference between them are not visible from the Object’s point of view. For this field will be associated an Enum with all it’s structure.
However, the difference between ORDINAL and STRING can be seen when you take a look at the database. When you define ORDINAL the position defined in Enum for that value will be stored. Starting from zero (zero based). For instance if you define the EnumType as ORDINAL and create an object like this:

And store it in database the record stored will looks like this:
enum_ordinal

On the other hand, if the definition of the EnumType is defined as STRING, for the same creation code will produce this record in the database:
enun_string

JSF and Facelets

If on the one hand you have the absolutely perfect Tiles working together (almost inside) Struts, on the other hand Facelets is a very useful, simple and powerful solution for layout design when you are using JSF. In this article I’ll describe how to configure it in a simple way.

Starting

Download the Facelets lib, I’m using the version 1.1.14: facelets download. Put the package in your classpath, generally in the WEB-INF/lib directory of your web app.

If you don’t this is the time to create your “Dynamic Web Application” using Eclipse:

eclipse-dynamic-web-projectFigure 1: Creating a Dynamic Web Project with Eclipse.

Using Eclipse, locate and double click in the faces-config.xml file, located at: WebContent/WEB-INF/faces-config.xml. You should be able to see a friendly and easy view to configure the faces configurations. Down on the bottom click in the “Others” tab, locate the “View Handler”, click in “Add” and type: com.sun.facelets. select the first option. It should be: com.sun.facelets.FaceletViewHandler.

configuring-facelets-eclipse

Figure 2: Configuring the FaceletViewHandler

At this point you may be wondering what the magic happened here? That’s no magic, actually it was just some XML tags added inthe faces-config.xml:

Now it’s time to configure the web.xml. That’s not so easy like the faces-config, you’ll have to open the file in the source mode. I reckon that for the web.xml the source view is more productive than the design. Add the follow instructions:

Note that this is my complete web.xml. Probably you don’t need all these stuffs, copy and paste just the difference and the configurations related with the Facelets.

XHTML versus JSP

I didn’t find any good sample using JSP, actually I didn’t find any. All of them used the xhtml as the extension instead of jsp. For me that’s fine, but if it’s not for you a solution that I’ve found was to download the .tld from the facelets website and put it in the tld directory inside your WEB-INF dir. I dunno if it works, I think that this is too much workaround and decided to give up of this approach and use the well-known and documented xhtm extension. The benefits that I’ve encountered was that all the HTML inserted in the file is “compiled” in runtime, if something wrong was typed you can see the stack trace on the page.

Layout

Great all configurations are done, now it’s time to see our work. First of all we have to create our layout. The strategy here is simple, just a header, content and a footer file. I decided to put these files in the WEB-INF/layout dir.

layoutTake a look in each content:

Header.xhtml:

Footer.xhtml:

Layout.xhtml:

First Page

The target here is to replace the content and keep the header and the footer sections. For that, let’s create a file called index.xhtml with the follow content:

Index.xhtml

Start the tomcat and point your browser out at: http://localhost:8080/your_app/index.jsf

Pay attention, the extension in the URL is JSF and NOT XHTML NOR JSP.

Play with the content and with the variables like title and template to see the difference.

Enjoy!

Testing private methods, Java and Groovy

To test private methods in Java is tough. I’ve faced developments model who instead of let methods as private the developers were forced to assign as default to be testable. Off course it is just a work around with a few collateral effects.

This is the class with the private method:

1
2
3
4
5
6
7
8
9
10
11
package com.marciogarcia;
 
public class SomeBean {
 
	private static final int FACTOR = 2;
 
	private int executeSomeTask(int val1, int val2) {
		int returnValue = (val1 + val2) * FACTOR;
		return returnValue;
	}
}

That’s a sample of what could be done keeping the method private and using just Java and reflection:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.marciogarcia.test;
 
import static org.junit.Assert.assertEquals;
 
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.junit.Test;
import com.marciogarcia.SomeBean;
 
public class SomeBeanJTest {
 
	@Test
	public void test_Execute_Some_Test_With_Java() {
		int value = 0;
		try {
			Method m = SomeBean.class.getDeclaredMethod("executeSomeTask", int.class, int.class);
			m.setAccessible(true);
			value = ((Integer) m.invoke(new SomeBean(), 1, 2)).intValue();
		} catch (NoSuchMethodException nsme) {
			System.out.println(nsme.toString());
		} catch (InvocationTargetException ite) {
			System.out.println(ite.toString());
		} catch (IllegalAccessException iae) {
			System.out.println(iae.toString());
		}
		assertEquals(6, value);
	}
}

Now, that’s what could be done keeping the method private and adding Groovy as a test solution.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.marciogarcia.test
 
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.marciogarcia.SomeBean;
 
public class SomeBeanGTest{
 
	@Test
	public void test_Execute_Some_Test_With_Groovy() {
		int value = new SomeBean().executeSomeTask(1, 2);
		assertEquals(6, value);
	}
}

Groovy simple ignore private methods, actually it is using underneath reflection to execute the task to call the method. This is a bug, but it is extremely useful that it is considered a “feature” instead of a bug.

Fluent Interfaces

Fluent Interface is part of domain-specific language DSL, the basic idea of the fluent interfaces is to rationalise a sequence of sequences. Using FI is quite simple to understand and also very readable.

There are some benefits of using fluent interfaces, first of all is the quality of the code, or at least how easy to read and understand it turns.

Testability

The second point is about testability. Implementing fluent interfaces you have to have methods returning something different than void, so it forces you to return at least the object, so for unitary test it’s perfect, because you know the parameters and also know what to wait as response, instead of verify the result of the method looking in other objects.

Proxies and Constructors

Other good point in this discussion is to create proxy for inside objects. For instance, supposing we have two classes: Person and Address, and each Person has one Address.

fluent-interface-1The basic, without using fluent interface way to write a code that sets and Address into Person could looks like this:

Person person = new Person();
person.setId(1);
person.setName("Name");
 
Address address = new Address();
address.setId(1);
address.setName("Your street name");
person.setAddress(address);

Now, let’s think a little bit about the reasons. Looking at this example there is any reason to have at Person class a default constructor? I mean, can exist a Person without an Id and a Name? Maybe a Person without Address could be acceptable, but not without and Id and Name, so why don’t put this obligatory fields into constructor?

Second point, for the same reason of the Person, can you imagine and Address without the street’s name? Neither me. Let’s change this code to looks more simple and friendly.

Person person = new Person(1, "Name");
person.setAddress(1, "Street Name")
      .setMotherName("Mom")
      .setFatherName("Dad")
      .setAge(30);

The main attributes are included as parameter into the constructor and the others attributes can be included outside the constructor, for instance, father’s name, mother’s name, age.

All the magic happens just applying the fluent interface. The code for the first peace of code is very basic, just two Java Beans full of gets and sets methods, on the other hand the JavaBeans’s code for the second example is a bit more sophisticated, looking like this:

Address:

public class Address {
 
    private Integer id;
    private String street;
 
    public Address(Integer id, String street) {
	this.id = id;
	this.street = street;
    }
 
    public Integer getId() {
        return id;
    }
 
    public Address setId(Integer id) {
        this.id = id;
        return this;
    }
 
    public String getStreet() {
        return street;
    }
 
    public Address setStreet(String street) {
        this.street = street;
        return this;
    }
 
}

Person:

public class Person {
 
    private Integer id;
    private String name, motherName, fatherName, age;
    private Address address;
 
    public Person(Integer id, String name) {
	this.id = id;
	this.name = name;
    }
 
    public Person setAddress(Integer id, String streetName) {
	address = new Address(id, streetName);
	return this;
    }
 
    public String getMotherName() {
        return motherName;
    }
 
    public Person setMotherName(String motherName) {
        this.motherName = motherName;
        return this;
    }
 
    public String getFatherName() {
        return fatherName;
    }
 
    public Person setFatherName(String fatherName) {
        this.fatherName = fatherName;
        return this;
    }
 
    public String getAge() {
        return age;
    }
 
    public Person setAge(String age) {
        this.age = age;
        return this;
    }
 
}

Maintenance

If you’re not convinced about simplicity, think about maintenance. If something changes during the development process, let’s say that the Product Owner have changed idea about the product, and the name of the street in the Address is not quite significant to have just “Name”, he prefers to have something like: “Street Name”.

Not using fluent interface you, as developer, you should update all classes that have used the Address class, at this example we have two business classes that use Address via Person object.

fluent-interface-withoutHaving using some good development tools like Eclipse, Netbeans or JEdit this task will not take too long to be re factored, but I’m not sure about unit tests. Some cumbersome  work have to be done to all unitary test starts to work again.

But using fluent interfaces, instead of changing all your business classes - at this example luckily just 2 classes - you can change just the Person class, once that this is the entity that knows exactly how to manipulate the values to fill out the Address  object.

fluent-interface-withConclusion

Using fluent interfaces, improve your code not just letting it more readable, but also less cumbersome with something has to be changed in the middle of the development process.