import com.sap.it.api.mapping.*;
import groovy.util.slurpersupport.GPathResult
import groovy.xml.StreamingMarkupBuilder
import java.text.NumberFormat;
import java.lang.Number;
import java.text.DecimalFormat;
import java.util.Locale;



def  GPathResult processXMLData(String message) {
    if(null == message){
	    return
	}
	return new XmlSlurper().parseText(message)

}

def String getSuperCategoryBaseProductCode(String matlName, String charName, String charValue, MappingContext context){
	return determineVariantAttributesCode(matlName,charName,charValue,context,getRelevantCharProfAttributes(context), getRelevantMatlCatAttributes(context))
}

def String getSuperCategoryCode(String matlName, String charName, String charValue, String charValueFloatFrom, String charValueFloatTo, String dependencyCode, MappingContext context){
    def String code = determineVariantAttributesCode(matlName,charName,charValue,context,getRelevantCharProfAttributes(context), getRelevantMatlCatAttributes(context))
    def String returnCharValue;
 
    if(null != code && !code.equals('')){
       def chrmas = processXMLData(context.getProperty(charName+'CHRMAS_XML'))
		//check dataType
	   def dataType = chrmas.IDOC.E1CABNM.ATFOR.text()
		//check rangesAllowed
	   def rangesAllowed = null
	   if(chrmas.IDOC.E1CABNM.ATINT.size()> 0){
	        rangesAllowed = chrmas.IDOC.E1CABNM.ATINT.text()
	   }
	   if(dataType.equals('NUM')) {
            def artmas = processXMLData(context.getProperty('ARTMASXMLFORMAT'))
            if(rangesAllowed != null && rangesAllowed.equals('X')){
	               returnCharValue = convertNumberRangeForVariantValueID(charValueFloatFrom, charValueFloatTo, dependencyCode)
	        }else{
                returnCharValue = charValue.split(' ')[0]
	        }
	    }
	    else {// CHAR
		    returnCharValue = charValue
	    }    
        
        return code+'_'+returnCharValue
    }else{
        return ''
    }   
}



def String determineVariantAttributesCode(matlName,charName,charValue,context,relevantAttributes,relevantMatlCatAttributes) {
	def String CHAR_PROF= context.getProperty("CHAR_PROF");
	def String BASE_ARTICLE_ID= context.getProperty("MATERIAL_CODE");
	def String MATL_GROUP= context.getProperty("MATL_GROUP");
	def String finalString =''

    def boolean additionalValueExists = context.getProperty("additionalValueExists")
	if(relevantAttributes.contains(charName)){ //This means the attribute is from CHAR_PROF 
	    if(!additionalValueExists) {
	        //NO ADDN VALUE
		    finalString= CHAR_PROF+'_'+charName
	    }else{
	        //ADDN VALUE
	        finalString= BASE_ARTICLE_ID+'_'+charName
	    }
	}else if(relevantMatlCatAttributes.contains(charName)){ //This means the attribute is fron MATL_GROUP 
	    if(!additionalValueExists) {
	        //NO ADDN VALUE
		    finalString= MATL_GROUP+'_'+charName
	    }else{
	        //ADDN VALUE
	        finalString= BASE_ARTICLE_ID+'_'+charName
	    }
	}
	return finalString
}

def getRelevantCharProfAttributes(context){
	def String CHAR_PROF= context.getProperty("CHAR_PROF");
	def String CHAR_PROF_CLSMAS_XML= context.getProperty(CHAR_PROF+'CLSMAS_XML');

	def relevantAttributes=[]
	
	if(null != CHAR_PROF) {
		relevantAttributes.addAll(extractAttributes(CHAR_PROF_CLSMAS_XML))
	}
   
	return relevantAttributes
}

def getRelevantMatlCatAttributes(context){
    def String MATL_CAT = context.getProperty("MATL_CAT");
    def String MATL_GROUP= context.getProperty("MATL_GROUP");
    def parent = null;
    def relevantMatlCatAttributes=[]
    
     // find attributes by category
	if(null != MATL_CAT && MATL_CAT.contains('1')) {
		while (null != MATL_GROUP && !MATL_GROUP.equals('')) {
			 relevantMatlCatAttributes.addAll(extractAttributes(context.getProperty(MATL_GROUP+'CLSMAS_XML')))
			 parent= findParentMatlGroup(MATL_GROUP,context)
			if(null != parent) {
				MATL_GROUP = parent
			}else {
				MATL_GROUP=null
			}
		}
	}
	return relevantMatlCatAttributes
}


def extractAttributes(String fileName) {
	def relevantAttributes = []
	if(null == fileName){
	    return relevantAttributes
	}
	def root = processXMLData(fileName)
	if(null != root && !root.text().contains('NOTFOUND') && root.IDOC.E1KLAHM.E1KSMLM.size()>0) {
		root.IDOC.E1KLAHM.E1KSMLM.each{ it->
			if(null != it.RELEV && it.RELEV.text().equals('2')) {
				relevantAttributes.add(it.ATNAM.text())
			}
		}
	}
    return relevantAttributes
}


def findParentMatlGroup(String matlGroup,context) {
	def clfmas=context.getProperty(matlGroup+'CLFMAS_XML')
	if(clfmas==null){
	    return null
	}
	def root = processXMLData(clfmas)
		if(null != root && root.CLFMAS02.IDOC.E1OCLFM.E1KSSKM.size()>0){
		return root.CLFMAS02.IDOC.E1OCLFM.E1KSSKM.CLASS.text()
	}else {
		return null
	}
}

def convertNonLocalizedNumberForVariantValueID(String number){
    return convertNonLocalizedNumber(number).replaceAll(",", "x").replaceAll("\\.", "x")
}

def convertNonLocalizedNumber(String number) {
	def maxFractionDigits = 9;
	
	java.text.NumberFormat numberFormat = NumberFormat.getInstance(java.util.Locale.ENGLISH);
	java.lang.Number parsedNumber = numberFormat.parse(number.replaceFirst("E\\+", "E"));
	java.text.DecimalFormat decimalFormat = (java.text.DecimalFormat)java.text.NumberFormat.getNumberInstance(java.util.Locale.ENGLISH)
	decimalFormat.setMaximumFractionDigits(maxFractionDigits);
	decimalFormat.setGroupingUsed(false);
	
	return decimalFormat.format(parsedNumber)
	
}


def convertNumberRangeForVariantValueID(String numberFrom, String numberTo, String dependencyCode){
		String rangeID;
        String formattedNumberFrom = convertNonLocalizedNumber(numberFrom);
		String formattedNumberTo = convertNonLocalizedNumber(numberTo);
		switch (dependencyCode)
		{
			case "1":
				rangeID = formattedNumberFrom;
				break;
			case "2":
				rangeID = ">=".concat(formattedNumberFrom.concat("<").concat(formattedNumberTo));
				break;
			case "3":
				rangeID = ">=".concat(formattedNumberFrom.concat("<=").concat(formattedNumberTo));
				break;
			case "4":
				rangeID = ">".concat(formattedNumberFrom.concat("<").concat(formattedNumberTo));
				break;
			case "5":
				rangeID = ">".concat(formattedNumberFrom.concat("<=").concat(formattedNumberTo));
				break;
			case "6":
				rangeID = "<".concat(formattedNumberFrom);
				break;
			case "7":
				rangeID = "<=".concat(formattedNumberFrom);
				break;
			case "8":
				rangeID = ">".concat(formattedNumberFrom);
				break;
			case "9":
				rangeID = ">=".concat(formattedNumberFrom);
				break;
		}

		return rangeID;
	}










 

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