IgorShare Weblog

Practical Engineering

Archive for the ‘REST’ Category

Messaging Platform and Service Bus Resources

Posted by igormoochnick on 10/25/2009

On the recent project we’ve put in place a messaging platform. Apparently my engineers had a vague understanding what that is. To save you the same trouble I’ve gathered a bunch of interesting resources that can help you get up to date:

Open source Service Bus implementations

nServiceBus

MassTransit

WCF (misc)

Posted in Messaging, REST, Service Bus, WCF | Leave a Comment »

XML/JSON symmetric REST web services providers for Jersey

Posted by igormoochnick on 07/27/2009

Many times I’ve been asked to provide a set of Web Services interfaces where both JSON and XML clients can communicate with the server. Primarily it’s done for a set of reasons:

  1. XML is very convenient to use for inter-service communication.
  2. JSON is great for AJAX (web) clients. It’s perfect for GWT too.

In the recent project we’ve been using XStream for all serialization aspects and, since it can serialize both to XML and JSON, it was plugged into Jersey as a provider too. Following you can see XML and JSON providers implemented using XStream library.

XML Provider (annotated to be a default provider, it’ll be used if no Content-Type or Accept headers provided):

Read the rest of this entry »

Posted in GWT, JSON, Java, Jersey, REST, Tutorials, XML, XStream | 1 Comment »

Building GWT web clients [Part 4.1] – How to create an Azure RESTful web service?

Posted by igormoochnick on 06/08/2009

Prerequisites: make sure that you have all the Azure SDK tools installed for your VS2008.

 

(1) Start by creating a new “Web Cloud Service” project in the Visual Studio. Give it a nice name.

(2) Add a new “WCF Service” to the WebRole project.

(3) Define a required contract:

The most important part here is to put attributes that will tell the WCF in what format to send/receive the message body (XML or JSON) …

[ServiceContract(Name = "service", Namespace = "http://www.igorshare.com")]
public interface IContactManagerService
{
    [OperationContract]
    [WebGet(UriTemplate = "/contacts", BodyStyle = WebMessageBodyStyle.Bare,
       ResponseFormat = WebMessageFormat.Json)]
    List<Contact> GetAllContacts();

    [OperationContract]
    [WebGet(UriTemplate = "/contacts/{filter}", BodyStyle = WebMessageBodyStyle.Bare,
       ResponseFormat = WebMessageFormat.Json)]
    List<Contact> GetContacts(string filter);
}

[DataContract]
public class Contact
{
    [DataMember]
    public string FirstName { get; set; }

    [DataMember]
    public string LastName { get; set; }

    [DataMember]
    public string Company { get; set; }
}

(4) Implement the service logic:

public class ContactManagerService : IContactManagerService
{
    private static readonly List<Contact> Contacts = new List<Contact>() { ... };

    public List<Contact> GetAllContacts()
    {
        return Contacts;
    }

    public List<Contact> GetContacts(string filter)
    {
        string f = filter.ToLower();

        var contacts = from contact in Contacts
                       where contact.FirstName.ToLower().Contains(f)
                            || contact.LastName.ToLower().Contains(f)
                            || contact.Company.ToLower().Contains(f)
                       select contact;

        return contacts.ToList();
    }
}

(5) Configure it to be exposed as a RESTful service:

To make it REALLY, REALLY simple for you, do this trick:

a) Comment out the system.serviceModel section in the Web.config file

b) Add the Factory attribute to the .svc file

<%@ ServiceHost Language="C#" Debug="true"
Service="ContactManagerCloudService_WebRole.ContactManagerService"
CodeBehind="ContactManagerService.svc.cs"
Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>

(6) Build the service

 

You’re interested in 2 artifacts of the build:

  1. .cscfg file – configuration for the Cloud Service deployment
  2. .cspkg file – all the bits packaged (zipped)

 

At this moment you have 2 choices:

  1. Run your project in the local Development Fabric (for testing and debugging), or …
  2. Deploy it to the Azure Cloud (for staging or production)

 

To deploy your application to the cloud, do right-click on the CloudService project and select “Publish”.

Visual Studio will launch the Azure Service Developer Portal page. Log-in to your account, create a project and deploy your bits to the staging environment:

clip_image001

 

This is it!  You’re good to go.

BTW: make sure that your application works in the staging environment and then you can push it to Production by just switching it with the Staging.

 

 

