Showing posts with label rest. Show all posts
Showing posts with label rest. Show all posts

Monday, 20 June 2011

Fetch Twitter friends or followers through REST API in Java

I was playing around with fetching Twitter followers and friends with Twitter4J. But it was taking time to do that. So I code it with using REST urls given by Twitter. It fetches all your friends or followers. Depending upon your application that you want one list or you want to use paging. But I did it in one go. Performance wise, it will be trouble of fetching say 2000 followers or friends.

I used JDOM to parse XML.

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

public class Twt {

String urlFlwrs= "http://twitter.com/statuses/followers/YOUR_TWITTER_SCREEN_NAME.xml?cursor=";
String urlFrnds= "http://twitter.com/statuses/friends/YOUR_TWITTER_SCREEN_NAME.xml?cursor=";

List followers = new ArrayList();
long cursorCounter = -1;

public static void main(String[] args) {
long start = System.currentTimeMillis();
new Twt().readFollowFriends();
System.out.printf("Total Time: %d secs",
(System.currentTimeMillis() - start)/1000);
}

void readFollowFriends(){

try {
StringBuffer followersData = new StringBuffer();
// use urlFrnds as a parameter if you want to fetch friends
URL url = new URL(urlFlwrs+cursorCounter);
URLConnection urlConnection = url.openConnection();
DataInputStream dis = new DataInputStream(
urlConnection.getInputStream());
String inputLine;
while ((inputLine = dis.readLine()) != null) {
followersData.append(inputLine);
}

SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new ByteArrayInputStream(
followersData.toString().getBytes()));

Element root = document.getRootElement();
Element usersElm = root.getChild("users");
Element nextCursor = root.getChild("next_cursor");
List users = usersElm.getChildren("user");

for (int c = 0; c < users.size(); c++) {
Element user = (Element) users.get(c);
Element name = user.getChild("name");
// now you have every thing, the information of a user
// here you can populate followers list
}

if (nextCursor != null){
cursorCounter = Long.parseLong(nextCursor.getText());

if (cursorCounter != 0)
readFollowFriends();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Saturday, 18 June 2011

Interview Question: Compare two web services type SOAP and RESTful (SOAP Vs RESTful)

Here are the differences between SOAP and Restful web services :





Criteria SOAP RESTful Comments
Orientation Wraps business logic Accesses resources/data
Developer View Object oriented Resource Oriented
Language Independence Yes Yes
Platform Independence Yes Yes
Simplicity No Yes
Standards Based Yes No SOAP web services are based on SOAP and WS-* specifications
Security SSL, WS-Security SSL WS-Security provides end-to-end security covering message integrity and authentication
Transactions WS-AtomicTransaction No
Reliability WS-ReliableMessaging Application specific
Performance Good Better Caching and lower message payload makes RESTful web services performance efficient and scalable
Caching No GET operations can be cached
Transport protocol support HTTP, SMTP, JMS HTTP Multiple transport protocol support makes SOAP Web Services flexible
Message Size Heavy, has SOAP and WS-* specific markup Lightweight, no extra xml markup
Message Communication protocol XML XML, JSON, other valid MIME type This flexibility of REST makes its extremely useful in providing consumer need specific message payloads
Message Encoding Yes No SOAP Web Services support text and binary encoding, RESTful encoding is limited to text
Service Description WSDL No formal contract definition In REST, no formal way to describe a service interface means more dependence on written documentation
Human intelligible Payload No Yes
Developer Tooling Yes Minimal or none Complexity of SOAP Web Services dictates the need for using frameworks to facilitate rapid application development. REST on the other hand due to its simplicity can be developed without any framework


Now we come to most important stage of deciding which type to select. There is no one answer for selecting either SOAP based or RESTful Web Services. Neither is the right choice for every situation. The choice is dependant upon specific needs and which solution addresses them best. An architect should ask the following questions and the responses should assist him/her in making an informed decision:
  • Does the service expose data or business logic? (REST can be a good choice for exposing data, SOAP/WS-* might be a better choice for logic)
  • Does the service need the capabilities of WS-*, or is a simpler RESTful approach sufficient?
  • What’s best for the developers who will build clients for the service?
Areas where RESTful WebServices are a great choice:
  • Limited bandwidth and resources: Remember the return structure is really in any format (developer defined). Plus, any browser can be used because the REST approach uses the standard GET, PUT, POST, and DELETE verbs. Again, remember that REST can also use the XMLHttpRequest object that most modern browsers support today, which adds an extra bonus of AJAX.
  • Totally stateless operations: If an operation needs to be continued, then REST is not the best approach and SOAP may fit it better. However, if you need stateless CRUD (Create, Read, Update, and Delete) operations, then REST is suitable.
  • Caching situations: If the information can be cached because of the totally stateless operation of the REST approach, this is perfect.
Areas where SOAP based WebServices is a great solution:
  • Asynchronous processing and invocation: If application needs a guaranteed level of reliability and security then SOAP 1.2 offers additional standards to ensure this type of operation. Things like WSRM – WS-Reliable Messaging etc.
  • Formal contracts: If both sides (provider and consumer) have to agree on the exchange format then SOAP 1.2 gives the rigid specifications for this type of interaction.
  • Stateful operations: If the application needs contextual information and conversational state management then SOAP 1.2 has the additional specification in the WS* structure to support those things (Security, Transactions, Coordination, etc). Comparatively, the REST approach would make the developers build this custom plumbing.
I have used a lot of information from resources generously shared by fellow bloggers. It would inconsiderate in case I do not mention them. The resources are:
  1. REST and SOAP: When to use each (or both)?
  2. SOAP vs REST: Complements or Competitors
  3. Introduction to Web APIs: REST vs SOAP



Monday, 11 April 2011

REST in Java

You may want to call the REST web service from Java. Following is the code for a simple Web Service client for the flickr web services interface.

pacage com.vaani.rest;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketAddress;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
public class FlickrClient {
    public static void main(String[] args) {
        String flickrURL = "http://api.flickr.com/services/rest/?method=flickr.test.echo&name=value&api_key=[yourflickrkey]";
        try {
            SocketAddress addr = new InetSocketAddress("[proxy]", 9090);
            Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
            URL u = new URL("http://api.flickr.com/services/rest/?method=flickr.test.echo&name=value&api_key=[yourflickrkey]");
            HttpURLConnection uc = (HttpURLConnection) u.openConnection(proxy);
            uc.setRequestProperty("Accept", "*/*");
            uc.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
            uc.setRequestProperty("Accept-Language", "en-us,en;q=0.5");
            uc.setRequestProperty("Keep-Alive", "300");
            uc.setRequestProperty("ucection", "keep-alive");
            String proxyUser = "[netUserId]";
            String proxyPassword = "[netPassword]";
            uc.setRequestProperty("Proxy-Authorization", "NTLM " + new sun.misc.BASE64Encoder().encode((proxyUser + ":" + proxyPassword).getBytes()));
            DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = docBuilder.parse(uc.getInputStream());
            System.out.println(doc.getDocumentElement().getTagName());
            System.out.println();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

RESTful Web Service tutorial: An Introduction for beginners

REST is a term coined by Roy Fielding in his Ph.D. dissertation to describe an architecture style of networked systems. REST is an acronym standing for Representational State Transfer. Representational State Transfer(REST), a software architecture style used in developing stateless web services. While this style may be used to describe any distributed framework that uses a simple protocol for data transmission and no other additional data transfer rules, the most common use of REST is on on the Web with HTTP being the only protocol used here. In REST each service (called “resource” in REST) is viewed as resource identified by a URL, and the only operations allowed are the HTTP – GET (Read), PUT (Update), POST(Create) and DELETE (Delete). You can find this style similar in SQL, thinking of a resource as equivalent to a Table. The main features and constraints of REST architectural style are:
  • Client-Server: A clear separation concerns is the reason behind this constraint. Separating concerns between the Client and Server helps improve portability in the Client and Scalability of the server components.
  • Stateless: All REST resources are required to be stateless. The idea is that the application would be resilient enough to work between server restarts. However, it is not uncommon to see some RESTful web services save states between requests.
  • Caching: Caching is allowed, however it is required that “response to a request be implicitly or explicitly labeled as cacheable or non-cacheable”
  • As there is no interface definition (like in SOAP), it becomes mandatory for a Client and Server to have a mutual understanding of the messages being transmitted between them.
Given that every resource in a RESTful service is represented by a URL, it is easy to write a client for such a web service.
A lot of companies these days (including Amazon and Yahoo!) are exposing their web services in the form of REST resources. At a high level REST is pretty easy to understand, all you’re doing is exposing a web service in the form of a URL. Users can then query this URL, through HTTP methods like GET and POST. REST calls generally return some type of XML or Object Encoding like JSON.