Overview
A quickly developed Jersey REST implementation of a Fibonacci sequence ‘service’.
What is the Fibonacci sequence
Wikipedia provides quite a detailed definition of the Fibonacci sequence http://en.wikipedia.org/wiki/Fibonacci_number
By definition, the first two numbers in the Fibonacci sequence are 1 and 1, or 0 and 1, depending on the chosen starting point of the sequence, and each subsequent number is the sum of the previous two:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Prerequisites
You will need to install the following technical components:
- Java 1.7.x
- Maven 3.0.5
- Nexus 2.8.1✝ (optional)
✝ by using Nexus, a repository manager, in conjunction with Maven the required dependencies are easily managed and packaged components will be downloaded as required.
Create a new Java project in using Jersey Grizzly quickstart
To create the Jersey web-app project, execute the following Maven archetype command in the directory where the new project should reside:
mvn archetype:generate -DarchetypeArtifactId=jersey-quickstart-webapp -DarchetypeGroupId=org.glassfish.jersey.archetypes
-DinteractiveMode=false -DgroupId=com.addison -DartifactId=jersey-webapp -Dpackage=com.addison -DarchetypeVersion=2.13
Java project skeleton structure
jersey-webapp
│ pom.xml
│
└───src
├───main
│ └───java
│ └───com
│ └───addison
│ App.java
├───resources
└───webapp
│ index.jsp
│
└───WEB-INF
web.xml
This essentially creates a very simple REST web-app, which retrieves a static string response.
Service implementation
package com.addison;
import java.math.BigInteger;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
/**
* Root resource (exposed at "fibonacci" path)
*/
@Path("fibonacci")
public class Fibonacci {
/**
* Method handling HTTP GET requests. The returned object will be sent to the client as "text/plain" media type.
*
* @return String that will be returned as a text/plain response.
*/
@GET
@Produces(MediaType.TEXT_PLAIN)
public String fibonacci(@QueryParam("num") String number) {
try {
long n = Long.parseLong(number);
StringBuilder series = new StringBuilder("Fibonacci ");
series.append(number);
series.append(" : 0");
if (n > 1)
series.append(" 1");
BigInteger prev = BigInteger.valueOf(0L), next = BigInteger.valueOf(1L), result = BigInteger.valueOf(0L);
for (long i = 1; i < n - 1; i++) {
result = prev.add(next);
series.append(" ");
series.append(result.toString());
prev = next;
next = result;
}
return series.toString();
} catch (NumberFormatException err) {
return "Invald Request: fibonacci?num=" + number + "\nNumberFormatException: " + err.getMessage();
}
}
}
Running
The service has been deployed to a server under apache tomcat
- execute Fibonacci-sequence=5
- execute Fibonacci-sequence=15
- execute Fibonacci-sequence=25
Code
The source code is available from my public Github repository jersey-webapp