Note: Check out a great explanation about the difference between the WCF REST Configuration for ASP.NET AJAX and plain REST Services by Rick Strahl.

Posted in .NET, Azure, C#, JSON, REST, S+S, Tutorials, WCF | Leave a Comment »

Building GWT web clients [Part 4] – How to connect GWT client to Azure web service?

Posted by igormoochnick on 06/08/2009

Stay tuned …

Posted in Azure, GWT, JSON, Java, REST, S+S, Tutorials | Leave a Comment »

Building GWT web clients [Part 3] – How to connect GWT client to JAX-RS Jersey server?

Posted by igormoochnick on 06/08/2009

Stay tuned …

Posted in GWT, JAX-RS, JSON, Java, Jersey, REST, S+S, Tutorials | Leave a Comment »

Building GWT web clients [Part 2.1] – How to control JSON output format from Jersey?

Posted by igormoochnick on 05/21/2009

As you know that in XML you can represent the same data in variety of ways by using fields, names, attributes, etc..

The same is true to JSON. In many cases different serializers produce different JSON representation of the same objects.

JAX-RS (as well as Jersey) provide you control over what and how you want to serialize. This is accomplished via providers.

Here is an example of such provider (Note that the class should be marked with @Provider annotation):

@Provider
public class JAXBContextResolver implements ContextResolver<JAXBContext> {
    private JAXBContext context;
    private Class<?>[] types = { ListDescription.class }; 

    public JAXBContextResolver() throws Exception {
        JSONConfiguration config = JSONConfiguration.natural().build();
        context = new JSONJAXBContext(config, types);
    } 

    public JAXBContext getContext(Class<?> objectType) {
        for (Class<?> type : types) {
            if (type == objectType) {
                return context;
            }
        }
        return null;
    }
}

Note that by creating an appropriate JSONConfiguration (JSONConfiguration.natural().build()) you, in fact, control the output JSON format. The JSONConfiguration class provide 4 different JSON formatters:

  1. natural (Jackson)
  2. mapped
  3. mappedJettison
  4. Badgerfish

Here is how the output will vary, depending on the choice of the configuration. Don’t forget that the class should be annotated with A simple class (with fields (int)ID and (String)Name) added to an ArrayList and then returned back as a @GET return value:

@XmlRootElement
public class ListDescription
{
	public int ID;
	public String Name;
}

@GET
@Produces({MediaType.APPLICATION_JSON })
public List<DataListInfo> getAllLists()
{
	List<ListDescription> lists = new ArrayList<ListDescription>();
	ListDescription ls = new ListDescription();
	ls.ID = 1;
	ls.Name = "Test";
	lists.add(ls);
	return lists;
}

This is what you’ll get from each configuration (respectively):

mappedJettison:

{"listDescriptions":{"listDescription":{"ID":1,"Name":"Test"}}}

mapped:

{"listDescription":{"ID":"1","Name":"Test"}}

natural (jackson):

[{"ID":1,"Name":"Test"}]

Badgerfish:

{"listDescriptions":{"listDescription":{"ID":{"$":"1"},"Name":{"$":"Test"}}}}

Posted in JAX-RS, JAXB, JSON, Java, Jersey, REST | 1 Comment »

Building GWT web clients [Part 2] – How to expose REST-full JAX-RS service with Jersey on Tomcat server?

Posted by igormoochnick on 05/20/2009

In the previous article (Part 1) we’ve seen how to create a web-based REST-full client (and an appropriate server) by using GWT. GWT is not providing any “standard” REST (if you can use this word in REST context at all) interface, but, merely, exposes the server-side logic via a proprietary GWT RPC interface.

Today, the most common REST standard is the JAX-RS specification. By implementing your code along the JAX-RS guidelines you can be rest assured that you can easily switch one REST-RX library with another.

As of today there are a couple of JAX-RS libraries used by the Java community:

  1. Jersey
  2. Restlet
  3. Portlet
  4. etc…

On the other hand, being a big fan of Spring, I was hoping that Spring will provide the JAX-RS support in it’s Spring v3 release, but, looking at the M3 drop, I have realized that it’s nowhere near that promise (check my discussion on the StackOverflow).

For this post I’m going to use Jersey JAX-RS implementation. Let’s start with creating

Read the rest of this entry »

