Overblog
Suivre ce blog Administration + Créer mon blog
20 octobre 2012 6 20 /10 /octobre /2012 20:29

 

ag2012.jpeg

 

I was at the Agile Tour 2012 in Lausanne Friday 12th October. A good chance to meet up with former coworkers and take time to think about agility in a quiet place, far from my office in London.

 

There were around 60 attendee and 12 Speakers. The conference was in French but it was possible to talk to speakers in english. So far i have seen : 

 

- "How use agility in general project" by Jean-Pierre Rey (HEVS Sierre) . How to use agility in projects that are not in IT sector.

 

- "Scrum Master, snakes and crocodiles" by Jérôme Perakis (We Can Live on Mars). How the Vivarium of Lausanne uses scrum.

 

- Workshop "Agile Dice" by Alex Cuva (Altran). How to calculate velocity.

 

- "How convert to agility a manager used to cascad fall?" par Léonard Bouchet (RTS). Where and why Cascade fall or agility can fail or succes. With an interesting concept of Agile semi-fail : When agile is use only by dev team but not all the company.

I prefer see there a semi-success, because It's probably the most common work environement of current agile pratictionners in IT and even in this case the team is often more efficient and motivated that in a full cascade fall project.

 

 

 

bouchet3

 

 

Léonard Bouchet - Agile Tour Lausanne 2012

 

 

Silvana Wasitova made a short presentation of Wiki Speed : a car developed by methods of fast-moving company software. Very amazing project with already some very good result. For example this car has recently passed a 5 star crash test in all direction.

 

Links :

Agile tour Lausanne : http://at2012.agiletour.org/en/lausanne.html

Wikispeed : http://www.wikispeed.com

Partager cet article
Repost0
6 octobre 2012 6 06 /10 /octobre /2012 22:03

 

agile-london-brandjpg.JPG

 

 

The 4th October 2012 Christopher Marsh talked about Agility in a agency environement. This event was orgnised by Agile London in the AQKA agency. The entrance was free like the beers and crisp. People friendly, it was a nice evening event. 

 

I was specificaly interested about his experience with continuous delivery .

 

His main observations are :

- In a project using a interatif process like scrum, the team needs to make some releases regulary,  to be tested by a QA tester at least.

- Sprint after sprint it becomes more and more time consuming to produce a release and deploy it. This decreases the velocity of the team

 

His solution :

- Make delivery to the QA by a kind of green button: The QA can deployement when he need a build if it is ready

 

The 2 benefits of this :

- Stabilise and minimize the cost of the deployements in a sprint 

- Remove the direct depency between developers and QA testers : Developers have to prepare a stable release at the end of each sprint. QA team can test it when it have time for it.

 

Lot of organisations are reluctant to use continuous delivery because they think it's almost impossible to make the last stage : contiuous deployment in production. Anyway they should use continuous delivery until QA in the purpose to increase the productivity of dev teams and QA teams.

 

Links :

Agile london : http://agilelondon.ning.com

Continuous delivery : http://en.wikipedia.org/wiki/Continuous_delivery

Christopher March : http://www.cjmarsh.com

 

 

 

 

 

 

 

Partager cet article
Repost0
2 avril 2012 1 02 /04 /avril /2012 19:24

 

SA UserGroup France sm1

I attended on the Scrum Day 2012, the 27th March 2012 in Paris.

 

It happend in Espace CAP 15 close to the Seine river and the Eiffel Tower. At least 300 people attended to this conference about Scrum and Agility in France.

 

This conference was constitued of 4 tracks and 3 worksshops.

 

I participated in a Kanban workshop organized by Laurent Morisseau. The objective was to show how use kanban to realease a maximum of business value in a a fixed periode of time. 

 

I really appreciate the session of Thierry Montulé : Scrum aux frontières de la psychologie social (Scrum at the border of the social psychology).  It's a brillant (and funny) attempt to explain how Scrum works according to a sociological analysis.

 

