Groovy – Unit Testing

Groovy – Unit Testing ”; Previous Next The fundamental unit of an object-oriented system is the class. Therefore unit testing consists of testig within a class. The approach taken is to create an object of the class under testing and use it to check that selected methods execute as expected. Not every method can be tested, since it is not always pratical to test each and every thing. But unit testing should be conducted for key and critical methods. JUnit is an open-source testing framework that is the accepted industry standard for the automated unit testing of Java code. Fortunately, the JUnit framework can be easily used for testing Groovy classes. All that is required is to extend the GroovyTestCase class that is part of the standard Groovy environment. The Groovy test case class is based on the Junit test case. Writing a Simple Junit Test Case Let assume we have the following class defined in a an application class file − Live Demo class Example { static void main(String[] args) { Student mst = new Student(); mst.name = “Joe”; mst.ID = 1; println(mst.Display()) } } public class Student { String name; int ID; String Display() { return name +ID; } } The output of the above program is given below. Joe1 And now suppose we wanted to write a test case for the Student class. A typical test case would look like the one below. The following points need to be noted about the following code − The test case class extends the GroovyTestCase class We are using the assert statement to ensure that the Display method returns the right string. class StudentTest extends GroovyTestCase { void testDisplay() { def stud = new Student(name : ”Joe”, ID : ”1”) def expected = ”Joe1” assertToString(stud.Display(), expected) } } The Groovy Test Suite Normally as the number of unit tests increases, it would become difficult to keep on executing all the test cases one by one. Hence Groovy provides a facility to create a test suite that can encapsulate all test cases into one logicial unit. The following codesnippet shows how this can be achieved. The following things should be noted about the code − The GroovyTestSuite is used to encapsulate all test cases into one. In the following example, we are assuming that we have two tests case files, one called StudentTest and the other is EmployeeTest which contains all of the necessary testing. import groovy.util.GroovyTestSuite import junit.framework.Test import junit.textui.TestRunner class AllTests { static Test suite() { def allTests = new GroovyTestSuite() allTests.addTestSuite(StudentTest.class) allTests.addTestSuite(EmployeeTest.class) return allTests } } TestRunner.run(AllTests.suite()) Print Page Previous Next Advertisements ”;

Groovy – Database

