Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Thursday, October 17, 2013

RESTful API Standards

Below are the common RESTful API standards that we should follow when designing our API's

Keep your base URL simple and intuitive
 /dogs     /dogs/1234

Keep verbs out of your base URLs
Never use /getDogs or /createDogs

Use HTTP verbs to operate on the collections and elements
POST, GET, PUT, DELETE is CRUD (Create-Read-Update-Delete)

Use Plural nouns
/dogs   /deals    /quotes

Concrete names are better than abstract
Instead of /items be more specific like /blogs  /videos
Number of resources - preferably between 12 to 24

Simplify the Relationship and Association between Resources
GET /owners/5678/dogs
POST /owners/5678/dogs

Keep complexity behind the ‘?’
GET /dogs?color=red&state=running&location=park

Have a good error design
                Aligning errors with HTTP status codes
                200 - OK
                400 - Bad Request from client
                500 - Internal Server Error
                304 - Not Modified
                404 – Not Found
                401 - Unauthorized
                403 - Forbidden
                Provide a more granular error message
                {"status" : "401", "message":"Authentication Required","code": 20003}

Versioning is mandatory
Always use v and never have minor version like v1.0. Ideal is v1, v2
Have version all the way to the left (highest scope): /v1/dogs

Maintain at least one version back
Follow proper cycle for deprecating and retiring the API

Response content type, OAuth etc must go into the header
information which doesn't change the logic for each response goes into the header

Extra optional fields must be requested in a comma-delimited list
/dogs?fields=name,color,location 

Pagination is a must for resource API's
Use limit and offset. 
/dogs?limit=25&offset=50
default pagination is limit=10 with offset=0

For Non-Resource API's: Use verbs not nouns
/convert?from=EUR&to=CNY&amount=100
/translate?from=EN&to=FR&text=Hello

Request format - support multiple if possible
Default should be JSON, but support XML if possible
Use the pure RESTful way with the header, Accept: application/json

Use standard Java/Javascript naming convention for attributes
example: createdAt, firstName

Search within a resource: use ?q=
/owners/5678/dogs?q=fluffy+fur

Have all API's in single store and under one domain
api.mycompany.com

Option to Supress error codes
Always sent HTTP 200, even in case of errors.
&suppress_response_codes=true

Authentication : Use OAuth 2.0

In addition to the atomic API, provide composite API's as well if required - if there is a need
This will avoid applications making multiple calls per screen.


Complement the API with code libraries and a software development kit (SDK)

Note: These are not the only standards and there may be variations. These are the standards which are followed my many and works for them.

Monday, July 22, 2013

Sonar - Code Quality Management

This Sonar tool is saving me a lot of time these days. Gone are the days where I need to worry about the developer following the coding standards of JAVA, HTML and JS.
I only need to worry about the business logic review these days.

This open source tool is surely a must have for every team. Check it out.
http://www.sonarsource.com/

The developers are also benefited as they are able to improve in their coding standards by using this tool.

Few plugins which are impressive are
http://docs.codehaus.org/display/SONAR/Quality+Index+Plugin
http://docs.codehaus.org/display/SONAR/Toxicity+Chart+Plugin
http://docs.codehaus.org/display/SONAR/Motion+Chart+Plugin

There are lot more though which can be easily added.


Wednesday, April 21, 2010

Java Split String

Java has a useful method to slip the string into a string array based on the delimiter. Its the Split() method.

But most of the time we may use it incorrectly. One example is, if we have a string with comma separated values, Split can be used to split the comma separated values into String[]. But if we use this directly, most of us might have noticed that it does not consider the last trailing string.

ie., if the string is String str = "a,b,c,d,";
When we do String[] strArray = str.split(","); we get the string array with 4 values only. And not with 5 values. To get the complete string array, we must use as below;
String[] strArray = str.split(",", -1);

This is generally useful when you have multiple rows of such comma separated string or the string is dynamically created.

Monday, December 21, 2009

Java Collections : Which one to use

When I initially started using Java and to be frank, until quite recently, I was never sure whether I am using the right collection for in my code.
Initially though, I never bothered about it and was using anyone which suites my needs (eg: Vector to store list of values and HashMap to store key value pair). I rarely used other implementations, unless my senior asked me to use it.

But later I did realise that using the right implementation for the right piece of work is important and can improve your code and the overall performance of your application.

I have put down a segment here for java developers who are having trouble making the decision on the right collection. to make it simpler for a java developer, I have put it in our language syntax, with if / else loop (The one we use most when we are starting up)