But there was one thing in particular that impresses  me: During a session about Agile Management, Thierry Cos ask "If you have already read the Agile Manifesto could you put your hand up?" 50% of the attendees put their hand up! 

I was very surprised because the majority of them are managers not programmers. I think 2 years ago only developers would know what the Agile Manifesto is.

 

It seems that agility is part of the mainstream in France now and that all main companies use it or try to use it.

 

 

The official web site (in French) : www.scrumday.fr

The news letter of the French Scrum user group (In english and French) : http://paper.li/frenchsug

The program in English : http://agileinspearit.wordpress.com/2012/03/09/27th-march-inspearit-at-scrum-day-2012-in-paris

Partager cet article
Repost0
16 mars 2012 5 16 /03 /mars /2012 22:04

 

spring-logo.jpeg

 

The purpose of this tutorial is to explain how to do a minimal REST Application with Spring MVC in a Maven project. 

This is illustrated by the creation of a REST Controller able to Create, Update, Delete some entity Computer.

 

So in this tutorial we will use this java class

 

public class Computer {

 

  private long id;

  private String brand;

  private String model;

  private String reference;

  private String description;

 

    // getter and setter ...

}

 

and some JSON computer objects as in this example :

{

     "id":1,"reference":"MACR","description":"Test","model":"Macbook Air","brand":"Apple"

}

 

I will not talk here about how to do a REST service really REST compliant, about best practice, or explain what exactly REST is.

I will just show how to implement 4 Basic REST Http Methods with Spring MVC, and how configure Spring MVC to do this. 

If you are in a rush you can go here : http://www.davidgimelle.com/src/SpringREST.zip, dowload this project, install it with Maven, deploy it on an application server and go there http://localhost:8080/SpringREST/rest/computer to see if it works. It should return the content of an empty json array []. But all the same it might be worth reading this first.

 

0) Introduction about REST and Spring MVC annotation in 10 lines

Spring MVC for REST uses the JSON format to exchange data with HTTP protocole. Spring MVC manages Http requests /responses and makes transformations JSON<->Java pojo.  

REST uses mainly 4 Http methods GET, POST, PUT and DELETE. If you are new to REST you should read this paragraph in wikipedia : http://en.wikipedia.org/wiki/Representational_state_transfer#RESTful_web_services

 

Spring MVC provides some annotation to manage Http. In this tutorial i will use only 5 :

@Controller --> Declare a Spring MVC Controller

@RequestMapping("/computer") --> Map an URI with a controller or a method

@PathVariable --> Read a variable in an Uri and assign this value to a java variable

@RequestBody --> Declare a Pojo class to map the http request body  

@ResponseBody --> Declare a Pojo class to generate Json content to return to the http client

 

1) Create a controller with a GET method      

So let see the declaration of a Controller in Java.

The Class ComputerController is a controller to handle all REST requests about entities Computer.

 

// Declaration as this class as a controller

@Controller 

// Declaration that this controller handles requests on uri */computer

@RequestMapping("/computer"

public class ComputerController {

 

 // Stores computers

 private static final ComputerStorage computerStorage = new ComputerStorage();

 

 // Declare a method that handle all GET request on */computer

 @RequestMapping(method = RequestMethod.GET)

 // Return a list of computer to the http client

 public @ResponseBody List<Computer> getComputers() {

  return computerStorage.getAll();

 }

}

 

2) Configure the application

It's a standard Spring mvc configuration, with nothing special for REST.