Groovy – Database ”; Previous Next Groovy’s groovy-sql module provides a higher-level abstraction over the current Java’s JDBC technology. The Groovy sql API supports a wide variety of databases, some of which are shown below. HSQLDB Oracle SQL Server MySQL MongoDB In our example, we are going to use MySQL DB as an example. In order to use MySQL with Groovy, the first thing to do is to download the MySQL jdbc jar file from the mysql site. The format of the MySQL will be shown below. mysql-connector-java-5.1.38-bin Then ensure to add the above jar file to the classpath in your workstation. Database Connection Before connecting to a MySQL database, make sure of the followings − You have created a database TESTDB. You have created a table EMPLOYEE in TESTDB. This table has fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME. User ID “testuser” and password “test123” are set to access TESTDB. Ensure you have downloaded the mysql jar file and added the file to your classpath. You have gone through MySQL tutorial to understand MySQL Basics The following example shows how to connect with MySQL database “TESTDB”. import java.sql.*; import groovy.sql.Sql class Example { static void main(String[] args) { // Creating a connection to the database def sql = Sql.newInstance(”jdbc:mysql://localhost:3306/TESTDB”, ”testuser”, ”test123”, ”com.mysql.jdbc.Driver”) // Executing the query SELECT VERSION which gets the version of the database // Also using the eachROW method to fetch the result from the database sql.eachRow(”SELECT VERSION()”){ row -> println row[0] } sql.close() } } While running this script, it is producing the following result − 5.7.10-log The Sql.newInstance method is used to establish a connection to the database. Creating Database Table The next step after connecting to the database is to create the tables in our database. The following example shows how to create a table in the database using Groovy. The execute method of the Sql class is used to execute statements against the database. import java.sql.*; import groovy.sql.Sql class Example { static void main(String[] args) { // Creating a connection to the database def sql = Sql.newInstance(”jdbc:mysql://localhost:3306/TESTDB”, ”testuser”, ”test123”, ”com.mysql.jdbc.Driver”) def sqlstr = “””CREATE TABLE EMPLOYEE ( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )””” sql.execute(sqlstr); sql.close() } } Insert Operation It is required when you want to create your records into a database table. Example The following example will insert a record in the employee table. The code is placed in a try catch block so that if the record is executed successfully, the transaction is committed to the database. If the transaction fails, a rollback is done. import java.sql.*; import groovy.sql.Sql class Example { static void main(String[] args) { // Creating a connection to the database def sql = Sql.newInstance(”jdbc:mysql://localhost:3306/TESTDB”, ”testuser”, ”test123”, ”com.mysql.jdbc.Driver”) sql.connection.autoCommit = false def sqlstr = “””INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES (”Mac”, ”Mohan”, 20, ”M”, 2000)””” try { sql.execute(sqlstr); sql.commit() println(“Successfully committed”) }catch(Exception ex) { sql.rollback() println(“Transaction rollback”) } sql.close() } } Suppose if you wanted to just select certain rows based on a criteria. The following codeshows how you can add a parameter placeholder to search for values. The above example can also be written to take in parameters as shown in the following code. The $ symbol is used to define a parameter which can then be replaced by values when the sql statement is executed. import java.sql.*; import groovy.sql.Sql class Example { static void main(String[] args) { // Creating a connection to the database def sql = Sql.newInstance(”jdbc:mysql://localhost:3306/TESTDB”, ”testuser”, ”test123”, ”com.mysql.jdbc.Driver”) sql.connection.autoCommit = false def firstname = “Mac” def lastname =”Mohan” def age = 20 def sex = “M” def income = 2000 def sqlstr = “INSERT INTO EMPLOYEE(FIRST_NAME,LAST_NAME, AGE, SEX, INCOME) VALUES ” + “(${firstname}, ${lastname}, ${age}, ${sex}, ${income} )” try { sql.execute(sqlstr); sql.commit() println(“Successfully committed”) } catch(Exception ex) { sql.rollback() println(“Transaction rollback”) } sql.close() } } READ Operation READ Operation on any database means to fetch some useful information from the database. Once our database connection is established, you are ready to make a query into this database. The read operation is performed by using the eachRow method of the sql class. Syntax eachRow(GString gstring, Closure closure) Performs the given SQL query calling the given Closure with each row of the result set. Parameters Gstring − The sql statement which needs to be executed. Closure − The closure statement to process the rows retrived from the read operation. Performs the given SQL query calling the given Closure with each row of the result set. The following code example shows how to fetch all the records from the employee table. import java.sql.*; import groovy.sql.Sql class Example { static void main(String[] args) { // Creating a connection to the database def sql = Sql.newInstance(”jdbc:mysql://localhost:3306/TESTDB”, ”testuser”, ”test123”, ”com.mysql.jdbc.Driver”) sql.eachRow(”select * from employee”) { tp -> println([tp.FIRST_NAME,tp.LAST_NAME,tp.age,tp.sex,tp.INCOME]) } sql.close() } } The output from the above program would be − [Mac, Mohan, 20, M, 2000.0] Update Operation UPDATE Operation on any database means to update one or more records, which are already available in the database. The following procedure updates all the records having SEX as ”M”. Here, we increase AGE of all the males by one year. import java.sql.*; import groovy.sql.Sql class Example { static void main(String[] args){ // Creating a connection to the database def sql = Sql.newInstance(”jdbc:mysql://localhost:3306/TESTDB”, ”testuser”, ”test@123”, ”com.mysql.jdbc.Driver”) sql.connection.autoCommit = false def sqlstr = “UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = ”M”” try { sql.execute(sqlstr); sql.commit() println(“Successfully committed”) }catch(Exception ex) { sql.rollback() println(“Transaction rollback”) } sql.close() } } DELETE Operation DELETE operation is required when you want to delete some records from your database. Following is the procedure to delete all the records from EMPLOYEE where AGE is more than 20. import java.sql.*; import groovy.sql.Sql class Example { static void main(String[] args) { // Creating a connection to the database def sql = Sql.newInstance(”jdbc:mysql://localhost:3306/TESTDB”, ”testuser”, ”test@123”, ”com.mysql.jdbc.Driver”) sql.connection.autoCommit = false def sqlstr = “DELETE FROM EMPLOYEE WHERE AGE > 20” try { sql.execute(sqlstr); sql.commit() println(“Successfully committed”)

Groovy – Annotations

Groovy – Annotations ”; Previous Next Annotations are a form of metadata wherein they provide data about a program that is not part of the program itself. Annotations have no direct effect on the operation of the code they annotate. Annotations are mainly used for the following reasons − Information for the compiler − Annotations can be used by the compiler to detect errors or suppress warnings. Compile-time and deployment-time processing − Software tools can process annotation information to generate code, XML files, and so forth. Runtime processing − Some annotations are available to be examined at runtime. In Groovy, a basic annotation looks as follows − @interface – The at sign character (@) indicates to the compiler that what follows is an annotation. An annotation may define members in the form of methods without bodies and an optional default value. Annotation’s can be applied to the following types − String Type An example of an Annotation for a string is given below − @interface Simple { String str1() default “HelloWorld”; } Enum type enum DayOfWeek { mon, tue, wed, thu, fri, sat, sun } @interface Scheduled { DayOfWeek dayOfWeek() } Class type @interface Simple {} @Simple class User { String username int age } def user = new User(username: “Joe”,age:1); println(user.age); println(user.username); Annotation Member Values When an annotation is used, it is required to set at least all members that do not have a default value. An example is given below. When the annotation Example is used after being defined, it needs to have a value assigned to it. @interface Example { int status() } @Example(status = 1) Closure Annotation Parameters A good feature of annotations in Groovy is that you can use a closure as an annotation value also. Therefore annotations may be used with a wide variety of expressions. An example is given below on this. The annotation Onlyif is created based on a class value. Then the annotation is applied to two methods which posts different messages to the result variable based on the value of the number variable. @interface OnlyIf { Class value() } @OnlyIf({ number<=6 }) void Version6() { result << ”Number greater than 6” } @OnlyIf({ number>=6 }) void Version7() { result << ”Number greater than 6” } Meta Annotations This is quite a useful feature of annotations in groovy. There may comes times wherein you might have multiple annotations for a method as the one shown below. Sometimes this can become messy to have multiple annotations. @Procedure @Master class MyMasterProcedure {} In such a case you can define a meta-annotation which clubs multiple annotations together and the apply the meta annotation to the method. So for the above example you can fist define the collection of annotation using the AnnotationCollector. import groovy.transform.AnnotationCollector @Procedure @Master @AnnotationCollector Once this is done, you can apply the following meta-annotator to the method − import groovy.transform.AnnotationCollector @Procedure @Master @AnnotationCollector @MasterProcedure class MyMasterProcedure {} Print Page Previous Next Advertisements ”;

Groovy – Builders

Groovy – Builders ”; Previous Next During the process of software development, sometimes developers spend a lot of time in creating Data structures, domain classes, XML, GUI Layouts, Output streams etc.And sometimes the code used to create these specific requirements results in the repitition of the same snippet of code in many places. This is where Groovy builders come into play. Groovy has builders which can be used to create standard objects and structures. These builders saves time as developer dont need to write their own code to create these builders. In the couse of this chapter we will look at the different builders available in groovy. Swing Builder In groovy one can also create graphical user interfaces using the swing builders available in groovy. The main class for developing swing components is the SwingBuilder class. This class has many methods for creating graphical components such as − JFrame − This is for creating the frame element. JTextField − This is used for creating the textfield component. Let’s look at a simple example of how to create a Swing application using the SwingBuilder class. In the following example, you can see the following points − You need to import the groovy.swing.SwingBuilder and the javax.swing.* classes. All of the componets displayed in the Swing application are part of the SwingBuilder class. For the frame itself, you can specify the initial location and size of the frame. You can also specify the title of the frame. You need to set the Visibility property to true in order for the frame to be shown. import groovy.swing.SwingBuilder import javax.swing.* // Create a builder def myapp = new SwingBuilder() // Compose the builder def myframe = myapp.frame(title : ”Tutorials Point”, location : [200, 200], size : [400, 300], defaultCloseOperation : WindowConstants.EXIT_ON_CLOSE { label(text : ”Hello world”) } // The following statement is used for displaying the form frame.setVisible(true) The output of the above program is given below. The following output shows a JFrame along with a JLabel with a text of Hello World. Let’s look at our next example for creating an input screen with textboxes. In the following example, we want to create a form which has text boxes for Student name, subject and School Name. In the following example, you can see the following key points − We are defining a layout for our controls on the screen. In this case we are using the Grid Layout. We are using an alignment property for our labels. We are using the textField method for displaying textboxes on the screen. import groovy.swing.SwingBuilder import javax.swing.* import java.awt.* // Create a builder def myapp = new SwingBuilder() // Compose the builder def myframe = myapp.frame(title : ”Tutorials Point”, location : [200, 200], size : [400, 300], defaultCloseOperation : WindowConstants.EXIT_ON_CLOSE) { panel(layout: new GridLayout(3, 2, 5, 5)) { label(text : ”Student Name:”, horizontalAlignment : JLabel.RIGHT) textField(text : ””, columns : 10) label(text : ”Subject Name:”, horizontalAlignment : JLabel.RIGHT) textField(text : ””, columns : 10) label(text : ”School Name:”, horizontalAlignment : JLabel.RIGHT) textField(text : ””, columns : 10) } } // The following statement is used for displaying the form myframe.setVisible(true) The output of the above program is given below − Event Handlers Now let’s look at event handlers. Event handlers are used for button to perform some sort of processing when a button is pressed. Each button pseudomethod call includes the actionPerformed parameter. This represents a code block presented as a closure. Let’s look at our next example for creating a screen with 2 buttons. When either button is pressed a corresponding message is sent to the console screen. In the following example, you can see the following key points − For each button defined, we are using the actionPerformed method and defining a closure to send some output to the console when the button is clicked. import groovy.swing.SwingBuilder import javax.swing.* import java.awt.* def myapp = new SwingBuilder() def buttonPanel = { myapp.panel(constraints : BorderLayout.SOUTH) { button(text : ”Option A”, actionPerformed : { println ”Option A chosen” }) button(text : ”Option B”, actionPerformed : { println ”Option B chosen” }) } } def mainPanel = { myapp.panel(layout : new BorderLayout()) { label(text : ”Which Option do you want”, horizontalAlignment : JLabel.CENTER, constraints : BorderLayout.CENTER) buttonPanel() } } def myframe = myapp.frame(title : ”Tutorials Point”, location : [100, 100], size : [400, 300], defaultCloseOperation : WindowConstants.EXIT_ON_CLOSE){ mainPanel() } myframe.setVisible(true) The output of the above program is given below. When you click on either button, the required message is sent to the console log screen. Another variation of the above example is to define methods which can can act as handlers. In the following example we are defining 2 handlers of DisplayA and DisplayB. import groovy.swing.SwingBuilder import javax.swing.* import java.awt.* def myapp = new SwingBuilder() def DisplayA = { println(“Option A”) } def DisplayB = { println(“Option B”) } def buttonPanel = { myapp.panel(constraints : BorderLayout.SOUTH) { button(text : ”Option A”, actionPerformed : DisplayA) button(text : ”Option B”, actionPerformed : DisplayB) } } def mainPanel = { myapp.panel(layout : new BorderLayout()) { label(text : ”Which Option do you want”, horizontalAlignment : JLabel.CENTER, constraints : BorderLayout.CENTER) buttonPanel() } } def myframe = myapp.frame(title : ”Tutorials Point”, location : [100, 100], size : [400, 300], defaultCloseOperation : WindowConstants.EXIT_ON_CLOSE) { mainPanel() } myframe.setVisible(true) The output of the above program would remain the same as the earlier example. DOM Builder The DOM builder can be used for parsing HTML, XHTML and XML and converting it into a W3C DOM tree. The following example shows how the DOM builder can be used. String records = ””” <library> <Student> <StudentName division = ”A”>Joe</StudentName> <StudentID>1</StudentID> </Student> <Student> <StudentName division = ”B”>John</StudentName> <StudentID>2</StudentID> </Student> <Student> <StudentName division = ”C”>Mark</StudentName> <StudentID>3</StudentID> </Student> </library>””” def rd = new StringReader(records) def doc = groovy.xml.DOMBuilder.parse(rd) JsonBuilder The JsonBuilder is used for creating json type objects. The following example shows how the Json builder can be used. Live Demo def builder = new groovy.json.JsonBuilder() def root = builder.students {

Groovy – JSON

Groovy – JSON ”; Previous Next This chapter covers how to we can use the Groovy language for parsing and producing JSON objects. JSON Functions Sr.No Function & Libraries 1 JsonSlurper JsonSlurper is a class that parses JSON text or reader content into Groovy data Structures such as maps, lists and primitive types like Integer, Double, Boolean and String. 2 JsonOutput This method is responsible for serialising Groovy objects into JSON strings. Parsing Data using JsonSlurper JsonSlurper is a class that parses JSON text or reader content into Groovy data Structures such as maps, lists and primitive types like Integer, Double, Boolean and String. Syntax def slurper = new JsonSlurper() JSON slurper parses text or reader content into a data structure of lists and maps. The JsonSlurper class comes with a couple of variants for parser implementations. Sometimes you may have different requirements when it comes to parsing certain strings. Let’s take an instance wherein one needs to read the JSON which is returned from the response from a web server. In such a case it’s beneficial to use the parser JsonParserLax variant. This parsee allows comments in the JSON text as well as no quote strings etc. To specify this sort of parser you need to use JsonParserType.LAX parser type when defining an object of the JsonSlurper. Let’s see an example of this given below. The example is for getting JSON data from a web server using the http module. For this type of traversal, the best option is to have the parser type set to JsonParserLax variant. http.request( GET, TEXT ) { headers.Accept = ”application/json” headers.”User-Agent” = USER_AGENT response.success = { res, rd -> def jsonText = rd.text //Setting the parser type to JsonParserLax def parser = new JsonSlurper().setType(JsonParserType.LAX) def jsonResp = parser.parseText(jsonText) } } Similarly the following additional parser types are available in Groovy − The JsonParserCharArray parser basically takes a JSON string and operates on the underlying character array. During value conversion it copies character sub-arrays (a mechanism known as “chopping”) and operates on them individually. The JsonFastParser is a special variant of the JsonParserCharArray and is the fastest parser. JsonFastParser is also known as the index-overlay parser. During parsing of the given JSON String it tries as hard as possible to avoid creating new char arrays or String instances. It just keeps pointers to the underlying original character array only. In addition, it defers object creation as late as possible. The JsonParserUsingCharacterSource is a special parser for very large files. It uses a technique called “character windowing” to parse large JSON files (large means files over 2MB size in this case) with constant performance characteristics. Parsing Text Let’s have a look at some examples of how we can use the JsonSlurper class. Live Demo import groovy.json.JsonSlurper class Example { static void main(String[] args) { def jsonSlurper = new JsonSlurper() def object = jsonSlurper.parseText(”{ “name”: “John”, “ID” : “1”}”) println(object.name); println(object.ID); } } In the above example, we are − First creating an instance of the JsonSlurper class We are then using the parseText function of the JsonSlurper class to parse some JSON text. When we get the object, you can see that we can actually access the values in the JSON string via the key. The output of the above program is given below − John 1 Parsing List of Integers Let’s take a look at another example of the JsonSlurper parsing method. In the following example, we are pasing a list of integers. You will notice from The following codethat we are able to use the List method of each and pass a closure to it. Live Demo import groovy.json.JsonSlurper class Example { static void main(String[] args) { def jsonSlurper = new JsonSlurper() Object lst = jsonSlurper.parseText(”{ “List”: [2, 3, 4, 5] }”) lst.each { println it } } } The output of the above program is given below − List=[2, 3, 4, 5] Parsing List of Primitive Data types The JSON parser also supports the primitive data types of string, number, object, true, false and null. The JsonSlurper class converts these JSON types into corresponding Groovy types. The following example shows how to use the JsonSlurper to parse a JSON string. And here you can see that the JsonSlurper is able to parse the individual items into their respective primitive types. Live Demo import groovy.json.JsonSlurper class Example { static void main(String[] args) { def jsonSlurper = new JsonSlurper() def obj = jsonSlurper.parseText ””” {“Integer”: 12, “fraction”: 12.55, “double”: 12e13}””” println(obj.Integer); println(obj.fraction); println(obj.double); } } The output of the above program is given below − 12 12.55 1.2E+14 JsonOutput Now let’s talk about how to print output in Json. This can be done by the JsonOutput method. This method is responsible for serialising Groovy objects into JSON strings. Syntax Static string JsonOutput.toJson(datatype obj) Parameters − The parameters can be an object of a datatype – Number, Boolean, character,String, Date, Map, closure etc. Return type − The return type is a json string. Example Following is a simple example of how this can be achieved. import groovy.json.JsonOutput class Example { static void main(String[] args) { def output = JsonOutput.toJson([name: ”John”, ID: 1]) println(output); } } The output of the above program is given below − {“name”:”John”,”ID”:1} The JsonOutput can also be used for plain old groovy objects. In the following example, you can see that we are actually passing objects of the type Student to the JsonOutput method. Live Demo import groovy.json.JsonOutput class Example { static void main(String[] args) { def output = JsonOutput.toJson([ new Student(name: ”John”,ID:1), new Student(name: ”Mark”,ID:2)]) println(output); } } class Student { String name int ID; } The output of the above program is given below − [{“name”:”John”,”ID”:1},{“name”:”Mark”,”ID”:2}] Print Page Previous Next Advertisements ”;

Groovy – DSLS

Groovy – DSLS ”; Previous Next Groovy allows one to omit parentheses around the arguments of a method call for top-level statements. This is known as the “command chain” feature. This extension works by allowing one to chain such parentheses-free method calls, requiring neither parentheses around arguments, nor dots between the chained calls. If a call is executed as a b c d, this will actually be equivalent to a(b).c(d). DSL or Domain specific language is meant to simplify the code written in Groovy in such a way that it becomes easily understandable for the common user. The following example shows what exactly is meant by having a domain specific language. def lst = [1,2,3,4] print lst The above code shows a list of numbers being printed to the console using the println statement. In a domain specific language the commands would be as − Given the numbers 1,2,3,4 Display all the numbers So the above example shows the transformation of the programming language to meet the needs of a domain specific language. Let’s look at a simple example of how we can implement DSLs in Groovy − class EmailDsl { String toText String fromText String body /** * This method accepts a closure which is essentially the DSL. Delegate the * closure methods to * the DSL class so the calls can be processed */ def static make(closure) { EmailDsl emailDsl = new EmailDsl() // any method called in closure will be delegated to the EmailDsl class closure.delegate = emailDsl closure() } /** * Store the parameter as a variable and use it later to output a memo */ def to(String toText) { this.toText = toText } def from(String fromText) { this.fromText = fromText } def body(String bodyText) { this.body = bodyText } } EmailDsl.make { to “Nirav Assar” from “Barack Obama” body “How are things? We are doing well. Take care” } When we run the above program, we will get the following result − How are things? We are doing well. Take care The following needs to be noted about the above code implementation − A static method is used that accepts a closure. This is mostly a hassle free way to implement a DSL. In the email example, the class EmailDsl has a make method. It creates an instance and delegates all calls in the closure to the instance. This is the mechanism where the “to”, and “from” sections end up executing methods inside the EmailDsl class. Once the to() method is called, we store the text in the instance for formatting later on. We can now call the EmailDSL method with an easy language that is easy to understand for end users. Print Page Previous Next Advertisements ”;

Groovy – JMX

Groovy – JMX ”; Previous Next JMX is the defacto standard which is used for monitoring all applications which have anything to do with the Java virual environment. Given that Groovy sits directly on top of Java, Groovy can leverage the tremendous amount of work already done for JMX with Java. Monitoring the JVM One can use the standard classes available in java.lang.management for carrying out the monitoring of the JVM. The following code example shows how this can be done. Live Demo import java.lang.management.* def os = ManagementFactory.operatingSystemMXBean println “””OPERATING SYSTEM: tOS architecture = $os.arch tOS name = $os.name tOS version = $os.version tOS processors = $os.availableProcessors “”” def rt = ManagementFactory.runtimeMXBean println “””RUNTIME: tRuntime name = $rt.name tRuntime spec name = $rt.specName tRuntime vendor = $rt.specVendor tRuntime spec version = $rt.specVersion tRuntime management spec version = $rt.managementSpecVersion “”” def mem = ManagementFactory.memoryMXBean def heapUsage = mem.heapMemoryUsage def nonHeapUsage = mem.nonHeapMemoryUsage println “””MEMORY: HEAP STORAGE: tMemory committed = $heapUsage.committed tMemory init = $heapUsage.init tMemory max = $heapUsage.max tMemory used = $heapUsage.used NON-HEAP STORAGE: tNon-heap memory committed = $nonHeapUsage.committed tNon-heap memory init = $nonHeapUsage.init tNon-heap memory max = $nonHeapUsage.max tNon-heap memory used = $nonHeapUsage.used “”” println “GARBAGE COLLECTION:” ManagementFactory.garbageCollectorMXBeans.each { gc -> println “tname = $gc.name” println “ttcollection count = $gc.collectionCount” println “ttcollection time = $gc.collectionTime” String[] mpoolNames = gc.memoryPoolNames mpoolNames.each { mpoolName -> println “ttmpool name = $mpoolName” } } When the code is executed, the output will vary depending on the system on which the code is run. A sample of the output is given below. OPERATING SYSTEM: OS architecture = x86 OS name = Windows 7 OS version = 6.1 OS processors = 4 RUNTIME: Runtime name = 5144@Babuli-PC Runtime spec name = Java Virtual Machine Specification Runtime vendor = Oracle Corporation Runtime spec version = 1.7 Runtime management spec version = 1.2 MEMORY: HEAP STORAGE: Memory committed = 16252928 Memory init = 16777216 Memory max = 259522560 Memory used = 7355840 NON-HEAP STORAGE: Non-heap memory committed = 37715968 Non-heap memory init = 35815424 Non-heap memory max = 123731968 Non-heap memory used = 18532232 GARBAGE COLLECTION: name = Copy collection count = 15 collection time = 47 mpool name = Eden Space mpool name = Survivor Space name = MarkSweepCompact collection count = 0 collection time = 0 mpool name = Eden Space mpool name = Survivor Space mpool name = Tenured Gen mpool name = Perm Gen mpool name = Perm Gen [shared-ro] mpool name = Perm Gen [shared-rw] Monitoring Tomcat In order to monitor tomcat, the following parameter should be set when tomcat is started − set JAVA_OPTS = -Dcom.sun.management.jmxremote Dcom.sun.management.jmxremote.port = 9004 -Dcom.sun.management.jmxremote.authenticate=false Dcom.sun.management.jmxremote.ssl = false The following code uses JMX to discover the available MBeans in the running Tomcat, determine which are the web modules and extract the processing time for each web module. import groovy.swing.SwingBuilder import javax.management.ObjectName import javax.management.remote.JMXConnectorFactory as JmxFactory import javax.management.remote.JMXServiceURL as JmxUrl import javax.swing.WindowConstants as WC import org.jfree.chart.ChartFactory import org.jfree.data.category.DefaultCategoryDataset as Dataset import org.jfree.chart.plot.PlotOrientation as Orientation def serverUrl = ”service:jmx:rmi:///jndi/rmi://localhost:9004/jmxrmi” def server = JmxFactory.connect(new JmxUrl(serverUrl)).MBeanServerConnection def serverInfo = new GroovyMBean(server, ”Catalina:type = Server”).serverInfo println “Connected to: $serverInfo” def query = new ObjectName(”Catalina:*”) String[] allNames = server.queryNames(query, null) def modules = allNames.findAll { name -> name.contains(”j2eeType=WebModule”) }.collect{ new GroovyMBean(server, it) } println “Found ${modules.size()} web modules. Processing …” def dataset = new Dataset() modules.each { m -> println m.name() dataset.addValue m.processingTime, 0, m.path } Print Page Previous Next Advertisements ”;

Groovy – XML

Groovy – XML ”; Previous Next XML is a portable, open source language that allows programmers to develop applications that can be read by other applications, regardless of operating system and/or developmental language. This is one of the most common languages used for exchanging data between applications. What is XML? The Extensible Markup Language XML is a markup language much like HTML or SGML. This is recommended by the World Wide Web Consortium and available as an open standard. XML is extremely useful for keeping track of small to medium amounts of data without requiring a SQLbased backbone. XML Support in Groovy The Groovy language also provides a rich support of the XML language. The two most basic XML classes used are − XML Markup Builder − Groovy supports a tree-based markup generator, BuilderSupport, that can be subclassed to make a variety of tree-structured object representations. Commonly, these builders are used to represent XML markup, HTML markup. Groovy’s markup generator catches calls to pseudomethods and converts them into elements or nodes of a tree structure. Parameters to these pseudomethods are treated as attributes of the nodes. Closures as part of the method call are considered as nested subcontent for the resulting tree node. XML Parser − The Groovy XmlParser class employs a simple model for parsing an XML document into a tree of Node instances. Each Node has the name of the XML element, the attributes of the element, and references to any child Nodes. This model is sufficient for most simple XML processing. For all our XML code examples, let”s use the following simple XML file movies.xml for construction of the XML file and reading the file subsequently. <collection shelf = “New Arrivals”> <movie title = “Enemy Behind”> <type>War, Thriller</type> <format>DVD</format> <year>2003</year> <rating>PG</rating> <stars>10</stars> <description>Talk about a US-Japan war</description> </movie> <movie title = “Transformers”> <type>Anime, Science Fiction</type> <format>DVD</format> <year>1989</year> <rating>R</rating> <stars>8</stars> <description>A schientific fiction</description> </movie> <movie title = “Trigun”> <type>Anime, Action</type> <format>DVD</format> <year>1986</year> <rating>PG</rating> <stars>10</stars> <description>Vash the Stam pede!</description> </movie> <movie title = “Ishtar”> <type>Comedy</type> <format>VHS</format> <year>1987</year> <rating>PG</rating> <stars>2</stars> <description>Viewable boredom </description> </movie> </collection> XML Markup Builder Syntax public MarkupBuilder() The MarkupBuilder is used to construct the entire XML document. The XML document is created by first creating an object of the XML document class. Once the object is created, a pseudomethod can be called to create the various elements of the XML document. Let’s look at an example of how to create one block, that is, one movie element from the above XML document − Live Demo import groovy.xml.MarkupBuilder class Example { static void main(String[] args) { def mB = new MarkupBuilder() // Compose the builder mB.collection(shelf : ”New Arrivals”) { movie(title : ”Enemy Behind”) type(”War, Thriller”) format(”DVD”) year(”2003”) rating(”PG”) stars(10) description(”Talk about a US-Japan war”) } } } In the above example, the following things need to be noted − mB.collection() − This is a markup generator that creates the head XML tag of <collection></collection> movie(title : ”Enemy Behind”) − These pseudomethods create the child tags with this method creating the tag with the value. By specifying a value called title, this actually indicates that an attribute needs to be created for the element. A closure is provided to the pseudomethod to create the remaining elements of the XML document. The default constructor for the class MarkupBuilder is initialized so that the generated XML is issued to the standard output stream When we run the above program, we will get the following result − <collection shelf = ”New Arrivals”> <movie title = ”Enemy Behind” /> <type>War, Thriller</type> <format>DVD</format> <year>2003</year> <rating>PG</rating> <stars>10</stars> <description>Talk about a US-Japan war</description> </movie> </collection> In order to create the entire XML document, the following things need to be done. A map entry needs to be created to store the different values of the elements. For each element of the map, we are assigning the value to each element. Live Demo import groovy.xml.MarkupBuilder class Example { static void main(String[] args) { def mp = [1 : [”Enemy Behind”, ”War, Thriller”,”DVD”,”2003”, ”PG”, ”10”,”Talk about a US-Japan war”], 2 : [”Transformers”,”Anime, Science Fiction”,”DVD”,”1989”, ”R”, ”8”,”A scientific fiction”], 3 : [”Trigun”,”Anime, Action”,”DVD”,”1986”, ”PG”, ”10”,”Vash the Stam pede”], 4 : [”Ishtar”,”Comedy”,”VHS”,”1987”, ”PG”, ”2”,”Viewable boredom ”]] def mB = new MarkupBuilder() // Compose the builder def MOVIEDB = mB.collection(”shelf”: ”New Arrivals”) { mp.each { sd -> mB.movie(”title”: sd.value[0]) { type(sd.value[1]) format(sd.value[2]) year(sd.value[3]) rating(sd.value[4]) stars(sd.value[4]) description(sd.value[5]) } } } } } When we run the above program, we will get the following result − <collection shelf = ”New Arrivals”> <movie title = ”Enemy Behind”> <type>War, Thriller</type> <format>DVD</format> <year>2003</year> <rating>PG</rating> <stars>PG</stars> <description>10</description> </movie> <movie title = ”Transformers”> <type>Anime, Science Fiction</type> <format>DVD</format> <year>1989</year> <rating>R</rating> <stars>R</stars> <description>8</description> </movie> <movie title = ”Trigun”> <type>Anime, Action</type> <format>DVD</format> <year>1986</year> <rating>PG</rating> <stars>PG</stars> <description>10</description> </movie> <movie title = ”Ishtar”> <type>Comedy</type> <format>VHS</format> <year>1987</year> <rating>PG</rating> <stars>PG</stars> <description>2</description> </movie> </collection> XML Parsing The Groovy XmlParser class employs a simple model for parsing an XML document into a tree of Node instances. Each Node has the name of the XML element, the attributes of the element, and references to any child Nodes. This model is sufficient for most simple XML processing. Syntax public XmlParser() throws ParserConfigurationException, SAXException The following codeshows an example of how the XML parser can be used to read an XML document. Let’s assume we have the same document called Movies.xml and we wanted to parse the XML document and display a proper output to the user. The following codeis a snippet of how we can traverse through the entire content of the XML document and display a proper response to the user. import groovy.xml.MarkupBuilder import groovy.util.* class Example { static void main(String[] args) { def parser = new XmlParser() def doc = parser.parse(“D:\Movies.xml”); doc.movie.each{ bk-> print(“Movie Name:”) println “${bk[”@title”]}” print(“Movie Type:”) println “${bk.type[0].text()}” print(“Movie Format:”) println “${bk.format[0].text()}” print(“Movie year:”) println “${bk.year[0].text()}” print(“Movie rating:”) println “${bk.rating[0].text()}” print(“Movie stars:”) println “${bk.stars[0].text()}” print(“Movie description:”) println “${bk.description[0].text()}” println(“*******************************”) } } } When we run the above program, we will get the following result − Movie Name:Enemy Behind Movie

Groovy – Traits

Groovy – Traits ”; Previous Next Traits are a structural construct of the language which allow − Composition of behaviors. Runtime implementation of interfaces. Compatibility with static type checking/compilation They can be seen as interfaces carrying both default implementations and state. A trait is defined using the trait keyword. An example of a trait is given below − trait Marks { void DisplayMarks() { println(“Display Marks”); } } One can then use the implement keyword to implement the trait in the similar way as interfaces. class Example { static void main(String[] args) { Student st = new Student(); st.StudentID = 1; st.Marks1 = 10; println(st.DisplayMarks()); } } trait Marks { void DisplayMarks() { println(“Display Marks”); } } class Student implements Marks { int StudentID int Marks1; } Implementing Interfaces Traits may implement interfaces, in which case the interfaces are declared using the implements keyword. An example of a trait implementing an interface is given below. In the following example the following key points can be noted. An interface Total is defined with the method DisplayTotal. The trait Marks implements the Total interface and hence needs to provide an implementation for the DisplayTotal method. Live Demo class Example { static void main(String[] args) { Student st = new Student(); st.StudentID = 1; st.Marks1 = 10; println(st.DisplayMarks()); println(st.DisplayTotal()); } } interface Total { void DisplayTotal() } trait Marks implements Total { void DisplayMarks() { println(“Display Marks”); } void DisplayTotal() { println(“Display Total”); } } class Student implements Marks { int StudentID int Marks1; } The output of the above program would be − Display Marks Display Total Properties A trait may define properties. An example of a trait with a property is given below. In the following example, the Marks1 of type integer is a property. class Example { static void main(String[] args) { Student st = new Student(); st.StudentID = 1; println(st.DisplayMarks()); println(st.DisplayTotal()); } interface Total { void DisplayTotal() } trait Marks implements Total { int Marks1; void DisplayMarks() { this.Marks1 = 10; println(this.Marks1); } void DisplayTotal() { println(“Display Total”); } } class Student implements Marks { int StudentID } } The output of the above program would be − 10 Display Total Composition of Behaviors Traits can be used to implement multiple inheritance in a controlled way, avoiding the diamond issue. In the following code example, we have defined two traits – Marks and Total. Our Student class implements both traits. Since the student class extends both traits, it is able to access the both of the methods – DisplayMarks and DisplayTotal. Live Demo class Example { static void main(String[] args) { Student st = new Student(); st.StudentID = 1; println(st.DisplayMarks()); println(st.DisplayTotal()); } } trait Marks { void DisplayMarks() { println(“Marks1”); } } trait Total { void DisplayTotal() { println(“Total”); } } class Student implements Marks,Total { int StudentID } The output of the above program would be − Total Marks1 Extending Traits Traits may extend another trait, in which case you must use the extends keyword. In the following code example, we are extending the Total trait with the Marks trait. Live Demo class Example { static void main(String[] args) { Student st = new Student(); st.StudentID = 1; println(st.DisplayMarks()); } } trait Marks { void DisplayMarks() { println(“Marks1”); } } trait Total extends Marks { void DisplayMarks() { println(“Total”); } } class Student implements Total { int StudentID } The output of the above program would be − Total Print Page Previous Next Advertisements ”;

Groovy – Decision Making

Groovy – Decision Making ”; Previous Next Decision-making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Sr.No. Statements & Description 1 if Statement The general working of this statement is that first a condition is evaluated in the if statement. If the condition is true, it then executes the statements. 2 if/else Statement The general working of this statement is that first a condition is evaluated in the if statement. If the condition is true it then executes the statements thereafter and stops before the else condition and exits out of the loop. If the condition is false it then executes the statements in the else statement block and then exits the loop. 3 Nested If Statement Sometimes there is a requirement to have multiple if statement embedded inside of each other. 4 Switch Statement Sometimes the nested if-else statement is so common and is used so often that an easier statement was designed called the switch statement. 5 Nested Switch Statement It is also possible to have a nested set of switch statements. Print Page Previous Next Advertisements ”;