Posted in JAX-RS, JAXB, JSON, Java, Jersey, REST, Tomcat, XML | 1 Comment »

Building fat GWT web clients [Intro] – How to create a GWT RPC client?

Posted by igormoochnick on 05/18/2009

After months of working (mainly fighting with quirks of Java) with GWT I’ve accumulated so much knowledge on the topic so, I feel, it starts spilling over. I’m planning to convert this spill into a series of articles on how to build fat REST-full GWT web fat clients both on Java and .NET.

Here is the list of topics I’ll cover:

  1. Building GWT fat client
  2. Java REST-full Web services
  3. .NET REST-full Web services
  4. Internationalization and localization
  5. IOC/DI
  6. Unit testing and integration testing of all the components of the system
  7. Build automation
  8. and much, much more …

Here is a draft list of technologies I’ll be using:

  1. GWT
  2. Eclipse
  3. Spring
  4. Jersey
  5. Tomcat
  6. XStream
  7. AJAX
  8. JSON/XML
  9. WCF
  10. JUnit/TestND/NUnit
  11. Selenium
  12. Ant
  13. TeamCity
  14. and much, much more …

For starters, let’s see how to create a simple GWT fat client that talks to the REST-full Web services. As an example,

Read the rest of this entry »

Posted in GWT, Java, REST, S+S, Tutorials, Web | 2 Comments »

HTTP Request processing sequence [ HTTP/1.1 (DELETE, GET, HEAD, PUT, POST) ]

Posted by igormoochnick on 03/26/2008

clip_image001

While reading Joe on .NET presentation on AJAX Security and AJAX Patterns I’ve stumbled on a pretty good diagram that describes the sequence of processing an HTTP Request and when, what and what errors will be returned at any different state of the process.

Check out original Alan Dean’s post HTTP/1.1 (DELETE, GET, HEAD, PUT, POST) for more information.

Posted in REST, Security, Tutorials | Leave a Comment »

Exposing dynamic data via RSS feed

Posted by igormoochnick on 02/11/2008

In my recent article “RSS is not only for the news” I’ve mentioned that the current Syndication API is pretty flexible and allows a great deal of control of what is sent over the wire. This allows you to give the client almost anything it asks for. For example your application can provide a graphical information, a binary data, etc… Think about all the different way you can present your data.

Here is a simple example: let’s say you have a resource that is changing over the time (it can be traffic data). You can provide a link to this data and as soon as a user (or another service) navigates there – the data (for example, XML) can be streamed as a response. But what if it’s a real user and you want to be friendly and present this data in a graphical form (render the graph)? You can do that by just adding additional parameter to the URL that will tell your service what format the data can be (should be) presented in.

Remember the feed contract?

[ServiceKnownType(typeof(Atom10FeedFormatter))]
[ServiceKnownType(typeof(Rss20FeedFormatter))]
[ServiceContract]
public interface IFileChangeFeed
{
    // ... other operations

    [OperationContract]
    [WebGet(UriTemplate = "file?path={path}")]
    Stream GetFile(string path);
}

Note that the GetFile request has a URL parameter. In my case the parameter tells the service what file to retrieve, but in your case it can tell your service what data to generate and in what format. [Note: please don't deploy this example on the real systems until you know EXACTLY how and who is accessing your feed. The sample, deployed AS-IS, exposes your system to the external attacks]

The URL request that will be routed to the GetFile method can look like this: http://yourHost/service/location/file?path=fileName.ext

The WCF will find a match in your contract and will call the GetFile method, substituting the “path” variable with the value of the “path” parameter.

public Stream GetFile(string path)
{
    if (File.Exists(path))
    {
        WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";
        WebOperationContext.Current.OutgoingResponse.Headers.Add(HttpResponseHeader.ContentLength,
             new FileInfo(path).Length.ToString());
        return new FileStream(path, FileMode.Open, FileAccess.Read);
    }
    else
    {
        WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound();
        return null;
    }
}

 

This is a pretty straightforward way to return back any type of data, depending on the incoming request. As you can see it’s extremely simple, so unravel your imagination and let REST be your friend!

BTW: Just found an MSDN article, HTTP Programming with WCF and the .NET Framework 3.5,  talks about similar issues and guides you through other REST-related examples.

Posted in C#, REST, Tutorials, WCF | Leave a Comment »