//Choose the collection
if ("Need to store key value pair")
{
  Use Map;
   //To choose the implementation
   if ("Map must be sorted by keys" && "Dont need to store null key")
   {
     Use TreeMap; //If speed is a major criteria, then you better use HashMap and sort it by your self.
   }
   else if ("Map must be fully synchronised" && "Must not allow null key and values")
   {
     Use HashTable;
   }
   else if ("Map must be thread safe while insertion" && "Must allow null key and values")
   {
     Use ConcurrentHashMap;
   }
   else if ("Map need not be thread safe" && "Must allow null key and values" && "Needs to be fast")
   {
     Use HashMap;
   }
   else if ("Need to store multiple values per key")
   {
     Use MultiMap;
   }
   else if ("Map must be fully synchronised" && "Must not allow null key and values" && "The order of insertion must be maintained")
   {
     Use LinkedHashMap;
   }
}
else if ("Must not store duplicates" && "Order of elements stored does not matter") //also, dont need key value pair, but have to store single values
{
   Use Set;
   //To choose the implementation
   if ("Set needs to be sorted")
   {
     Use TreeSet; //If speed is a major criteria, then you better use HashSet and sort it by your self.
   }
   else if ("Set need not be sorted" && "Speed is important")
   {
     Use HashSet;
   }
}
else if ("Will need to store duplicates" || "Order of elements stored matters" || "Need to have control over where the element is added")
{
   Use List;
   //To choose the implementation
   if ("Need to add and remove more frequently" || "Need the functionality of a Queue/Stack/Double-ended Queue")
   {
     Use LinkedList;
   }
   else if ("List must be synchronized")
   {
     Use Vector;
   }
   else if ("List need not be synchronized" && "Speed is important")
   {
     Use ArrayList;
   }
}
else if ("Amount of data is predictable" && "Amount of data is less")
{
   Use Array; //If searching is more important, use ordered array, else if insertion speed is important, use unordered array
}

There are ofcourse a lot more implementations of the collections. But I have tried to put in a few which are frequently used by us. And I believe, most of the operations can be handled by those mentioned above.

To know more about each implementation or collection, you can go through the Java API.

Please note that the above is based on my knowledge and if you see any mistakes, I am ready to correct myself.

Saturday, March 14, 2009

Last Day of the month - Java

Playing with dates is always fun.

Here is one of those....

//Given the month, will return the date of the last day of the month
//parameter is month number (starting from 0)
public static Date getLastDayOfMonth (int month) {

Calendar calendar = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat( format );

Date d = new Date();
d.setMonth( month );

calendar.set(Calendar.MONTH, month);
//System.out.println("Value "+ calendar.get(calendar.MONTH));
int lastDateofMonth = calendar.getActualMaximum(Calendar.DATE);
d.setDate( lastDateofMonth );

return d;
}

Quick Sort - Java Vector

Here is a small code snippet to sort a 2D Vector in Java.

//pos is the column number to be sorted with
private void quickSortVector(Vector v, int start, int end, int pos)
{
int i = start; // index of left-to-right scan
int k = end; // index of right-to-left scan

if (end - start >= 1) // check that there are at least two elements to sort
{
String pivot = (String)((Vector)v.elementAt(start)).get(pos); // set the pivot as the first element in the partition

try {
while (k > i) // while the scan indices from left and right have not met,
{
while (((String)((Vector)v.elementAt(i)).get(pos)).compareToIgnoreCase(pivot) <= 0 && i <= end && k > i) // from the left, look for the first
i++; // element greater than the pivot
while (((String)((Vector)v.elementAt(k)).get(pos)).compareToIgnoreCase(pivot) > 0 && k >= start && k >= i) // from the right, look for the first
k--; // element not greater than the pivot
if (k > i) // if the left seekindex is still smaller than
swapVector(v, i, k); // the right index, swap the corresponding elements
}
swapVector(v, start, k); // after the indices have crossed, swap the last element in
// the left partition with the pivot
quickSortVector(v, start, k - 1, pos); // quicksort the left partition
quickSortVector(v, k + 1, end, pos); // quicksort the right partition
}
catch (ArrayIndexOutOfBoundsException ae) {
System.out.println("Could not sort vector : Array out of bound exception for column "+ pos);
return;
}
catch (Exception e) {
System.out.println("Could not sort vector : Exception "+ e);
return;
}
}
else // if there is only one element in the partition, do not do any sorting
{
return; // the array is sorted, so exit
}
}