{"id":36236,"date":"2016-04-18T15:00:08","date_gmt":"2016-04-18T12:00:08","guid":{"rendered":"http:\/\/examples.javacodegeeks.com\/?p=36236"},"modified":"2019-03-29T14:23:27","modified_gmt":"2019-03-29T12:23:27","slug":"groovy-script-tutorial-beginners","status":"publish","type":"post","link":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-script-tutorial-beginners\/","title":{"rendered":"Groovy Script Tutorial for Beginners"},"content":{"rendered":"<p>In this article we will see how easy it is to write scripting in <code>Groovy<\/code>, with a practical example that serves a common use case. As you would probably know, Groovy is a JVM Language which is defined to run on top of Java Virtual Machine. Having said that it borrows all Java&#8217;s capabilities alongside providing its own extra features to simplify the tasks of the developers to achieve things in a easy and efficient manner.<\/p>\n<blockquote>\n<p><b>Pre-requisite : <\/b> The readers are expected to have a good exposure on Java programming language and the basic SQL (like table creation, inserting and reading values from a table etc.,) alongside a beginner level introduction to the Groovy at least to start off with. However we will cover the required aspects of the elementary semantics of Groovy, wherever required during the flow. You can read a good set of introductory tutorials of Groovy <a href=\"https:\/\/examples.javacodegeeks.com\/category\/jvm-languages\/groovy\/\">here<\/a>.<\/p>\n<\/blockquote>\n<p>The following table shows an overview of the entire article:\n<\/p>\n<div class=\"toc\">\n<h3>Table of Contents<\/h3>\n<dl>\n<dt><a href=\"#env\">1. Environment<\/a><\/dt>\n<dt><a href=\"#basics\">2. Scripting Basics<\/a><\/dt>\n<dt><a href=\"#requirement\">3. Example &#8211; Order Processing<\/a><\/dt>\n<dt><a href=\"#approach\">4. Planning and Approach<\/a><\/dt>\n<dt><a href=\"#scripts-bus\">5. Groovy Scripts for Business Objects<\/a><\/dt>\n<dd>\n<dl>\n<dt><a href=\"#scripts-bus-1\">5.1 Order POGO<\/a><\/dt>\n<dt><a href=\"#scripts-bus-2\">5.2 First Level Unit Test<\/a><\/dt>\n<dt><a href=\"#scripts-bus-3\">5.3 Test Order &#8211; Random Entries Onetime<\/a><\/dt>\n<dt><a href=\"#scripts-bus-4\">5.4 Test Order &#8211; Random Entries at Intervals<\/a><\/dt>\n<\/dl>\n<\/dd>\n<dt><a href=\"#scripts-db\">6. Groovy Scripts for Database<\/a><\/dt>\n<dd>\n<dl>\n<dt><a href=\"#scripts-db-1\">6.1 Configuration file to hold the database properties<\/a><\/dt>\n<dt><a href=\"#scripts-db-2\">6.2 Parsing the configuration file<\/a><\/dt>\n<dt><a href=\"#scripts-db-3\">6.3 Create Table<\/a><\/dt>\n<dt><a href=\"#scripts-db-4\">6.4 Insert Rows from a Single File<\/a><\/dt>\n<dt><a href=\"#scripts-db-5\">6.5 Select Total Count<\/a><\/dt>\n<dt><a href=\"#scripts-db-6\">6.6 Select All Rows<\/a><\/dt>\n<dt><a href=\"#scripts-db-7\">6.7 Insert Rows from the matching files at interval<\/a><\/dt>\n<dt><a href=\"#scripts-db-8\">6.8 Truncate Table<\/a><\/dt>\n<dt><a href=\"#scripts-db-9\">6.9 Drop Table<\/a><\/dt>\n<\/dl>\n<\/dd>\n<dt><a href=\"#conclusion\">7. Conclusion<\/a><\/dt>\n<dt><a href=\"#ref\">8. References<\/a><\/dt>\n<dt><a href=\"#download\">9. Download the Source Code<\/a><\/dt>\n<\/dl>\n<\/div>\n<h2><a name=\"env\"><\/a>1. Environment<\/h2>\n<p>The examples shown below are executed in the <i>Command Prompt \/ Shell<\/i> and the <i>GroovyConsole<\/i>. But they are guaranteed to work with any of the IDEs (like <i>Eclipse, IntelliJ IDEA, Netbeans<\/i>) through the respective plugins. The examples are executed with the Groovy Version <strong>Groovy Version: 2.4.3<\/strong>.<\/p>\n<p>For our example Order Processing System, we will use <code>MySQL<\/code> open source database. We use <strong>MySQL V 5.6 for Windows<\/strong>, with <code>JDBC driver for MySQL - <strong>MySQL JDBC Connector 5.1.29<\/strong><\/code>.<\/p>\n<h2><a name=\"basics\"><\/a>2. Scripting Basics<\/h2>\n<p>Script is an executable program which is accomplished to automate the mundane tasks in a simple and easy manner that requires a minimal or no human intervention thereby resulting in time saving. However there are various scripting languges and tools with their owns pros and cons depending on the features they have to offer, the simplified syntax they have in store, the limitations they have by nature etc.,<\/p>\n<p>In general, the scripting languages have one thing in common &#8211; their simplified syntax and ease of use as that is the main attracting point to the users (or developers) who aims to get the job done quickly and efficiently.<\/p>\n<p>Groovy is a programming language which can be used as a Scripting language due to its very simplified syntax which is very easy to use. If you are an experienced Java professional for more than 5 years and have explored Groovy for sometime, you would undoubtedly agree with the above statement.<\/p>\n<h2><a name=\"requirement\"><\/a>3. Example &#8211; Order Processing<\/h2>\n<p>We will see an example of an Order Processing System where we will get the details related to an order in a flat file (a pipe separated \/ delimited) file where each line contains the information pertaining to an order. We will parse (read and process) the line entries from the file and add an Order for each line into the Database to store it permanently.<\/p>\n<p>For the sake of our example, imagine a system that dumps such a flat file in our file system at regular intervals. Our Groovy Script will continuously monitor the same directory in the file system at regular intervals for the new files. Upon finding the files, it will process them and move the files into a different directory, so as not to process them in the next iteration.<\/p>\n<p>We will be using Groovy language basics for covering this example like String Concatenation, Collections &#8211; List and Map, File Handling, SQL Handling etc., You may please check the <a href=\"#ref\">References<\/a> section at the bottom of this article to have a quick glance on each of the topics to facilitate your understanding of scripts.<\/p>\n<h2><a name=\"approach\"><\/a>4. Planning and approach<\/h2>\n<p>For our order processing script, we will do the following in order as a step by step approach.<\/p>\n<ol>\n<li><b>Business Model (Domain Object)<\/b> &#8211; We will create a Domain Object (Business Object) to carry all the information of an order as a single entity, otherwise it will be tedious and an overhead if we were to pass all the individual attributes of an order. It is a common practice to wrap all the relevant attribute into an Object of a corresponding class. In Java, it is called as POJO (Plain Old Java Object) where in Groovy it is called as POGO (Plain Old Groovy Object).<\/li>\n<li><b>Application Business Scripts<\/b> &#8211; We will write a few simple Groovy scripts for creating random Order entries and write them into a delimited file (pipe separated) in a directory so that our Database scripts will be able to parse (read and process) them for inserting them into Database.<\/li>\n<li><b>Database Scripts<\/b> &#8211; We will write a few simple Groovy Scripts to interact with the database for creating a Database Table, reading the records from the table, truncating the table (wiping off the records), dropping a table etc., with a help of a JDBC Driver (MySQL JDBC Connector).<\/li>\n<\/ol>\n<h2><a name=\"scripts-bus\"><\/a>5. Groovy Scripts for Business Objects<\/h2>\n<p>In this section, we will write a few simple Groovy Scripts pertaining to the business purpose.<\/p>\n<h3><a name=\"scripts-bus-1\"><\/a>5.1 Order POGO<\/h3>\n<p>This is a very essential script that carries the class structure for a POGO (Plain Old Groovy Object) to have the essential properties of an Order &#8211; like the Order Id, Date, Customer Name, Currency, Price, Country, Payment Mode etc.,<\/p>\n<p>We need to carry all the properties of an Order in a single entity &#8211; which is a Wrapper Object. It is also called as BO (Business Object) or a DTO (Data Transfer Object) &#8211; due to its nature of transferring the data from one layer to another within an application.<\/p>\n<p>We will need to create as many as objects based on the number of order entries. The ratio between the order entry in a flat file Vs the Order POGO instance will be <code>1:1<\/code>.<\/p>\n<p>The following Groovy scripts has different member variables for each of the Order attributes\/properties plus few methods to be used for a common usage &#8211; like <code>toString()<\/code> to print the state of an object in a meaningful manner, <code>initOrder()<\/code> &#8211; a method to initialize an object with a line of text being read from the text file etc.,<\/p>\n<p>Please remember the fact that Groovy does not really mandate the presence of a semicolon at the end of every executable statement as in Java. This is one of the many significant ease of uses of Groovy.<\/p>\n<blockquote>\n<p>All the scripts in this article will be under a package <code>com.javacodegeeks.example.groovy.scripting<\/code> which helps us to organize all the related classes and scripts in a same folder\/directory (which is called as a Package in Java&#8217;s term).<\/p>\n<\/blockquote>\n<p>We will compile this Groovy class using <code>groovyc Order.groovy<\/code> so that the compiled .class file gets generated in a folder matching with <code>com\/javacodegeeks\/example\/groovy\/scripting<\/code> in the present directory. It will be referred by other scripts to load the Order class.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>Order.groovy<\/em><\/span><\/p>\n<pre class=\"brush:java; wrap-lines:false\">\/\/ package statement should be the very first executable statement in any script\n\/\/ packaging helps us to organize the classes into a related folder\npackage com.javacodegeeks.example.groovy.scripting\n\n\/**\n  * A POGO (Plain Old Groovy Object) used as a DTO (Data Transfer Object)\n  * or a BO (Business Object) which will carry the essential particulars \n  * of an Order\n  *\/\nclass Order         \n{      \n    \/** Self explanining fields and the default values for the few *\/\n    \/\/unique value from Database to denote a particular order\n    def id = 0 \n    def customerName, country='India', price\n    def currency='INR', paymentMode='Cash'\n    def orderDate \/\/ will be the current time in DB during insert\n         \n    \/**\n     * A method to format the value with the specified pattern (format),\n     * useful in having a fixed width while displaying in Console\n     *\/\n    def String format(format, value)\n    {\n        String.format(format, value)\n    }\n\n    \/**\n     * A method to parse a line of text and initialize an Order instance\n     * with the parsed tokens\n     *\/\n    def initOrder(strAsCSV)\n    {\n        \/\/ tokenize() will split the line of text into tokens, and trimmed to \n        \/\/ remove the extra spaces if any\n        \/\/ the tokens are assigned to the variables in order - as per \n        \/\/ the declaration on the left side\n\n        def(nameParsed, countryParsed, priceParsed, currencyParsed, modeParsed) = strAsCSV.tokenize(\"|\")*.trim()    \n        \n        this.customerName=nameParsed\n        this.country=countryParsed\n        this.price=priceParsed\n        this.currency=currencyParsed\n        this.paymentMode=modeParsed\n\n        return this\n    }\n\n    \/**\n      * An overridden toString() method of this Order class to have a \n      * meaningful display wherever it is invoked (which otherwise\n      * will be a typical hashcode and the classname)\n      *\/\n    def String toString()  \n    {                 \n        \/\/preparing the output in a fixed width format via format() method defined above\n        def output = String.format(\"%-15s\", customerName) + \" | \"   + \n            String.format(\"%-10s\", country) + \" | \" + String.format(\"%-8s\", price) + \" | \" + \n            String.format(\"%-8s\", currency) + \" | \" + String.format(\"%-12s\", paymentMode) + \" | \" \n\n        \/\/ add the OrderDate in the output Data if is not null\n        if(orderDate!=null &amp;&amp; orderDate.trim().length()&gt;0)\n            output += String.format(\"%-20s\", orderDate) + \" | \"\n\n        \/\/ add the Id if it is valid (not zero - meaning it was inserted in the database)\n        if(id!=0)\n            output = String.format(\"%-5s\", id) + \" | \" + output\n\n        output\n      }          \n}\n<\/pre>\n<h3><a name=\"scripts-bus-2\"><\/a>5.2 First Level Unit Test<\/h3>\n<p>Let us just quickly test the <code>Order.groovy<\/code> to ensure that this class behaves as expected. This will be very important to complete one module perfectly so that we can be comfortable in proceeding with the rest of the scripts. This is the best and recommended practice for the correctness of the script execution.<\/p>\n<p>This script will have 3 different Order instances created and printed on the screen. The script has a self explaining comment at every other step.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>TestOrder.groovy<\/em><\/span><\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.example.groovy.scripting\n\n\/** \n *  A straight forward way to instantiate and initialize an Order instance\n *  Field name and value is separated by a colon (:) and \n *  each name value pair is separated by a commma (,)\n *\/\ndef order = new Order(customerName: 'Raghavan', country : 'India', id : '1', \n        price : '2351', currency: 'INR', paymentMode : 'Card')\nprintln order\n\n\/** \n  * Another approach to initialize the Order instance where \n  * one property or field is intialized during instantiation (invoking the constructor)\n  * and rest of the properties are initialized separately\n  *\/\ndef order2 = new Order(customerName: 'Kannan')\norder2.country='Hong Kong'\norder2.id='2'\norder2.price='1121'\norder2.currency='HKD'\nprintln order2\n\n\/**\n * Yet another way to initialize the Order instance with one complete line of formatted line\n * pipe separated values (\"|\")\n *\/\ndef lineAsCSV = \"Ganesh     | Hong Kong  | 1542.99  | HKD   | Cheque      |\" \ndef order3 = new Order().initOrder(lineAsCSV)\nprintln order3\n<\/pre>\n<p>The script produces the following output.<\/p>\n<pre class=\"brush:java\">1     | Raghavan        | India      | 2351     | INR      | Card         | \n2     | Kannan          | Hong Kong  | 1121     | HKD      | Cash         | \nGanesh          | Hong Kong  | 1542.99  | HKD      | Cheque       | \n<\/pre>\n<p>The output in each line consists of the different pieces of an Order each separated by a pipe character. The output being displayed is generated out of the <code>toString()<\/code> method of the <code>Order.groovy<\/code> class. The fields displayed are <i>Order Id (if not null), Customer Name, Country, Amount, Currency, Payment Mode<\/i><\/p>\n<p>The first two instances are having the order Id because it was given during the instantiation. However the 3rd order instance did NOT have the Order Id and hence the output is slightly different from the first 2 instances. The 3rd instance is very important because the actual lines in the flat file will resemble the same as we will not have the order Id at first. It will be created after inserting the record into database, as it should be typically an auto-generated Id.<\/p>\n<h3><a name=\"scripts-bus-3\"><\/a>5.3 Test Order &#8211; Random Entries Onetime<\/h3>\n<p>Now that we have made our Business Object &#8211; Order.groovy and we had also tested that successfully, we will proceed further with the next step. We will create some random Order instances and write them into a text file in a delimited &#8211; pipe separated format.<\/p>\n<p>This class have all few set of names, country and currencies, amounts and payment modes in separate data structures (List and Map) &#8211; using which we will pickup some values at random to constitute an Order instance. We will generate a random number to be used as an index (pointer) to the corresponding data structure.<\/p>\n<p>This script will generate a set of entries based on a max limit that is configured in the script itself &#8211; <code>noOfRecords<\/code>, which can be passed as a command line argument if needed. Otherwise this will have a default value of 5 &#8211; meaning 5 entries will be generated and stored in a text file.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>TestOrderRandomBulk.groovy<\/em><\/span><\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.example.groovy.scripting\n\n\/\/ a list of values for customer names\ndef namesList = ['Raghavan', 'Ganesh', 'Karthick', 'Sathish', 'Kanna', 'Raja', \n         'Karthiga', 'Manoj', 'Saravanan',  'Adi', 'Dharma', 'Jhanani', \n         'Ulags', 'Prashant', 'Anand']\n\n\/\/ a Map to hold a set of countries and the currency for each\ndef countryCurrencyMap = ['India':'INR', 'Australia' : 'AUD', 'Bahrain' : 'BHD', \n              'Dubai' : 'AED', 'Saudi' : 'SAR', 'Belgium' : 'EUR', \n              'Canada' : 'CAD', 'Hong Kong' : 'HKD', 'USA' : 'USD', \n              'UK' : 'GBP', 'Singapore' : 'SGD']\n\n\/\/ a list to hold random amount values\ndef amountList = ['1234.00', '1542.99', '111.2', '18920.11', '4567.00', '9877.12', \n      '2500.00', '50000.00', '6500.18', '7894.11', '1234.56', '1756.55', '8998.11']\n\n\/\/ a list to hold different payment modes\ndef paymentModeList = ['Cash', 'Card', 'Cheque']\n\nint noOfRecords = 5\n\nprintln \" \"\n\n\/\/ Take a default value of 5 for the total number of entries to be printed\n\/\/ if nothing was specified in the command prompt while invoking the script\nif(args.length&gt;0) {\n   noOfRecords = Integer.parseInt(args[0])\n} else {\n   println \"Considering the default value for total # of entries\"\n}\n\nprintln \"No of entries to be printed : \" + noOfRecords\n\ndef random = new Random()\ndef randomIntName, randomIntCountry, randomIntAmount, randomIntMode\ndef orderRandom, mapKey\n\ndef outputToWrite = \"\"\n\nfor(int i = 0; i      \n    writer.writeLine outputToWrite \n}                                                               \n              \nprintln \"\"                                                  \nprintln \"Contents are written to the file -&gt; [$fileName] in the directory [$baseDir]\" \nprintln \"\"\n\n\/\/ 'line' is an implicit variable provided by Groovy  \nnew File(baseDir, fileName).eachLine {         \n        line -&gt; println line                          \n}                                                  \n\nprintln \"----------------- \"\nprintln \" == COMPLETED ==  \"\nprintln \"----------------- \"\n<\/pre>\n<p>The script produces the following output.<div style=\"display:inline-block; margin: 15px 0;\"> <div id=\"adngin-JavaCodeGeeks_incontent_video-0\" style=\"display:inline-block;\"><\/div> <\/div><\/p>\n<pre class=\"brush:java\"> \nConsidering the default value for total # of entries\nNo of entries to be printed : 5\n\nContents are written to the file -&gt; [outputTest.txt] in the directory [outputFiles]\n\nManoj           | USA        | 9877.12  | USD      | Cheque       | \nJhanani         | Canada     | 4567.00  | CAD      | Cash         | \nKanna           | Singapore  | 9877.12  | SGD      | Card         | \nKarthiga        | Saudi      | 9877.12  | SAR      | Cash         | \nSaravanan       | Australia  | 8998.11  | AUD      | Cheque       | \n\n----------------- \n == COMPLETED ==  \n----------------- \n<\/pre>\n<p>As you see, the script produced 5 different Order Instances with random values picked up from the respective data structure and stored each Order instance as a pipe separated values. Each order instance was accumulated and all the lines were stored in a text file &#8211; <code>outputTest.txt<\/code> in the directory <code>outputFiles<\/code>.<\/p>\n<p>At the end of the script, we had read the same file <code>outputTest.text<\/code> and printed the contents of the file into screen &#8211; for our quick and easy verification.<\/p>\n<h3><a name=\"scripts-bus-4\"><\/a>5.4 Test Order &#8211; Random Entries at Intervals<\/h3>\n<p>We saw how to write a script to write a set of Order Instances into a text file. We will see how to generate a similar set of random entries at regular intervals by making the script sleep for a while in between. This is to simulate a real time environment where one system will be dumping the flat files at regular intervals in a shared location where the other system will be watching the files for processing further.<\/p>\n<p>For the sake of brevity, we will make our script execute 2 iterations where each iteration will generate 5 random Order instances and store them in a separate text file whose names will have the timestamp appended for distinguishing with each other.<\/p>\n<p>The script will generate the files in <code><strong><i><u>outputTest.txt_count_&lt;yyyyMMdd_HHmmss&gt;<\/u><\/i><\/strong><\/code> pattern. We have an utility method <code>getNow()<\/code> to give the present date and time in the prescribed format, which we will call everytime while writing to a new file. The output file will be written in the same directory, which will be processed by a next database script which, after processing will move the file into a different target directory to avoid these files being reprocessed in the subsequent iterations.<\/p>\n<p>As usual the script below has a good documentation at every step that will be self explanatory for the readers to follow along.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>TestOrderRandomInterval.groovy<\/em><\/span><\/p>\n<pre class=\"brush:java; wrap-lines:false\">package com.javacodegeeks.example.groovy.scripting\n\n\/\/ a list of values for customer names\ndef namesList = ['Raghavan', 'Ganesh', 'Karthick', 'Sathish', 'Kanna', 'Raja',\n                 'Karthiga', 'Manoj', 'Saravanan',  'Adi', 'Dharma', 'Jhanani',\n                 'Ulags', 'Prashant', 'Anand']\n\n\/\/ a Map to hold a set of countries and the currency for each\ndef countryCurrencyMap = ['India':'INR', 'Australia' : 'AUD', 'Bahrain' : 'BHD',\n                          'Dubai' : 'AED', 'Saudi' : 'SAR', 'Belgium' : 'EUR',\n                          'Canada' : 'CAD', 'Hong Kong' : 'HKD', 'USA' : 'USD',\n                          'UK' : 'GBP', 'Singapore' : 'SGD']\n\n\/\/ a list to hold random amount values\ndef amountList = ['1234.00', '1542.99', '111.2', '18920.11', '4567.00', '9877.12',\n          '2500.00', '50000.00', '6500.18', '7894.11', '1234.56', '1756.55', '8998.11']\n\n\/\/ a list to hold different payment modes\ndef paymentModeList = ['Cash', 'Card', 'Cheque']\n\ndef getNow() {\n    new Date().format(\"yyyyMMdd_HHmmss\")\n}\n\n\/\/ default value if nothing is specified during runtime at the command prompt\nint noOfRecords = 5\n\nprintln \"\"\n\n\/\/ Take a default value of 5 for the total number of entries to be printed\n\/\/ if nothing was specified in the command prompt while invoking the script\nif(args.length&gt;0) {                                                    \n   noOfRecords = Integer.parseInt(args[0])                             \n} else {                                                               \n   println \"Considering the default value for total # of entries : 10\" \n}                                                                      \n\nprintln \"Total # of records to be printed : $noOfRecords\"\n\ndef random = new Random()\ndef randomIntName, randomIntCountry, randomIntAmount, randomIntMode\ndef orderRandom, mapKey\n\n\/\/ a variable to hold the output content to be written into a file\ndef outputToWrite = \"\"\n\n\/\/no of iterations this script will execute\ndef MAX_ITERATIONS = 2; \n\n\/\/ interval to let this script sleep (1000ms=1s, here it will be for 1 min)\ndef SLEEP_INTERVAL = 1000*60*1; \n\n\/\/ Directory to which the output files to be written\ndef baseDir = \".\"\n\/\/ Prefix of the output file\ndef fileNamePrefix = 'outputTest.txt'\n\/\/ Name of the output file which will vary in the loop below\ndef fileName = fileNamePrefix\n\nprintln \" \"\nprintln \"[*] This script will write $noOfRecords records for $MAX_ITERATIONS iterations\"\nprintln \" \"\n\nfor(int iteration = 1; iteration &lt;= MAX_ITERATIONS; iteration++) \n{\n    \/* Empty the buffer to avoid the previous stuff to be appended over and over *\/\n    outputToWrite = \"\"\n\n    for(int i = 0; i      \n        writer.writeLine outputToWrite \n    }                                                               \n                                                                \n    println getNow() + \" : Contents are written to the file -&gt; [$fileName] in the directory [$baseDir]\" \n    println \"\"\n\n    \/\/ 'line' is an implicit variable provided by Groovy  \n    new File(baseDir, fileName).eachLine {         \n            line -&gt; println line                          \n    }\n\n    println getNow() + \" ...... Script will sleep for ${SLEEP_INTERVAL} milliseconds [1000ms=1s]......\"\n    println \" \"\n    sleep(SLEEP_INTERVAL)\n    println getNow() + \" .............. Script awaken ......................\"\n    println \"\"\n}\n\nprintln \" \"\nprintln \"----------------- \"\nprintln \" == COMPLETED ==  \"\nprintln \"----------------- \"\n<\/pre>\n<p>The script produces the following output.<\/p>\n<pre class=\"brush:java; wrap-lines:false\">Considering the default value for total # of entries : 5\nTotal # of records to be printed : 5\n \n[*] This script will write 5 records for 2 iterations\n \n20160415_122040 : Contents are written to the file -&gt; [outputTest.txt_1_20160415_122040] in the directory [.]\n\nKanna           | UK         | 8998.11  | GBP      | Card         | \nManoj           | Australia  | 9877.12  | AUD      | Cash         | \nPrashant        | Saudi      | 9877.12  | SAR      | Card         | \nDharma          | Australia  | 1756.55  | AUD      | Card         | \nRaja            | Belgium    | 18920.11 | EUR      | Cheque       | \n\n20160415_122040 ...... Script will sleep for 60000 milliseconds [1000ms=1s]......\n \n20160415_122140 .............. Script awaken ......................\n\n20160415_122140 : Contents are written to the file -&gt; [outputTest.txt_2_20160415_122140] in the directory [.]\n\nPrashant        | Canada     | 111.2    | CAD      | Cash         | \nDharma          | UK         | 50000.00 | GBP      | Card         | \nKanna           | Belgium    | 50000.00 | EUR      | Card         | \nSaravanan       | Hong Kong  | 9877.12  | HKD      | Cheque       | \nManoj           | Singapore  | 8998.11  | SGD      | Cash         | \n\n20160415_122140 ...... Script will sleep for 60000 milliseconds [1000ms=1s]......\n \n20160415_122240 .............. Script awaken ......................\n\n \n----------------- \n == COMPLETED ==  \n----------------- \n<\/pre>\n<p>As explained above, the script had produced two different flat (text) files with the pattern outputTest.txt_ with a sequence number along with the date and time pattern to distinguish the files from each other. We had also retrieved the file contents and displayed in the console for our quick verification.<\/p>\n<p>We will see in the next subsection how to process these order entries for storing them into the database.<\/p>\n<h2><a name=\"scripts-db\"><\/a>6. Groovy Scripts for Database<\/h2>\n<p>We have completed our scripts for producing the flat files to cater to the business needs. Now we need a place to store the data values into a permanent storage &#8211; a Database. Like how we created a main POGO <code>Order.groovy<\/code> to use it as a Business Object for our business oriented scripts, we need a database table to store the specific attributes of an Order, which were carried in an instance of Order class.<\/p>\n<p>We will see in the subsequent sub-sections how we will write the simple groovy scripts to create a database table, insert or store values into the table, retrieve the values from the table, truncate (or wipe off the entries) from the table for us to clean and start over again, drop the database etc.,<\/p>\n<blockquote>\n<p>Please ensure you have the <b>MySQL<\/b> database installed in your machine and you have the <b>MySQL JDBC Connector Jar file<\/b> before you proceed with the rest of the scripts in this section.<\/p>\n<\/blockquote>\n<p>You may read a suitable tutorial or the <a href=\"http:\/\/www.mysql.com\/\">MySQL website<\/a> for installing the database in to your machine.<\/p>\n<h3><a name=\"scripts-db-1\"><\/a>6.1 Configuration file to hold the database properties<\/h3>\n<p>A database is a different entity and it needs to be connected to before we could actually do any operation with it. After finising our operation we should close the connection as a best practice so that the database can support further clients and connections in a better manner.<\/p>\n<p>We need certain important properties about the database like the Server IP Address or hostname where the database is running, the port number to which the database service is listening for client requests, the database type &#8211; like Oracle, DB2, MySQL etc., , the actual name of the database we need to connect to, the JDBC (Java Database Connectivity) driver url using which the underlying Java based Programming Language will talk to the database.<\/p>\n<p>As we will have a few different scripts dealing with the database and each of them will need the same properties, it is better to capture them in a separate file and be it referred in all the relevant scripts whichever needs those properties. The advantage of doing this practice is if at all we need to make a change in any of the properties, we can do so in a single place rather than changing in all the files where it was referred individually.<\/p>\n<p>Before we could write the separate database related scripts, we should see the configuration file (or a properties file in Java terminology) as to how we can store the values. The below <code>db.properties<\/code> stores the properties in a <code>key,value<\/code> pair where each pair is entered in a separate line and each key value pair is stored in the format <code>key=value<\/code>, where <code>key<\/code> is the actual key we will be referring to pick up the value from the file and the <code>value<\/code> is the actual value of the property.<\/p>\n<blockquote>\n<p>The configuration file can be of any extension but it is a standard practice to have it stored in the meaningful <code>.properties<\/code> extension.<\/p>\n<\/blockquote>\n<p>The lines starting with a <code>#<\/code> will be treated as a comment and will be ignored. It is more like a <code>\/\/<\/code> in a Java like Programming language to indicate a meaningful description or a comment.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>db.properties<\/em><\/span><\/p>\n<pre class=\"brush:java; wrap-lines:false\"># Properties needed to construct a JDBC URL programmatically inside a script\ndb.type=mysql\ndb.host=localhost\ndb.port=3306\ndb.name=test\n\n# Username and password for authenticating the client everytime a database connection is obtained\ndb.user=root\ndb.pwd=root\n\n# The JDBC Driver class that needs to be loaded from the classpath (mysql-connector-x.y.z.jar)\n# which does the actual talking to the database from within the Java based Programming language\ndb.driver=com.mysql.jdbc.Driver\n\n# Database table name\ndb.tableName=GroovyScriptTest\n<\/pre>\n<h3><a name=\"scripts-db-2\"><\/a>6.2 Parsing the configuration file<\/h3>\n<p>We will write a script to parse the database configuration file so that we can read and process the values and get them stored in to respective variables of a class. This way we can use these variables from the class any number of times we need, otherwise we may need to read it from the configuration file which is typically be slow and a time consuming operation when compared to reading it from the Groovy object variable.<\/p>\n<p>The below Groovy script will read the configuration file from the file system and parse the values and store them into respective variables. To make it efficient reading, we read them through <code>static<\/code> initializer blocks which will be executed only once during the class loading time. The values read will be retained until the script completes its execution or the JVM shuts down. Just to verify the properties being read, we will print them in the console via a helper method called <code>printValues()<\/code>.<\/p>\n<p>We will compile this Groovy class using <code>groovyc DBProps.groovy<\/code> so that the compiled .class file gets generated in a folder matching with <code>com\/javacodegeeks\/example\/groovy\/scripting<\/code> in the present directory. It will be referred by other scripts to load the Order class.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>dbProperties.groovy<\/em><\/span><\/p>\n<pre class=\"brush:java; wrap-lines:false\">package com.javacodegeeks.example.groovy.scripting\n\nclass DBProps\n{\n    \/\/ meaningful class level variables for each of the db properties\n    static String dbType, dbHost, dbPort, dbName, dbUser, dbPwd, dbUrl, dbDriver, dbTblName\n    \n    \/\/ class level varaibles for the properties file \n    static String baseDir=\".\", propsFileName = 'db.properties'\n    \n    \/\/ class level variables to hold the properties loaded\n    static def props = new Properties(), config\n\n    \/\/static initializer block (gets invoked when the class is loaded and only once)\n    static\n    {\n        \/\/ Groovy's simple way to load a configuration file from a directory and\n        \/\/ create a Properties (java.util.Properties) instance out of it    \n        new File(baseDir, propsFileName).withInputStream {\n          stream -&gt; props.load(stream)\n        }\n\n        \/\/ ConfigSlurper supports accessing properties using GPath expressions (dot notation)\n        config = new ConfigSlurper().parse(props)\n        \n        \/\/ Assign the value of each property through ConfigSlurper instance\n        dbType    = config.db.type\n        dbName    = config.db.name\n        dbHost    = config.db.host\n        dbPort    = config.db.port\n        dbUser    = config.db.user\n        dbPwd     = config.db.pwd\n        dbDriver  = config.db.driver\n        dbTblName = config.db.tableName\n\n        dbUrl = 'jdbc:' + dbType + ':\/\/' + dbHost + ':' + dbPort + '\/' + dbName\n        \/\/assert dbUrl=='jdbc:mysql:\/\/localhost:3306\/test'\n    }\n\n    static printValues()\n    {\n        println \"Db Type     : \" + DBProps.dbType\n        println \"Db Name     : \" + DBProps.dbName        \n        println \"Db Host     : \" + DBProps.dbHost\n        println \"Db Port     : \" + DBProps.dbPort        \n        println \"Db User     : \" + DBProps.dbUser\n        println \"Db Pwd      : \" + DBProps.dbPwd\n        println \"Db URL      : \" + DBProps.dbUrl\n        println \"JDBC Driver : \" + DBProps.dbDriver\n        println \"Table Name  : \" + DBProps.dbTblName       \n    }\n}\n\n\/\/ To test the values through the same script\nDBProps.printValues()\n<\/pre>\n<p>The script produces the following output.<\/p>\n<pre class=\"brush:java\">Db Type     : mysql\nDb Name     : test\nDb Host     : localhost\nDb Port     : 3306\nDb User     : root\nDb Pwd      : root\nDb URL      : jdbc:mysql:\/\/localhost:3306\/test\nJDBC Driver : com.mysql.jdbc.Driver\nTable Name  : GroovyScriptTest\n<\/pre>\n<p>As you see, the values read from the configuration \/ properties file were stored into a respective variables of a class, which will be referred in different other scripts for the efficient and ease of use.<\/p>\n<h3><a name=\"scripts-db-3\"><\/a>6.3 Create Table<\/h3>\n<p>We will now write a Groovy script to create a database table <code>GroovyScriptTest<\/code> to capture the Order related information for our example. This table will have a placeholder to store every bit of information about our Order &#8211; as we discussed in Business Object in the <code>Order.groovy<\/code>. However the data types and declaration in the database may be little different from the Programming language(s).<\/p>\n<blockquote>\n<p>For executing the database scripts, you should specify the directory where the MySQL JDBC Jar file is present, as a classpath option while invoking the groovy script. For example, to invoke the below script the command should be <code>groovy -classpath C:\\commonj2eelibs\\mysql-connector-java-5.1.29-bin.jar dbCreateTable.groovy<\/code>, where the mysql jar file <code>mysql-connector-java-5.1.29-bin.jar<\/code> is present in the directory <code>C:\\commonj2eelibs\\<\/code>[ulp id=&#8217;kHqyxwGNoyzYAfPN&#8217;]<\/p>\n<\/blockquote>\n<p><span style=\"text-decoration: underline;\"><em>dbCreateTable.groovy<\/em><\/span><\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.example.groovy.scripting\n\n\/\/ Database related methods are present in Sql class\n\/\/ we need to import the Sql class from groovy.sql package\nimport groovy.sql.Sql\n\n\/\/ we read the database properties from DBProps class \n\/\/ which had already read those values from the configuration file\ndef url = DBProps.dbUrl\ndef user = DBProps.dbUser\ndef password = DBProps.dbPwd\ndef driver = DBProps.dbDriver\ndef tableName = DBProps.dbTblName\n \n\/\/ Groovy's way of executing SQL statement after obtaining a connection\n\/\/ from database. 'withInstance' is a special construct that helps the\n\/\/ connection closed automatically even in case of any errors\nSql.withInstance(url, user, password, driver) { sql -&gt;\n \n  sql.execute '''\n    CREATE TABLE ''' + tableName + '''\n    (\n        Id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,\n        NAME VARCHAR(30),\n        COUNTRY VARCHAR(20),\n        PRICE FLOAT(8,2),\n        CURRENCY VARCHAR(3),\n        PAYMENT_MODE VARCHAR(10),\n        ORDER_DATE DATETIME DEFAULT CURRENT_TIMESTAMP\n    );\n  '''\n\n  println \"Table [${tableName}] created successfully\"\n}\n<\/pre>\n<p>The script produces the following output.<\/p>\n<pre class=\"brush:java\">Table [GroovyScriptTest] created successfully\n\n<\/pre>\n<p>The above script created a table named <code>GroovyScriptTest<\/code> in the MySQL database named &#8216;test&#8217; with the columns <i>Id<\/i> being auto-generated primary key (unique value per row), <i>Name<\/i> of String datatype with maximum 30 characters limit, <i>country<\/i> of String datatype of maximum 20 characters limit, <i>price<\/i> of floating data type of 8 digits with 2 digits for precision, <i>currency<\/i> as a String datatype of 30 characters limit, <i>Payment_Mode<\/i> of String datatype of 10 characters limit and <i>Order_date<\/i> of datetime datatype with the default value of the current date and time in the System, if not specified.<\/p>\n<h3><a name=\"scripts-db-4\"><\/a>6.4 Insert Rows from a Single File<\/h3>\n<p>Now that we had created a table in the MySQL database, let us write\/ insert some data into the table from a flat file. We had already executed a script <code>TestOrderRandomBulk.groovy<\/code> where it had produced a flat file <code>outputTest.txt<\/code> in the directory <code>outputFiles<\/code>. The below script <code>dbInsertValueSingleFile.groovyy<\/code> will read the same flat file and insert into the <code>GroovyScriptTest<\/code> table.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>dbInsertValueSingleFile.groovy<\/em><\/span><\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.example.groovy.scripting\n\nimport groovy.sql.Sql\n\n\/\/ Properties of DBProps class parsed out of the configuration file\ndef url = DBProps.dbUrl\ndef user = DBProps.dbUser\ndef password = DBProps.dbPwd\ndef driver = DBProps.dbDriver\ndef tableName = DBProps.dbTblName\n\ndef baseDir=\".\/outputFiles\"\ndef fileName = 'outputTest.txt'\n\n\/\/ a list to hold the list of valid (non-empty) lines in the flat file\ndef list = new File(baseDir, fileName).readLines()*.trim()\n\ndef orderList = []\n\nlist.each { it -&gt;\n       \/\/ Consider ONLY the non-empty lines in the flat file\n       if(it.trim().length() &gt; 0)\n          orderList.add(new Order().initOrder(it))\n}\n\nSql.withInstance(url, user, password, driver) { sql -&gt;\n  \/\/process each line which is an Order Instance\n  orderList.each { it -&gt; \n      sql.execute \"\"\"\n          INSERT INTO ${Sql.expand(tableName)}\n            (NAME, COUNTRY, PRICE, CURRENCY, PAYMENT_MODE)\n            VALUES\n            (\n                ${it.customerName}, ${it.country},\n                ${it.price}, ${it.currency}, ${it.paymentMode}\n            );\n      \"\"\"\n  }\n\n  println \"Total Rows Inserted to db : \" + orderList.size()\n}\n\n\nprintln \" \"\nprintln \"----------------- \"\nprintln \" == COMPLETED ==  \"\nprintln \"----------------- \"\n<\/pre>\n<p>The script produces the following output.<\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.example.groovy.scripting\n\n<\/pre>\n<p>The script produces the following output.<\/p>\n<pre class=\"brush:java\">Total Rows Inserted to db : 5\n \n----------------- \n == COMPLETED ==  \n----------------- \n<\/pre>\n<p>The above script successfully read the flat file and inserted each line as a separate Order entry in the database table. The output confirmed that there were 5 Order instances successfully inserted.<\/p>\n<p>Let us verify the values inserted in the database table with another script as discussed in the next subsection.<\/p>\n<h3><a name=\"scripts-db-5\"><\/a>6.5 Select Total Count<\/h3>\n<p>Let us write a simple Groovy script to get the total number of rows present in the database table.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>dbSelectTotal.groovy<\/em><\/span><\/p>\n<pre class=\"brush:java; wrap-lines:false\">package com.javacodegeeks.example.groovy.scripting\n\nimport groovy.sql.Sql\n\ndef url = DBProps.dbUrl\ndef user = DBProps.dbUser\ndef password = DBProps.dbPwd\ndef driver = DBProps.dbDriver\ndef tableName = DBProps.dbTblName\n\n\/\/ We will have a explicit handle on sql instance through newInstance() method\n\/\/ which will require us to manually close the sql instance after the work is done\ndef sql = Sql.newInstance(url, user, password, driver)\n                                                      \nquery=\"\"\"Select COUNT(*) as TotalRows from \"\"\" + tableName\n                                                                                               \ndef totatlRows                                                         \n                                                                                               \nsql.query(query) { resultSet -&gt;                                                                \n    while(resultSet.next()) {            \n        totalRows = resultSet.getString(1)                                    \n        println \"Total Rows in the table [${tableName}] : ${totalRows}\"                 \n    }                                                                                          \n}                                                                                              \n\n\/\/ Sql.withInstance() automatically closes, else we need to manually close the sql connection)\nsql.close()                                                                                    \n<\/pre>\n<p>The script produces the following output.<\/p>\n<pre class=\"brush:java; wrap-lines:false\">Total Rows in the table [GroovyScriptTest] :: 5 \n\n<\/pre>\n<h3><a name=\"scripts-db-6\"><\/a>6.6 Select All Rows<\/h3>\n<p>Let us write yet another Groovy script to retrieve all the rows available in the <code>GroovyScriptTest<\/code> database table.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>dbSelectRows.groovy<\/em><\/span><\/p>\n<pre class=\"brush:java; wrap-lines:false\">package com.javacodegeeks.example.groovy.scripting\n                                                                                                               \nimport groovy.sql.Sql\n\ndef url = DBProps.dbUrl\ndef user = DBProps.dbUser\ndef password = DBProps.dbPwd\ndef driver = DBProps.dbDriver\ndef tableName = DBProps.dbTblName\n\ndef sql = Sql.newInstance(url, user, password, driver)\n                                                      \ndef query= '''select count(*) as total_rows from ''' +  tableName\n                                                                             \ndef totalRows                                                         \n                                                                                               \nsql.query(query) { resultSet -&gt;                                                                \n    while(resultSet.next()) {   \n        totalRows = resultSet.getString(1) \n        println \"Total Rows in the table [${tableName}] : ${totalRows}\"\n    }                                                                                          \n}                                                                                              \n                                                                                               \ndef fieldsList = \"Id, Name, Country, Price, Currency, Payment_Mode, Order_Date\"\n\nquery='''                                                                                    \n    Select\n       Id, Name, Country, Price, Currency, Payment_Mode, Order_Date\n    from                                                                                       \n        ''' + tableName                       \n\n\/\/ declare the individual variables to hold the respective values from database\ndef id, name, country, orderNo, price, currency, mode, orderDate\n\n\/\/ a list to hold a set of Order Instances\ndef orderList = []\n\n\/\/ a variable to hold an Order Instance prepared out of the values extracted from database\ndef order\n\nsql.query(query) { rs -&gt;\n    while(rs.next()) \n    {\n        \/\/ extract each field from the resultset(rs) and \n        \/\/ store them in separate variables\n        id = rs.getString(1)\n        name = rs.getString(2)\n        country = rs.getString(3)\n        price = rs.getString(4)\n        currency = rs.getString(5)\n        mode = rs.getString(6)\n        orderDate = rs.getString(7)\n    \n        \/\/ create an Order Instance from the values extracted\n        order = new Order('id' : id, 'customerName': name, 'country': country, 'price': price, \n                    'currency' : currency, 'paymentMode' : mode, 'orderDate' : orderDate)\n    \n        \/\/ add the order instances into a collection (List)\n        orderList.add(order)\n    }\n}\n\n\/\/ Prepare the column headers with a fixed width for each\ndef fieldListDisplay = String.format(\"%-5s\", \"Id\") + \" | \" + \n         String.format(\"%-15s\", \"Customer Name\") + \" | \"  + \n         String.format(\"%-10s\", \"Country\") + \" | \" + \n         String.format(\"%-8s\", \"Price\") + \" | \" + \n         String.format(\"%-8s\", \"Currency\") + \" | \" + \n         String.format(\"%-12s\", \"Payment Mode\") + \" | \" + \n         String.format(\"%-21s\", \"Order Date\") + \" | \"\n\n\/\/ an utility method to display a dash (\"-\") for a visual aid\n\/\/ to keep the data aligned during the display in the console\ndef printDashes(limit) {                                                  \n    for(int i = 0 ; i 0)                                                    \n{\n    \/\/print the Headers\n    println \"\"\n    def dashWidth = 102\n    printDashes(dashWidth)\n    println fieldListDisplay\n    printDashes(dashWidth)\n\n    \/\/ Print each of the order instances\n    \/\/ Here the toString() method will be invoked on the Order instance\n    orderList.each { it -&gt;\n         println it\n    }\n\n    \/\/ To print a line with dashes to indicate the end of the display\n    printDashes(dashWidth)\n }\n\n\/\/ Dont' forget to close the database connection\nsql.close()\n<\/pre>\n<p>The script produces the following output.<\/p>\n<pre class=\"brush:java; wrap-lines:false\">Total Rows in the table [GroovyScriptTest] :: 5\n\n------------------------------------------------------------------------------------------------------\nId    | Customer Name   | Country    | Price    | Currency | Payment Mode | Order Date            | \n------------------------------------------------------------------------------------------------------\n1     | Manoj           | USA        | 9877.12  | USD      | Cheque       | 2016-04-15 16:53:14.0 | \n2     | Jhanani         | Canada     | 4567.00  | CAD      | Cash         | 2016-04-15 16:53:14.0 | \n3     | Kanna           | Singapore  | 9877.12  | SGD      | Card         | 2016-04-15 16:53:14.0 | \n4     | Karthiga        | Saudi      | 9877.12  | SAR      | Cash         | 2016-04-15 16:53:14.0 | \n5     | Saravanan       | Australia  | 8998.11  | AUD      | Cheque       | 2016-04-15 16:53:14.0 | \n------------------------------------------------------------------------------------------------------\n<\/pre>\n<p>As you see, the above script extracted all the 5 rows from the database table and created a separate Order Instance using the values, in an iteration. All those Order instances were printed with the help of toString() method that helps us to get the values of an Order Instance with a fixed width &#8211; to have a better visual aid while displaying. The values are displayed with the headers to make it meaningful to indicate which value belongs to which column.<\/p>\n<blockquote>\n<p>Please observe the values for <b>Id<\/b> column where it is in sequence starting from 1 to 5. It was because we declared the syntax for the column while creating the database table as an <i>auto generated, identity<\/i> column.<\/p>\n<\/blockquote>\n<h3><a name=\"scripts-db-7\"><\/a>6.7 Insert Rows from the matching files at interval<\/h3>\n<p>Now we had successfully inserted the records from a single flat file and also verified the total record count plus extracted all the rows available in a table. We will enhance the script further to make it process the files in iteration at regular intervals while letting the script sleep for a while. The duration for sleeping, number of iterations are configured in the script.<\/p>\n<p><b>Note: <\/b> This script will look for the files with the matching pattern <code><strong><i><u>outputTest.txt_count_&lt;yyyyMMdd_HHmmss&gt;<\/u><\/i><\/strong><\/code> which were generated out of the script <code>TestOrderRandomInterval.groovy<\/code><\/p>\n<blockquote>\n<p>For the brevity, the script will process two iterations and will exit. However, to make it execute indefinitely, you can make the while loop as follows.<\/p>\n<pre class=\"brush:bash\">     while(true) { \n        ... \n     }\n    \n<\/pre>\n<\/blockquote>\n<p><span style=\"text-decoration: underline;\"><em>dbInsertValueInterval.groovy<\/em><\/span><\/p>\n<pre class=\"brush:java; wrap-lines:false\">package com.javacodegeeks.example.groovy.scripting\n\nimport groovy.sql.Sql\nimport groovy.io.FileType\n\ndef url = DBProps.dbUrl\ndef user = DBProps.dbUser\ndef password = DBProps.dbPwd\ndef driver = DBProps.dbDriver\ndef tableName = DBProps.dbTblName\n\ndef baseDir = \".\"\ndef targetDir=\".\/outputFiles\"\ndef fileNamePattern = 'outputTest.txt_'\n\ndef dir = new File(baseDir)\ndef list, fileName, fileNameMatches\ndef orderlist = []\n\/\/ interval to let the script sleep (1000ms = 1s, here it indicates 1 minute)\ndef SLEEP_INTERVAL = 1000*60*1\ndef MAX_ITERATIONS = 2, i = 1\n\n\/\/ an utility method to print the current date and time in a specified format\ndef getNow()\n{\n    new Date().format(\"yyyyMMdd_HHmmss\")\n}\n\nprintln \" \"\nprintln \"Script will try ${MAX_ITERATIONS} times for the matching input files while sleeping for ${SLEEP_INTERVAL\/60000} minutes\"\n\nwhile(i++ \n       \n       fileName = file.name\n       fileNameMatches = false\n       \n       if(fileName.startsWith(fileNamePattern)) \n       {\n           println \"Processing the file -&gt; $fileName\"\n           fileNameMatches = true\n       }\n    \n       if(fileNameMatches)\n       {\n            \/\/ store all the lines from a file into a List, after trimming the spaces on each line\n            list = new File(baseDir, fileName).readLines()*.trim()\n            orderList = []\n        \n            \/\/ Process only the valid (non-empty) lines and prepare an Order instance\n            \/\/ by calling the initOrder() method by passing the pipe delimited line of text\n            list.each { it -&gt;\n                if(it.trim().length()&gt;0)\n                  orderList.add(new Order().initOrder(it))\n            }    \n    \n            Sql.withInstance(url, user, password, driver) { sql -&gt;\n              orderList.each { it -&gt; \n                  sql.execute \"\"\"\n                      INSERT INTO ${Sql.expand(tableName)}\n                    (NAME, COUNTRY, PRICE, CURRENCY, PAYMENT_MODE)\n                    VALUES\n                    (\n                        ${it.customerName}, ${it.country},\n                        ${it.price}, ${it.currency}, ${it.paymentMode}\n                    );\n                  \"\"\"\n              }\n            \n              println \"Total Rows Inserted to db : \" + orderList.size()\n            }\n        \n            \/\/ Move the processed file into a different directory\n            \/\/ so that the same file will NOT be processed during next run\n            \"mv ${fileName} ${targetDir}\".execute()\n            println \"File ${fileName} moved to dir [${targetDir}] successfully.\"\n           }\n        }\n    \n    println \"\"\n    println getNow() + \" ... script will sleep for ${SLEEP_INTERVAL} milliseconds...\"\n    println \"\"\n    sleep(SLEEP_INTERVAL)\n    println getNow() + \" ......... script awaken ........ \"\n    println \"\"\n}\n\nprintln \" \"\nprintln \"----------------- \"\nprintln \" == COMPLETED ==  \"\nprintln \"----------------- \"\n<\/pre>\n<p>The script produces the following output.<\/p>\n<pre class=\"brush:java; wrap-lines:false\">Script will try 2 times for the matching input files while sleeping for 1 minutes\n\n-------------------------------------------------------------------------------------------------\n20160415_172226 =========== SCANNING for files matching with outputTest.txt_ =================== \n-------------------------------------------------------------------------------------------------\n \nProcessing the file -&gt; outputTest.txt_1_20160415_122040\nTotal Rows Inserted to db : 5\nFile outputTest.txt_1_20160415_122040 moved to dir [.\/outputFiles] successfully.\nProcessing the file -&gt; outputTest.txt_2_20160415_122140\nTotal Rows Inserted to db : 5\nFile outputTest.txt_2_20160415_122140 moved to dir [.\/outputFiles] successfully.\n\n20160415_172227 ... script will sleep for 60000 milliseconds...\n\n20160415_172327 ......... script awaken ........ \n\n \n-------------------------------------------------------------------------------------------------\n20160415_172327 =========== SCANNING for files matching with outputTest.txt_ =================== \n-------------------------------------------------------------------------------------------------\n \n\n20160415_172427 ... script will sleep for 60000 milliseconds...\n\n20160415_172427 ......... script awaken ........ \n \n----------------- \n == COMPLETED ==  \n----------------- \n<\/pre>\n<p>You can verify the total values inserted by executing the <code>dbSelectRows.groovy<\/code> where it will display all the rows in the table with a fixed width column for each of the values as we saw in <i>section 6.6.<\/i><\/p>\n<h3><a name=\"scripts-db-8\"><\/a>6.8 Truncate Table<\/h3>\n<p>We will also see a Groovy Script to truncate the database table. Truncating helps to retain the table structure but wipe off (delete) all the rows in the table. It will be helpful whenever you want to start the operations afresh from the beginning.<\/p>\n<blockquote>\n<p>Once the table is truncated successfully, you can insert the values again, for which the auto-generated Id value will start from 1.<\/p>\n<\/blockquote>\n<p><span style=\"text-decoration: underline;\"><em>dbTruncateTable.groovy<\/em><\/span><\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.example.groovy.scripting\n\nimport groovy.sql.Sql\n\ndef url = DBProps.dbUrl\ndef user = DBProps.dbUser\ndef password = DBProps.dbPwd\ndef driver = DBProps.dbDriver\ndef tableName = DBProps.dbTblName\n\nSql.withInstance(url, user, password, driver) { sql -&gt;\n  sql.execute \"\"\"TRUNCATE TABLE \"\"\" + tableName\n\n  println \"Table [${tableName}] truncated successfully\"\n}\n\n<\/pre>\n<p>The script produces the following output.<\/p>\n<pre class=\"brush:java\">Table [GroovyScriptTest] truncated successfully\n<\/pre>\n<h3><a name=\"scripts-db-9\"><\/a>6.9 Drop Table<\/h3>\n<p>At times we need to drop the table to start everything afresh. Let us write a simple Groovy script for dropping the table from the database.<\/p>\n<blockquote>\n<p>Once the table is dropped successfully, you need to recreate the table by executing the script <code>dbCreateTable.groovy<\/code> before you can insert the values.<\/p>\n<\/blockquote>\n<p><span style=\"text-decoration: underline;\"><em>dbDropTable.groovy<\/em><\/span><\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.example.groovy.scripting                                                           \n\nimport groovy.sql.Sql\n\ndef url = DBProps.dbUrl\ndef user = DBProps.dbUser\ndef password = DBProps.dbPwd\ndef driver = DBProps.dbDriver\ndef tableName = DBProps.dbTblName\n\nSql.withInstance(url, user, password, driver) { sql -&gt;\n  sql.execute '''DROP TABLE ''' + tableName\n\n  println \"Table [${tableName}] dropped successfully\"\n}\n<\/pre>\n<p>The script produces the following output.<\/p>\n<pre class=\"brush:java\">Table [GroovyScriptTest] dropped successfully\n<\/pre>\n<h2><a name=\"conclusion\"><\/a>7. Conclusion<\/h2>\n<p>Hope you had enjoyed this article &#8211; Groovy Script Tutorial for Beginners. In this article we have seen how to write simple Groovy scripts to create a Business Object, generate random Order entries, write them into a text file, read the flat file and parse the order entries, read a property\/configuration file for the database related values, create a database table, store values into a table, read the values from the table, truncate and drop the table.<\/p>\n<p>Though the article aimed at a practical scenario, there may be few different conditions and best practices for a requirement if any different you have at hand. In such case, you are required to go through the documentation of the respective language constructs for a better scripting.<\/p>\n<h2><a name=\"ref\"><\/a>8. References<\/h2>\n<p>You may please refer the following URLs for further reading.<\/p>\n<ol>\n<li><a href=\"http:\/\/groovy-lang.org\/single-page-documentation.html\">Groovy Official Documentation<\/a><\/li>\n<li><a href=\"http:\/\/www.mysql.com\/downloads\/\">MySQL Downloads<\/a><\/li>\n<li><a href=\"https:\/\/dev.mysql.com\/downloads\/connector\/j\/5.0.html\">MySQL JDBC Connector Jar Download<\/a><\/li>\n<li><a href=\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-string-example\/\">Groovy String Example Java Code Geeks Example<\/a><\/li>\n<li><a href=\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-array-example\/\">Groovy Array Example Java Code Geeks Example<\/a><\/li>\n<li><a href=\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-closure-example-2\/\">Groovy Closures Example Java Code Geeks Example<\/a><\/li>\n<li><a href=\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-list-example\/\">Groovy List Example from Java Code Geeks Example<\/a><\/li>\n<li><a href=\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-map-example\/\">Groovy Map Example from Java Code Geeks Example<\/a><\/li>\n<li><a href=\"http:\/\/docs.groovy-lang.org\/latest\/html\/documentation\/#_working_with_io\">Groovy Working with IO<\/a><\/li>\n<li><a href=\"http:\/\/docs.groovy-lang.org\/latest\/html\/documentation\/#_interacting_with_a_sql_database\">Groovy Database Interaction<\/a><\/li>\n<\/ol>\n<h2><a name=\"download\"><\/a>9. Download the Source Code<\/h2>\n<p>This is an example of how to write scripting in Groovy, tested with the Command Prompt \/ Shell and Groovy Console against Groovy Version 2.4.3.<\/p>\n<div class=\"download\"><strong>Download<\/strong><br \/>\nYou can download the full source code of this example here: <strong><a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/04\/groovyScriptTutorial.zip\">Groovy Scripting Tutorial<\/a><\/strong>. Please read the <b>ReadMe.txt<\/b> file for how to execute the scripts.<\/div>\n","protected":false},"excerpt":{"rendered":"<p>In this article we will see how easy it is to write scripting in Groovy, with a practical example that serves a common use case. As you would probably know, Groovy is a JVM Language which is defined to run on top of Java Virtual Machine. Having said that it borrows all Java&#8217;s capabilities alongside &hellip;<\/p>\n","protected":false},"author":87,"featured_media":24987,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1216],"tags":[1450],"class_list":["post-36236","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-groovy","tag-scripting"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Groovy Script Tutorial for Beginners - Java Code Geeks<\/title>\n<meta name=\"description\" content=\"In this article we will see how easy it is to write scripting in Groovy, with a practical example that serves a common use case. As you would probably\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-script-tutorial-beginners\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Groovy Script Tutorial for Beginners - Java Code Geeks\" \/>\n<meta property=\"og:description\" content=\"In this article we will see how easy it is to write scripting in Groovy, with a practical example that serves a common use case. As you would probably\" \/>\n<meta property=\"og:url\" content=\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-script-tutorial-beginners\/\" \/>\n<meta property=\"og:site_name\" content=\"Examples Java Code Geeks\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/javacodegeeks\" \/>\n<meta property=\"article:published_time\" content=\"2016-04-18T12:00:08+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2019-03-29T12:23:27+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/07\/groovy-logo.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"150\" \/>\n\t<meta property=\"og:image:height\" content=\"150\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Raghavan Muthu\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/itsraghz\" \/>\n<meta name=\"twitter:site\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Raghavan Muthu\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"34 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-script-tutorial-beginners\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-script-tutorial-beginners\/\"},\"author\":{\"name\":\"Raghavan Muthu\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/aa8716fe8bdb3e382d5bdf9b9e960315\"},\"headline\":\"Groovy Script Tutorial for Beginners\",\"datePublished\":\"2016-04-18T12:00:08+00:00\",\"dateModified\":\"2019-03-29T12:23:27+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-script-tutorial-beginners\/\"},\"wordCount\":3779,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-script-tutorial-beginners\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/07\/groovy-logo.jpg\",\"keywords\":[\"scripting\"],\"articleSection\":[\"Groovy\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-script-tutorial-beginners\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-script-tutorial-beginners\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-script-tutorial-beginners\/\",\"name\":\"Groovy Script Tutorial for Beginners - Java Code Geeks\",\"isPartOf\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-script-tutorial-beginners\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-script-tutorial-beginners\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/07\/groovy-logo.jpg\",\"datePublished\":\"2016-04-18T12:00:08+00:00\",\"dateModified\":\"2019-03-29T12:23:27+00:00\",\"description\":\"In this article we will see how easy it is to write scripting in Groovy, with a practical example that serves a common use case. As you would probably\",\"breadcrumb\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-script-tutorial-beginners\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-script-tutorial-beginners\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-script-tutorial-beginners\/#primaryimage\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/07\/groovy-logo.jpg\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/07\/groovy-logo.jpg\",\"width\":150,\"height\":150},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-script-tutorial-beginners\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/examples.javacodegeeks.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"JVM Languages\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/jvm-languages\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Groovy\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/jvm-languages\/groovy\/\"},{\"@type\":\"ListItem\",\"position\":4,\"name\":\"Groovy Script Tutorial for Beginners\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#website\",\"url\":\"https:\/\/examples.javacodegeeks.com\/\",\"name\":\"Java Code Geeks\",\"description\":\"Java Examples and Code Snippets\",\"publisher\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\"},\"alternateName\":\"JCG\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/examples.javacodegeeks.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\",\"name\":\"Exelixis Media P.C.\",\"url\":\"https:\/\/examples.javacodegeeks.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"width\":864,\"height\":246,\"caption\":\"Exelixis Media P.C.\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/javacodegeeks\",\"https:\/\/x.com\/javacodegeeks\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/aa8716fe8bdb3e382d5bdf9b9e960315\",\"name\":\"Raghavan Muthu\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/01\/Raghavan-Muthu-96x96.jpg\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/01\/Raghavan-Muthu-96x96.jpg\",\"caption\":\"Raghavan Muthu\"},\"description\":\"Raghavan alias Saravanan Muthu is a seasoned IT professional having more than 2 decades of experience on Java SE\/EE based Application Architecture, Design, Development, Management and Administration for Banking, Insurance, Telecom, HealthCare and Automobile Industries, having a very good hands on experience on Multi-threaded, batch processing applications and Relational Databases. He is currently working as a Director of Engineering for one of the Product based companies in India that delivers the product on Health Care and Insurance Domain. He holds a Post Graduation (Master of Science), and a PG Degree on Big Data Engineering from Birla Institute of Technology and Science (BITS), Pilani, India. He is a Founder, Chief Executive Volunteer and a Web Master of a non-profit charity organization named SHaDE (http:\/\/shade.org.in).\",\"sameAs\":[\"https:\/\/www.raghsonline.com\/\",\"https:\/\/x.com\/https:\/\/twitter.com\/itsraghz\"],\"url\":\"https:\/\/examples.javacodegeeks.com\/author\/raghavan-muthu\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Groovy Script Tutorial for Beginners - Java Code Geeks","description":"In this article we will see how easy it is to write scripting in Groovy, with a practical example that serves a common use case. As you would probably","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-script-tutorial-beginners\/","og_locale":"en_US","og_type":"article","og_title":"Groovy Script Tutorial for Beginners - Java Code Geeks","og_description":"In this article we will see how easy it is to write scripting in Groovy, with a practical example that serves a common use case. As you would probably","og_url":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-script-tutorial-beginners\/","og_site_name":"Examples Java Code Geeks","article_publisher":"https:\/\/www.facebook.com\/javacodegeeks","article_published_time":"2016-04-18T12:00:08+00:00","article_modified_time":"2019-03-29T12:23:27+00:00","og_image":[{"width":150,"height":150,"url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/07\/groovy-logo.jpg","type":"image\/jpeg"}],"author":"Raghavan Muthu","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/itsraghz","twitter_site":"@javacodegeeks","twitter_misc":{"Written by":"Raghavan Muthu","Est. reading time":"34 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-script-tutorial-beginners\/#article","isPartOf":{"@id":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-script-tutorial-beginners\/"},"author":{"name":"Raghavan Muthu","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/aa8716fe8bdb3e382d5bdf9b9e960315"},"headline":"Groovy Script Tutorial for Beginners","datePublished":"2016-04-18T12:00:08+00:00","dateModified":"2019-03-29T12:23:27+00:00","mainEntityOfPage":{"@id":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-script-tutorial-beginners\/"},"wordCount":3779,"commentCount":0,"publisher":{"@id":"https:\/\/examples.javacodegeeks.com\/#organization"},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-script-tutorial-beginners\/#primaryimage"},"thumbnailUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/07\/groovy-logo.jpg","keywords":["scripting"],"articleSection":["Groovy"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-script-tutorial-beginners\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-script-tutorial-beginners\/","url":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-script-tutorial-beginners\/","name":"Groovy Script Tutorial for Beginners - Java Code Geeks","isPartOf":{"@id":"https:\/\/examples.javacodegeeks.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-script-tutorial-beginners\/#primaryimage"},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-script-tutorial-beginners\/#primaryimage"},"thumbnailUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/07\/groovy-logo.jpg","datePublished":"2016-04-18T12:00:08+00:00","dateModified":"2019-03-29T12:23:27+00:00","description":"In this article we will see how easy it is to write scripting in Groovy, with a practical example that serves a common use case. As you would probably","breadcrumb":{"@id":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-script-tutorial-beginners\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-script-tutorial-beginners\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-script-tutorial-beginners\/#primaryimage","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/07\/groovy-logo.jpg","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/07\/groovy-logo.jpg","width":150,"height":150},{"@type":"BreadcrumbList","@id":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-script-tutorial-beginners\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/examples.javacodegeeks.com\/"},{"@type":"ListItem","position":2,"name":"JVM Languages","item":"https:\/\/examples.javacodegeeks.com\/category\/jvm-languages\/"},{"@type":"ListItem","position":3,"name":"Groovy","item":"https:\/\/examples.javacodegeeks.com\/category\/jvm-languages\/groovy\/"},{"@type":"ListItem","position":4,"name":"Groovy Script Tutorial for Beginners"}]},{"@type":"WebSite","@id":"https:\/\/examples.javacodegeeks.com\/#website","url":"https:\/\/examples.javacodegeeks.com\/","name":"Java Code Geeks","description":"Java Examples and Code Snippets","publisher":{"@id":"https:\/\/examples.javacodegeeks.com\/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/examples.javacodegeeks.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/examples.javacodegeeks.com\/#organization","name":"Exelixis Media P.C.","url":"https:\/\/examples.javacodegeeks.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/javacodegeeks","https:\/\/x.com\/javacodegeeks"]},{"@type":"Person","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/aa8716fe8bdb3e382d5bdf9b9e960315","name":"Raghavan Muthu","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/image\/","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/01\/Raghavan-Muthu-96x96.jpg","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/01\/Raghavan-Muthu-96x96.jpg","caption":"Raghavan Muthu"},"description":"Raghavan alias Saravanan Muthu is a seasoned IT professional having more than 2 decades of experience on Java SE\/EE based Application Architecture, Design, Development, Management and Administration for Banking, Insurance, Telecom, HealthCare and Automobile Industries, having a very good hands on experience on Multi-threaded, batch processing applications and Relational Databases. He is currently working as a Director of Engineering for one of the Product based companies in India that delivers the product on Health Care and Insurance Domain. He holds a Post Graduation (Master of Science), and a PG Degree on Big Data Engineering from Birla Institute of Technology and Science (BITS), Pilani, India. He is a Founder, Chief Executive Volunteer and a Web Master of a non-profit charity organization named SHaDE (http:\/\/shade.org.in).","sameAs":["https:\/\/www.raghsonline.com\/","https:\/\/x.com\/https:\/\/twitter.com\/itsraghz"],"url":"https:\/\/examples.javacodegeeks.com\/author\/raghavan-muthu\/"}]}},"_links":{"self":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/36236","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/users\/87"}],"replies":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/comments?post=36236"}],"version-history":[{"count":0,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/36236\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/media\/24987"}],"wp:attachment":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/media?parent=36236"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/categories?post=36236"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/tags?post=36236"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}