tisdag 12 november 2013

Padding and Masking


Padding and Masking in Groovy vs Java.
Example with zero padding:

       


    
JAVA:

public static String addPreceedingZeros(String str, int len)
    {
        if (str == null)
        {
            return null;
        }
        StringBuilder buf = new StringBuilder(str);
        while (buf.length() < len)
        {
            buf.insert(0, "0");
        }
        return buf.toString();
    }

GROOVY:

def str = '5';
str = str.padLeft(5,'0')



Example with credit card mask:


       

JAVA:

public static String maskCardNumber(String cardNumber, String mask) {

    // format the number
    int index = 0;
    StringBuilder maskedNumber = new StringBuilder();
    for (int i = 0; i &lt; mask.length(); i++) {
        char c = mask.charAt(i);
        if (c == '#') {
            maskedNumber.append(cardNumber.charAt(index));
            index++;
        } else if (c == 'x') {
            maskedNumber.append(c);
            index++;
        } else {
            maskedNumber.append(c);
        }
    }

    // return the masked number
    return maskedNumber.toString();
}

println maskCardNumber("1234123412341234", "*************####")

GROOVY:

def card_number = "1234123412341234"
card_number.replaceFirst('.*(?=.{4})', { match ->; return "".padLeft(match.length(), '*')});

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

Simple currency converter in Groovy Swing Style

Simple currency converter in Groovy Swing Style:

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

 import groovyx.net.ws.WSClient

class TryIt
{
      groovy.swing.SwingBuilder swing = new groovy.swing.SwingBuilder()
      def proxy = new WSClient("http://www.webservicex.net/CurrencyConvertor.asmx?WSDL",                       TryIt.class.classLoader)
      def currency = ['USD', 'EUR', 'CAD', 'GBP', 'AUD', 'SGD','SEK','DKK','NOK']
      def rate = 0.0
      def exc = 1.0
   
     void main()
    {
           proxy.initialize()
           def refresh = swing.action( name:'Refresh', closure:this.&refreshText, mnemonic:'R' )
           def frame = swing.frame(title:'Currency Demo')
           {
                  panel
                 {
                       label 'Currency rate from '
                       comboBox(id:'from', items:currency)
                       label ' to '
                      comboBox(id:'to', items:currency)
                      label ' rate '
                      textField(id:'currency', columns:10, rate.toString(),editable:false)
                      label ' exchange '
                      textField(id:'exchange', columns:10, exc.toString())
                      button(text:'Go !', action:refresh)
               }
          }
          frame.pack()
          frame.show()
   }
   def refreshText(event)
   {
          rate = proxy.ConversionRate(swing.from.getSelectedItem(), swing.to.getSelectedItem())                               swing.currency.text = rate
          swing.exchange.text = rate*Double.parseDouble(swing.exchange.text)
   }
}

new TryIt().main()

Extract input tags from a web page

If you need to extract a specific html-tag from a web page you can do so:

       


@Grapes( @Grab('org.jsoup:jsoup:1.6.1')) 

import org.jsoup.Jsoup; 
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

//Get a web page
Document doc = Jsoup.connect("https://biglietti.italotreno.it/Booking_Acquisto_Ricerca.aspx").get() def results = doc.select("input") 

for (Element src : results) 
{
      if (src.tagName().equals("input"))
      {
             println("tag name: "+ src.tagName()+" id: "+src.attr("id")+" type: "+src.attr("type")+"                  name: "+ src.attr("name"));
      }
}

Simple Groovy Scheduler

How to write a simple scheduler in Groovy? Here you are:
       


      
class GroovyTimerTask extends TimerTask {
    Closure closure
    void run() 
    {
        closure()
    }
}

class TimerMethods 
{
    static TimerTask runEvery(Timer timer, long delay, 

    long period, Closure codeToRun) 
    {
        TimerTask task = new GroovyTimerTask(closure: codeToRun)
        timer.schedule task, delay, period
        task
    }
}

use (TimerMethods) 

{
    def timer = new Timer()
    def task = timer.runEvery(1000, 5000) 

    {
        println "Task executed at ${new Date()}."
    }
    println "Current date is ${new Date()}."
}

Attetion: If you run this code as is, to stop the script you have to kill the GroovyConsole!