import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
class RestAuthenticationSignatureGenerator {
  static String ALGORITHM_HMAC_SHA1 = "HmacSHA1";
  static String CHARACTER_ENCODING = "UTF-8"
  static String requestDate = "2020-03-02T17:58:00Z"
  static String PARAM_CONTENT_TYPE = "application/json"
  static String requestUri = "POST /v1/businessUnits"
  static String requestApiKey = "D0HP6ae1oWxlRmHwFNfTF3k4zy6VYxXD0HP6"
 public static void main(String ... args){
   println new RestAuthenticationSignatureGenerator().
   generateSignature('testMethod','application/json',requestDate,requestUri,requestApiKey)
 }
  /**
   * Generate the HMAC signature for the given {@link RestAuthenticationParameters} and secret key.
   */
  String generateSignature(RestAuthenticationParameters authParams, String secretKey) {
    generateSignature(authParams.method, authParams.contentType, authParams.date, authParams.uri, secretKey)
  }
  /**
   * Generate the HMAC signature for the given request parameters and secret key.
   */
  String generateSignature(String requestMethod, String contentType, String date, String requestUri, String secretKey) {
    // Determine the string to be signed based on the request params
    String stringToSign = """${requestMethod}
${contentType}
${date}
${requestUri}"""
    calculateRFC2104HMAC(stringToSign, secretKey)
  }
  /**
   * Calculate the HMAC of the given data and key, i.e. the calculated signature to compare against the provided one.
   */
  private String calculateRFC2104HMAC(String data, String key) {
    SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(CHARACTER_ENCODING), ALGORITHM_HMAC_SHA1);
    Mac mac = Mac.getInstance(ALGORITHM_HMAC_SHA1);
    mac.init(signingKey);
    byte[] rawHmac = mac.doFinal(data.getBytes(CHARACTER_ENCODING));
    return rawHmac.encodeBase64().toString()
  }
  class RestAuthenticationParameters {
  static public final String PARAM_API_KEY = "x-tau-rest-apikey";
  static public final String PARAM_CONTENT_TYPE = "content-type";
  static public final String PARAM_DATE = "date";
  static public final String PARAM_SIGNATURE = "x-tau-rest-signature";
  /**
   * @param requestUri String uri of the request, i.e. uriInfo.requestUri.path
   * @param requestMethod String name of the request method
   * @param requestHeaders A Map of String keys and either String or List<String> values
   */
  public RestAuthenticationParameters(String requestUri, String requestMethod, Map requestHeaders) {
    apiKey = getParamValue(requestHeaders, PARAM_API_KEY);
    contentType = getParamValue(requestHeaders, PARAM_CONTENT_TYPE);
    date = getParamValue(requestHeaders, PARAM_DATE);
    method = getCleanedValue(requestMethod);
    signature = getParamValue(requestHeaders, PARAM_SIGNATURE);
    uri = getCleanedValue(requestUri);
  }
  public String apiKey;
  public String contentType;
  public String date;
  public String method;
  public String signature;
  public String uri;
  @Override
  public String toString() {
    return PojoToStringTools.buildString(this, "apiKey", "contentType", "date", "method", "uri");
  }
  private String getParamValue(Map requestParams, Object key) {
    Object mapVal = requestParams.get(key);
    String valStr = null;
    if (mapVal != null) {
      if (mapVal instanceof CharSequence) {
        valStr = mapVal.toString();
      }
      else if (mapVal instanceof Collection) {
        Collection valColl = (Collection) mapVal;
        Object firstVal = valColl.isEmpty() ? null : valColl.iterator().next();
        if (firstVal instanceof CharSequence) {
          valStr = firstVal.toString();
        }
      }
    }
    return getCleanedValue(valStr);
  }
  private String getCleanedValue(String value) {
    return (value != null) ? value : "";
  }
}
} 

Groovy online compiler

Write, Run & Share Groovy code online using OneCompiler's Groovy online compiler for free. It's one of the robust, feature-rich online compilers for Groovy language, running the latest Groovy version 2.6. Getting started with the OneCompiler's Groovy editor is easy and fast. The editor shows sample boilerplate code when you choose language as Groovy and start coding.

Read inputs from stdin

OneCompiler's Groovy online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample Groovy program which takes name as input and prints hello message with your name.

def name = System.in.newReader().readLine()
println "Hello " + name

About Groovy

Groovy is an object-oriented programming language based on java. Apache Groovy is a dynamic and agile language which is similar to Python, Ruby, Smalltalk etc.

Key Features

  • It's not a replacement for java but it's an enhancer to Java with extra features like DSL support, dynamic typing, closures etc.
  • Accepts Java code as it extends JDK
  • Greater flexibility
  • Concise and much simpler compared to Java
  • Can be used as both programming language and scripting language.

Syntax help

Data Types

Data typeDescriptionRange
StringTo represent text literalsNA
charTo represent single character literalNA
intTo represent whole numbers-2,147,483,648 to 2,147,483,647
shortTo represent short numbers-32,768 to 32,767
longTo represent long numbers-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807
doubleTo represent 64 bit floating point numbers4.94065645841246544e-324d to 1.79769313486231570e+308d
floatTo represent 32 bit floating point numbers1.40129846432481707e-45 to 3.40282346638528860e+38
byteTo represent byte value-128 to 127
booleanTo represent boolean values either true or falseTrue or False

Variables

You can define variables in two ways

Syntax:

data-type variable-name;

[or]

def variable-name;

Loops

0.upto(n) {println "$it"}

or

n.times{println "$it"}

where n is the number of loops and 0 specifies the starting index

Decision-Making

1. If / Nested-If / If-Else:

When ever you want to perform a set of operations based on a condition or set of conditions, then If / Nested-If / If-Else is used.

if(conditional-expression) {
  // code
} else {
  // code
}

2. Switch:

Switch is an alternative to If-Else-If ladder and to select one among many blocks of code.

switch(conditional-expression) {    
case value1:    
 // code    
 break;  // optional  
case value2:    
 // code    
 break;  // optional  
...    
    
default:     
 //code to be executed when all the above cases are not matched;    
} 

List

List allows you to store ordered collection of data values.

Example:

def mylist = [1,2,3,4,5];
List MethodsDescription
size()To find size of elements
sort()To sort the elements
add()To append new value at the end
contains()Returns true if this List contains requested value.
get()Returns the element of the list at the definite position
pop()To remove the last item from the List
isEmpty()Returns true if List contains no elements
minus()This allows you to exclude few specified elements from the elements of the original
plus()This allows you to add few specified elements to the elements of the original
remove()To remove the element present at the specific position
reverse()To reverse the elements of the original List and creates new list