- Spring mvc must be declared in the web.xml :

 

 <servlet>

   <servlet-name>mvc-dispatcher</servlet-name>

   <servlet-class>

    org.springframework.web.servlet.DispatcherServlet

    </servlet-class>

   <load-on-startup>1</load-on-startup>

 </servlet>

 

 <servlet-mapping>

   <servlet-name>mvc-dispatcher</servlet-name>

   <url-pattern>/rest/*</url-pattern>

 </servlet-mapping>

 

 <context-param>

   <param-name>contextConfigLocation</param-name>

   <param-value>

    /WEB-INF/mvc-dispatcher-servlet.xml

   </param-value>

 </context-param>

 

 <listener>

   <listener-class>

    org.springframework.web.context.ContextLoaderListener

    </listener-class>

 </listener>

 

The Servlet mapping of the mvc-dispatcher redirects all requests on */rest/* to Spring MVC.

So it's possible to request the computer controller by a GET on http://localhost:8080/SpringREST/rest/computer .

 

SpringREST is the default name of the application, you can change it when you deploy the war. 

 

- The file mvc-dispatcher-servlet.xml discribes REST controllers. Because we use annotation base declaration of controllers, we just need to set witch packages contain controllers with the context:component-scan declaration.

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd

http://www.springframework.org/schema/mvc

http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

 

 <context:component-scan 

 base-package="com.davidgimelle.springrest.tuto" 

 />

 

 <mvc:annotation-driven />

 

</beans>

 

 <display-name>Spring REST Application</display-name>


3) Add methods POST, PUT and DELETE to the controller

Now complete the controller with 3 more methods.

 

- The POST method add one computer. 

@RequestMapping(method = RequestMethod.POST)

@ResponseBody 

public void addComputer(@RequestBody Computer computer) {

  computerStorage.add(computer);

}

@RequestBody indicate to the server that the json content of the request is use to fill a new Computer instance.

@ResponseBody alone is required on void method to return no content to the REST Client .

 

- The PUT method update one computer. 

@RequestMapping(value="{id}",method = RequestMethod.PUT)

@ResponseBody

public void putComputer(@PathVariable long id, @RequestBody Computer computer) {

  computer.setId(id);

  computerStorage.update(computer);

}

Following the rest convention, the id of the entity to update is set in the uri like in this example : PUT on http://localhost:8080/SpringREST/rest/computer/6 .

Set the id in the uri and not in the json content respect the REST convention. You can see the PUT convention here : http://en.wikipedia.org/wiki/Representational_state_transfer#RESTful_web_services .

 

@RequestMapping completes the request mapping of the controller with the id and the @PathVariable assigns the value to the long id.

 

-A DELETE method delete a computer.

@RequestMapping(value="{id}", method = RequestMethod.DELETE)

@ResponseBody

public void deleteComputer(@PathVariable long id) {

  computerStorage.delete(id);

}

 

4) How to test it ?

You can  use RestClient, a firefox's plugin to test the Rest application : https://addons.mozilla.org/en-US/firefox/addon/restclient/ . 

 

  - Start by testing a GET on http://localhost:8080/SpringREST/rest/computer .

The response body (Visible in the panel Response Body of Rest Client Plugin) will be an empty array because there is no data yet : []

 

  - Test POST http://localhost:8080/SpringREST/rest/computer

Before sending the request, add an http header Content-Type with the button Add Request Header of Rest client : Content-Type:application/json; charset=utf-8

add a JSON content in the request body 

  {"reference":"MAC","description":"Test","model":"MB Pro","brand":"Apple"}

  - Now the GET should return 

  [{"id":1,"reference":"MAC","description":"Test","model":"MB Pro","brand":"Apple"}]

 

  - Do a second POST

  - Now the GET should return 

 [{"id":1,"reference":"MAC","description":"Test","model":"MB Pro","brand":"Apple"},  {"id":2,"reference":"MAC","description":"Test","model":"MB Pro","brand":"Apple"}]

 

  - Delete a computer with a PUT on http://localhost:8080/SpringREST/rest/computer/2

  - GET return now

 [{"id":1,"reference":"MAC","description":"Test","model":"MB Pro","brand":"Apple"}]

 

  - Update a computer with a PUT on http://localhost:8080/SpringREST/rest/computer/1 with

Content-Type:application/json; charset=utf-8

add a JSON content in the request body 

 {"reference":"MACR","description":"Test","model":"Macbook Air","brand":"Apple"}

  - GET return 

 [{"id":1,"reference":"MACR","description":"Test","model":"Macbook Air","brand":"Apple"}]

 

 

5) Jackson JSON Processor

Jakson JOSN Processor is used by Spring to make the mapping JSON <-> Java Object. Since spring 3.0.2, it uses by default if it presents in the classpath of the application.

 

6) How to use Maven ?

It's the same declaration that for Spring MVC with a dependency on JSON Processor : 

<dependency>

     <groupId>org.codehaus.jackson</groupId>

    <artifactId>jackson-mapper-asl</artifactId>

    <version>1.7.1</version>

</dependency>

You can find the entire pom.xml it in the source of this article.

 

7) Where are the source of this article ?

You can dowload it here : http://www.davidgimelle.com/src/SpringREST.zip

 

Thanks for reading. The next time i will talk about more advanced features such as Handle Error or Http parameters.

 

 

Links

REST : http://en.wikipedia.org/wiki/Representational_state_transfer

 

An other tutorial : http://www.mkyong.com/spring-mvc/spring-3-mvc-and-json-example

Springsource example : http://static.springsource.org/spring-security/site/petclinic-tutorial.html

Jackson JSON processor : http://jackson.codehaus.org

REST and HTTP : http://www.packetizer.com/ws/rest.html

Firefox Rest Client :  https://addons.mozilla.org/en-US/firefox/addon/restclient

 

Technical Specifications

Spring mvc 3.0.5 use Jackson JSON processor 1.7.1 to marchal/unmarchal Java/JSON

Tested 11th March 2012 with Spring 3.0.5, Glassfish 3.1.1, Java 1.6.0_29, Mac OSX 10.6.8

 

Partager cet article
Repost0
9 octobre 2011 7 09 /10 /octobre /2011 17:11

sshake2011.jpg

 

I was at the Second Edition of Softshake in Geneva this week. 2 Days of presentations and demonstrations about Java, Agility, Mobility and new Programming Languages.

 

I spend 50% of my time to discovert some new features in Java 7 and the JVM. I appreciated the presentation of Fork/Join framework in Java SE 7 by Julien Ponge.

 

It was also my chance to try some functional languages like Erlang and Clojure.

 

It was great conference and i will attend to the next in 2012.

 

 Links : SoftShake

Partager cet article
Repost0
29 septembre 2011 4 29 /09 /septembre /2011 13:16

visa

A little word about my current project in London :

 

It's official. Visa Europe will launch a new Android application for Person to Person Payement. With this application an user in europe will be able to send money from his visa card to an other visa card. 

I am very happy to work on this project. It will be an very usefull and handy application.

 

You can find more information in those links :

http://www.pocket-lint.com/news/42293/visa-takes-on-paypal-mobile

http://techblog.weblineindia.com/news/visa-announces-payment-application-for-android-users

http://www.finextra.com/News/Fullstory.aspx?newsitemid=23011

 

 

Partager cet article
Repost0
20 mai 2011 5 20 /05 /mai /2011 13:27

hibernate-icon.jpeg

 

Why a NonUniqueObjectException is thrown ? 

 

A NonUniqueObjetException is thrown because hibernate is not able to decide what version of an entity it has to persist.

 

In this case, it will throw something like this :

org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.davidgimelle.hibernate.examples.Role#1]

at org.hibernate.engine.StatefulPersistenceContext.checkUniqueness(StatefulPersistenceContext.java:590)

at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performUpdate(DefaultSaveOrUpdateEventListener.java:284)

at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:223)

at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:89)

at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)

at org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:507)

at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:499)

at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:495)

at com.davidgimelle.hibernate.examples.TestLostSession.commitADetachedObjetThrowAnNonUniqueObjectException(TestLostSession.java:53)

This exception has been thrown because hibernate has tried to persist 2 instances of the same entity, with the same id but not the same content.

For example : role1(id:1, name:"admin") and role2(id:1,name"user")

 

Usually that happens when an entity is persisted and detached from the session. Another instance of this entity is requested to hibernate. This second instance stayed attached to the session. The first instance is modified.

 

When hibernate persit the second instance, it is not able to choose what is the correct content to persist and throw an NonUniqueObjectException. 

 

It easier to understand with an example. This piece of code will throw and display an NonUniqueObjectException :

 

Role role = new Role().withName("Customer");

 

 //Persist a first Role Entity and close the session

Session openSession = sessionFactory.openSession();

Transaction beginTransaction = openSession.beginTransaction();

openSession.persist(role);

beginTransaction.commit();

openSession.close();

 //Now role is detached from the session

 

 //change a value in this role

role.setName("new role Name");

 

 //Open a new session

openSession =sessionFactory.openSession();

 

 //Instanciation of the same role from the new session

Role roleFromDB= (Role) openSession.get(Role.class, role.getId());

 //Now role and roleFromDB have the same id, but role is detached

 

Transaction beginTransaction2 = openSession.beginTransaction();

 

 

 //The next line will throw an exception

try{

 //Save role and throw an exception

openSession.saveOrUpdate(role);

 

//This line will be never executed

beginTransaction2.commit();

Assert.fail();// Fail this test if this line is reached

}

catch(NonUniqueObjectException nuoe){

//Display this exception

nuoe.printStackTrace();

}

openSession.close();

 

You can find a complet maven project able to run this exemple in a Junit test at http://www.davidgimelle.com/src/hibernate_examples_dg-src.1.1.1-SNAPSHOT.zip 

 

References    

- SaveOrUpdate versus Merge : http://www.stevideter.com/2008/12/07/saveorupdate-versus-merge-in-hibernate

- Saving detached entities : http://blog.xebia.com/2009/03/jpa-implementation-patterns-saving-detached-entities

Partager cet article
Repost0
26 janvier 2011 3 26 /01 /janvier /2011 17:41

 

jquery.jpeg

Voici comment faire une requête Ajax de type GET avec JQuery coté navigateur, RESTEasy coté Serveur et JSON entre les 2.

 

Les sources complètes de ce projet sont disponible sous la forme d'un projet maven téléchargeable à la fin de ce billet.

 

 

Ajax, JQuery, JSON, RESTEasy qu'est ce que c'est ?

 

Ajax : Ajax est une technologie permettant de faire des requêtes asynchrones depuis un navigateur web vers un serveur web avec http en utilisant Javascript.  Ajax permet via du javascript d'aller faire un appel à n'importe quel serveur web sans changer de page web dans le navigateur. 

 

JQuery :  JQuery est une bibliothèque Javascript Crossbrowser, c'est a dire qu'un code javascript écrit avec Jquery fonctionnera aussi bien avec Firefox que IE ou Opera. JQuery permet de faire des requetes Ajax.

 

GET : Les méthodes d'appel Ajax dans une architecture REST sont les méthodes HTTP classiques principalement GET et POST. Dans ce billet nous allons faire un GET HTTP.

 

JSON : Un format de données utilisable directement en Javascript. Il ressemble à du XML ultra simplifié. C'est ce format qui sera utilisé pour les échanges de données entre le serveur web et jquery

 

RESTEasy : Une implementation de REST , repectant la spécification JAX-RS, proposé par JBOSS pour publier des ressources REST.

 

Voici comment vous s'enchaîner ces technologies lors de l'exécution du Hello world de ce tuto :

 

- L'utilisateur ouvre une page html qui contient du code JQuery

- Il clique sur le bouton d'essai, ce qui déclenche une fonction javascript

- Cette fonction javascript utilise JQuery pour faire un GET sur le serveur RESTEasy

- Le serveur RESTEasy génère un fichier JSON et l'envoie à JQuery

- JQuery récupère le fichier JSON et le fourni à javascript

- Une boite d'alerte javascript affiche le contenue du fichier JSON

 

 Assez de théories, passons à la pratique, grace à ce tutorial en 5 étapes.

 

 

Mise en place de la ressource REST avec RESTEasy

 

Mise en place du serveur REST . Cette partie à déjà été décrite dans mon précédant billet sur RESTEasy : Mini Tutorial : REST Web Service avec JBoss RESTEasy . Aussi je ne vais reprendre ici que les grandes lignes.

 

1 - Déclaration des dépendances et des repositories dans le pom maven :

    Le repository de jboss est nécessaire pour récupérer la version 2.0-beta-2 de RESTEasy.

 

<repositories>
        <repository>
            <id>maven repo</id>
            <name>maven repo</name>
            <url>http://repo1.maven.org/maven2/</url>
        </repository>
        <!-- For resteasy -->
        <repository>
            <id>jboss</id>
            <name>jboss repo</name>
            <url>http://repository.jboss.org/maven2</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxrs</artifactId>
            <version>2.0-beta-2</version>
            <!-- filter out unwanted jars -->
            <exclusions>
                <exclusion>
                    <groupId>commons-httpclient</groupId>
                    <artifactId>commons-httpclient</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.servlet</groupId>
                    <artifactId>servlet-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jettison-provider</artifactId>
            <version>2.0-beta-2</version>
        </dependency>
    </dependencies>

 

2 - Déclaration de RESTEasy dans web.xml

 Voir ce billet : Mini Tutorial : REST Web Service avec JBoss RESTEasy

 

3 - Déclaration de la Classe World pour générer du JSON

Créons une classe World avec un champs message. Notre objectif est de faire passer un objet World Java avec son message dans le javascript du navigateur sous forme d'un objet World JSON avec le même message.

 

package com.davidgimelle.tutorial.resteasyjquerygetjson.element;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "world")
public class World {

    private String message;

    @XmlElement
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

 

Les annotations XML vont être transformées lors de l'utilisation de RESTEasy en JSON. Et ainsi l'instance Java suivante 

  World myWorld  = new World();

  myWorld.setMessage("Hi");

va devenir le fichier JSON suivant dans le navigateur

  {"world":{"message":"Hi"}}

 

4 - Déclaration du service RESTEasy pour publier la classe World

Cette classe va lire un message reçu depuis le navigateur, générer une instance de World et la transformer en JSON.

A ce stade du projet, une fois déployée cette ressource est disponible sous l'url :  http://localhost:8080/RESTEasyTutorialJQueryGetJSON/rest/hello/world/Hi

 

L'annotation @Produces(MediaType.APPLICATION_JSON) précise que le format envoyé par la ressources est JSON. Mais il aurait très bien pu être du XML, ATOM ou autres.

Pour comprendre la significations des autres annotations consulter ce billet : Mini Tutorial : REST Web Service avec JBoss RESTEasy

 

package com.davidgimelle.tutorial.resteasyjquerygetjson;

import com.davidgimelle.tutorial.resteasyjquerygetjson.element.World;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("hello")
public class HelloWorld {

    @GET
    @Path("/world/{message}")
    @Produces(MediaType.APPLICATION_JSON)
    public World helloWorldJSON(@PathParam("message") String message){
        World res=new World();
        res.setMessage(message);
        return res;
    }

}

 

La partie serveur RESTEasy est terminée, passons à la partie client.

 

 

Ecriture d'une fonction d'appel Ajax avec JQuery

 

5 Déclaration d'une page HTML executant JQuery

 

  <html>
    <head>
        <title>RESTEasy Tutorial JQuery Get JSON</title>

         <script type="text/javascript" src="inc/jquery-1.4.2.min.js" language="JavaScript"></script>
         <script type="text/javascript">
            function getHelloWorld(message){
                $.getJSON("./rest/hello/world/"+message,
                    function(dataJson){
                        alert("Message extract from Json:"+dataJson.world.message);
                    }
                );
            }
         </script>

    </head>
    <body>
        For try an Get JQUERY with 'Salut' value, try this button : <button onclick="getHelloWorld('Salut');" >Salut</button>
    </body>
</html>

 

- La ligne <script type="text/javascript" src="inc/jquery-1.4.2.min.js" language="JavaScript"></script> permet d'inclure dans la page la bibliothèque JQuery qui se trouve sur le même serveur que la page html dans le repertoire inc

 

- Le script javascript est la  function getHelloWorld(message)

 

- La fonction JSON est

$.getJSON("./rest/hello/world/"+message,
                    function(dataJson){
                        alert("Message extract from Json:"+dataJson.world.message);
                    }
                );

 

- Le $ est un alias pour appeler la bibliothèque JQuery

- getJSON est la fonction jquery qui va faire un appel GET Ajax sur une ressources JSON

./rest/hello/world/"+message est l'url du serveur, plus la valeur du message à envoyer au serveur

 

- function(dataJson) est la fonction de callback qui est executée dès que JQuery a recu la reponse du serveur. 

dataJson contient les infos json renvoyées par le serveur

dataJson.world.message permet de récupérer la valeur du message dans l'objet JSON

 

C'est terminé. :)

 

 

Sources : 

Les sources complétes de ce tutorial sont disponibles sous forme d'un projet maven  téléchargable : RESTEasyTutorialJQueryGetJSON-src

 

Testé le 18 juillet 2010 avec :

resteasy-jaxrs 2.0-beta-2 , JBoss 4.2.3, Java jdk 1.5_20, maven 2.0.9 et netbeans 6.7.1

 

Liens et références :  

Mini tutorial sur RESTEasy : Mini Tutorial : REST Web Service avec JBoss RESTEasy

Ajax : http://en.wikipedia.org/wiki/Ajax_%28programming%29

Crossbrowser : http://en.wikipedia.org/wiki/Cross-browser

JQuery : http://jquery.com/

JSON : http://www.json.org/

Les exemples de RESTEasy : http://sourceforge.net/projects/resteasy/files/Resteasy%20JAX-RS/

JQuery et JSON: http://api.jquery.com/jQuery.getJSON/

RESTFull : http://tomayko.com/writings/rest-to-my-wife

REST: http://en.wikipedia.org/wiki/Representational_State_Transfer

 

Partager cet article
Repost0
12 juin 2010 6 12 /06 /juin /2010 10:00

resteasylogo.jpg

Voici un mini tutorial sur JBoss RESTEasy, l'implementation de JAX-RS 1.2.GA de JBoss avec le serveur JBoss 5.1. Ce mini tutorial est directement inspiré de l'excellent tutoriel de Damien Gouyette : Exposer un service crud RESTul avec JBoss RESTasy  http://dgouyette.developpez.com/tutoriels/java/exposer-service-crud-restful-avec-jboss-resteasy/

 

J'ai eu quelques misères à en faire fonctionner les sources et à récupérer les bonnes versions des bibliothèques sous maven avec netbeans,  aussi en m'inspirant des sources de Damien Gouyette j'ai eu l'idée de me faire un mini projet pilote, un genre de CRUD sans le C ni le U, ni le D, bref juste un READ, c a d un GET dans le monde REST.

 

Et finalement j'en fait un mini tutorial que je poste sur mon blog. Les sources complètes du projet sous maven sont disponible à la fin de l'article dans un zip.

 

L'objet de tutorial est de faire un appel Rest GET de la forme : http://localhost:8080/RestEasyTutorial/rest/hello/bill .

il s'agit de l'appel d'une des ressources des services REST du site http://localhost:8080/RestEasyTutorial . La ressource se nomme hello et l'identifiant est bill dans cet exemple. Cet appel va retourner hello bill

 

La déclaration des ressources se fait via des annotations dans une classe Java :

 

package com.davidgimelle.tutorial.resteasyread;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("hello")
public class HelloWorld {

    @GET
    @Path("/{qui}")
    public Response echoService(@PathParam("qui") String message) {
        return Response.status(200).entity("hello "+message).build();
    }

}

 

- L'annotation @Path sur la classe détermine le nom de la ressource.

- @GET précise quelle méthode sera appelée en cas de requête Http GET sur cette ressource.

- @Path sur la méthode précise la forme des paramètres sur la ressource

- @PathParam précise quel paramètre va être utilisé dans la méthode

 

 

Ces classes de ressources REST doivent être déployées dans une application web. Cette application web nécessite un fichier web.xml qui va définir comment est configurer RESTEasy :


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <display-name>RestEasyTutorial</display-name>
   

   <context-param>
      <param-name>resteasy.scan</param-name>
      <param-value>true</param-value>
   </context-param>

    <context-param>
        <param-name>resteasy.servlet.mapping.prefix</param-name>
        <param-value>/rest</param-value>
    </context-param>

    <listener>
        <listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
    </listener>

    <servlet>
        <servlet-name>Resteasy</servlet-name>
        <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>Resteasy</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

</web-app>

 

- Le context-param resteasy.scan à true signifie que les sources du war vont être scannées à la recherche des annotations RESTEasy pour publier les ressources automatiquement lors du démarrage de l'application.

- Le servlet-mapping RESTEasy avec la valeur /rest/* précise que tous les appels de cette forme sont à destination de RESTEasy.

 

 

Les dépendances maven nécessaires au bon fonctionnements de RESTEasy sont les suivantes :

 

    <repositories>
        <repository>
            <id>jboss</id>
            <url>http://repository.jboss.com/maven2/</url>
        </repository>
    </repositories>

    <dependencies>


        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxrs</artifactId>
            <version>1.2.GA</version>
        </dependency>


    </dependencies>

 

Le repository http://repository.jboss.com/maven2/ permet de télécharger la dépendance resteasy-jaxrs.

 

 

Ce mini tuto est terminé. Vous pouvez tétécharger les sources du projet maven complet de ce mini tuto ici.

 

N'oubliez pas de suivre le tutorial de Damien Gouyette pour bien comprendre comment fonctionne REST, comment faire un CRUD et surtout comment faire des tests automatisées des services RESTEasy. On ne test jamais assez. !

 

 

Sources : http://www.davidgimelle.com/src/RestEasyReadTutorial-src.zip

 

Testé le 10 juin 2010 avec :

resteasy-jaxrs 1.2.GA, JBoss 5.1.0.GA, Java jdk 1.5_20, maven 2.0.9 et netbeans 6.7.1

 

Références :

Le tutorial de Damien Gouyette : http://dgouyette.developpez.com/tutoriels/java/exposer-service-crud-restful-avec-jboss-resteasy/

JBoss RestEasy : http://www.jboss.org/resteasy

Rest dans wikipedia : http://en.wikipedia.org/wiki/Representational_State_Transfer

Pour acheter des objets RestEasy : http://www.cafepress.co.uk/jbossorg/7097895

 

Partager cet article
Repost0
11 juin 2010 5 11 /06 /juin /2010 11:24

 

glassfish_logo_large_transparent.png

La prochaine présentation du GenevaJUG est consacrée à EE6 et GlassFish v3.

 

Cette présentation est faite par Alexis Moussine-Pouchkine.

 

Partager cet article
Repost0

Summary

  • : GetJ2ee -Java development
  • : Articles about Java and EE
  • Contact

Profil

  • David Gimelle
  • Java Developer for more 10 years. I worked in France, Canada and Switzerland. I am contractor in London since 2010.
  • Java Developer for more 10 years. I worked in France, Canada and Switzerland. I am contractor in London since 2010.

Contact

You can contact me here

or by Twitter

Search

Archives