onsdag 6 november 2013

Groovy Web Service

It's very simple to create a web service with Groovy, look a this:
       

@Grab(group='org.codehaus.groovy.modules', module='groovyws', version='0.5.2')
import groovyx.net.ws.WSServer
import java.security.SecureRandom
 import java.math.BigInteger
class UtilsService
{
     double add(double arg0, double arg1)
     {
          return (arg0 + arg1)
     }

    double square(double arg0)
    {
         return (arg0 * arg0)
    }
 
   String randomPassword()
   {
       SecureRandom random = new SecureRandom()
       return new BigInteger(130, random).toString(32)
   }

   long random()
  {
         Random random = new Random();
         long randInt = random.nextLong()
        if (randInt < 0) 
        {  
            randInt = randInt*-1L; 
        } return randInt;
  }

  String randomPhrase()
  {
      String[] randomStrings = new String[4];
      Random random = new Random();
      for(int i = 0; i < randomStrings.length; i++)
     {
          char[] word = new char[random.nextInt(8)+3];
         // words of length 3 through 10. (1 and 2 letter words are boring.)
          for(int j = 0; j < word.length; j++)
         {
            word[j] = (char)(99 + random.nextInt(26));
         }
         randomStrings[i] = new String(word);
     }
     String words = "";
     for(String word:randomStrings)
     {
         words+= word+" ";      
     }
     return words.trim();
 }
 
}
def server = new WSServer()
//Start your service
server.setNode("UtilsService", "http://localhost:6980/UtilsService")
server.start()


Now you can test this with SoapUI or with this code:

       

@Grab(group='org.codehaus.groovy.modules', module='groovyws', version='0.5.2')

import groovyx.net.ws.WSClient

def proxy = new WSClient("http://localhost:6980/UtilsService?WSDL", this.class.classLoader) proxy.initialize()

 result = proxy.add(23.88, 24.88)
println "You are sum is: "+result

Inga kommentarer:

Skicka en kommentar