Welcome!

Java IoT Authors: Elizabeth White, Pat Romanski, Akhil Sahai, JP Morgenthal, Janakiram MSV

Related Topics: Java IoT

Java IoT: Blog Feed Post

A Quick Introduction to the Groovy Language (Part 1)

Groovy is a general purpose scripting language that runs on the JVM

Before I start talking about using Groovy's capabilities to create a DSL (mostly in Java), let's take a few minutes to go over what Groovy is.

Groovy is a general purpose scripting language which runs on the JVM, and can largely be viewed as a superset of Java.  Take the following program:

public class Hello {

    String name;
    
    public void sayHello() {
        System.out.println("Hello "+getName()+"!");
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public String getName() {
        return name;
    }
    
    public static void main(String[] args) {
    
        Hello hello = new Hello();
        hello.setName("world");
        hello.sayHello();
    }
}

Is this a Groovy program or a Java program?  Yes, it is - it will compile and run in both.  This basic program is a bit wordy, and we can certainly do things more simply in Java, but this contains a number of patterns that you'd commonly see, including the use of the bean pattern, as well as the use of the main method to make the class executable via the java command line program.    When we run it, it simply prints out "Hello world!", as is customary in these sorts of things.

To try this out in Java, you can use your favorite IDE.  You can also use an IDE to try this in Groovy, but you may just want to use the groovyConsole program, which is available as part of the GDK.  Download it now, and play along via cut and paste...

Now, as I said, Groovy is a rough superset of Java - one difference is that things are public by default.  That means we could just as easily say the following:

class Hello {

    String name;
    
    void sayHello() {
        System.out.println("Hello "+getName()+"!");
    }
    
    void setName(String name) {
        this.name = name;
    }
    
    String getName() {
        return name;
    }
    
    static void main(String[] args) {
    
        Hello hello = new Hello();
        hello.setName("world");
        hello.sayHello();
    }
}

Accessors and mutators are automatically created for your class variables, so we can also shorten it by taking those out:

class Hello {

    String name;
    
    void sayHello() {
        System.out.println("Hello "+getName()+"!");
    }
    
    static void main(String[] args) {
    
        Hello hello = new Hello();
        hello.setName("world");
        hello.sayHello();
    }
}

Now we're getting somewhere.  In Groovy, System.out.println can be shortened to just "println" as a convenience, so you can also say:

class Hello {

    String name;
    
    void sayHello() {
        println("Hello "+getName()+"!");
    }
    
    static void main(String[] args) {
    
        Hello hello = new Hello();
        hello.setName("world");
        hello.sayHello();
    }
}

There's also a difference in how Groovy deals with String objects - double quote strings allow for variable substitution.  There's also single quote strings, which do not:

class Hello {

    String name;
    
    void sayHello() {
        println("Hello $name!");
    }
    
    static void main(String[] args) {
    
        Hello hello = new Hello();
        hello.setName('world');
        hello.sayHello();
    }
}

Groovy also allows dot notation to get and set fields of classes, just like Java.  Unlike Java, this will actually go through the getter/setter methods (which, you'll recall, are automatically generated in our current example):

class Hello {

    String name;
    
    void sayHello() {
        println("Hello $name!");
    }
    
    static void main(String[] args) {
    
        Hello hello = new Hello();
        hello.name = 'world';
        hello.sayHello();
    }
}

Typing information is also optional - instead of specifying a type, you can just use the keyword def.  Use of def is mandatory for methods, but optional for parameters on those methods.  You should also use def for class and method variables.  While we're at it, let's take out those semicolons:  They're optional in Groovy.

class Hello {

    def sayHello(name) {
        println("Hello $name!")
    }
    
    static def main(args) {
        Hello hello = new Hello()
        def name = 'world'
        hello.sayHello(name)
    }
}

OK, that's nice, but we can get this even shorter. Because Groovy is a scripting language, there's automatically a wrapping class (called Script, which will become very important to us later). This wrapping class means that we can get rid of our own wrapping class, as well as the main method, like so:

def sayHello(name) {
    println("Hello $name!")
}
def name = 'world'
sayHello(name)

That's all for now, I'll do a second part to this later.  But for now, if someone asks you if you know Groovy, you can now say "Sure, a bit".

Credit for the idea behind this post goes to Guillaume Laforge - I saw him give a variation of this as an intro to his talk at JavaOne, and loved it.

(As usual, this article is cross posted on my main blog site.)

Read the original blog entry...

More Stories By Jim Driscoll

Jim Driscoll has worked at Sun Microsystems for 12 years, working on such projects as the first version of Servlets (in the Java Web Server), and the initial implementation of Java 2, Enterprise Edition. He is currently a Senior Engineer working on the implementation of Java Server Faces, helping to integrate technologies such as AJAX and Comet into the new release.

@ThingsExpo Stories
The cloud market growth today is largely in public clouds. While there is a lot of spend in IT departments in virtualization, these aren’t yet translating into a true “cloud” experience within the enterprise. What is stopping the growth of the “private cloud” market? In his general session at 18th Cloud Expo, Nara Rajagopalan, CEO of Accelerite, explored the challenges in deploying, managing, and getting adoption for a private cloud within an enterprise. What are the key differences between wh...
For basic one-to-one voice or video calling solutions, WebRTC has proven to be a very powerful technology. Although WebRTC’s core functionality is to provide secure, real-time p2p media streaming, leveraging native platform features and server-side components brings up new communication capabilities for web and native mobile applications, allowing for advanced multi-user use cases such as video broadcasting, conferencing, and media recording.
SYS-CON Events announced today that Venafi, the Immune System for the Internet™ and the leading provider of Next Generation Trust Protection, will exhibit at @DevOpsSummit at 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. Venafi is the Immune System for the Internet™ that protects the foundation of all cybersecurity – cryptographic keys and digital certificates – so they can’t be misused by bad guys in attacks...
There will be new vendors providing applications, middleware, and connected devices to support the thriving IoT ecosystem. This essentially means that electronic device manufacturers will also be in the software business. Many will be new to building embedded software or robust software. This creates an increased importance on software quality, particularly within the Industrial Internet of Things where business-critical applications are becoming dependent on products controlled by software. Qua...
In addition to all the benefits, IoT is also bringing new kind of customer experience challenges - cars that unlock themselves, thermostats turning houses into saunas and baby video monitors broadcasting over the internet. This list can only increase because while IoT services should be intuitive and simple to use, the delivery ecosystem is a myriad of potential problems as IoT explodes complexity. So finding a performance issue is like finding the proverbial needle in the haystack.
Machine Learning helps make complex systems more efficient. By applying advanced Machine Learning techniques such as Cognitive Fingerprinting, wind project operators can utilize these tools to learn from collected data, detect regular patterns, and optimize their own operations. In his session at 18th Cloud Expo, Stuart Gillen, Director of Business Development at SparkCognition, discussed how research has demonstrated the value of Machine Learning in delivering next generation analytics to imp...
The 19th International Cloud Expo has announced that its Call for Papers is open. Cloud Expo, to be held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA, brings together Cloud Computing, Big Data, Internet of Things, DevOps, Digital Transformation, Microservices and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding business opportuni...
The Internet of Things will challenge the status quo of how IT and development organizations operate. Or will it? Certainly the fog layer of IoT requires special insights about data ontology, security and transactional integrity. But the developmental challenges are the same: People, Process and Platform. In his session at @ThingsExpo, Craig Sproule, CEO of Metavine, demonstrated how to move beyond today's coding paradigm and shared the must-have mindsets for removing complexity from the develo...
SYS-CON Events announced today that MangoApps will exhibit at the 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. MangoApps provides modern company intranets and team collaboration software, allowing workers to stay connected and productive from anywhere in the world and from any device.
Large scale deployments present unique planning challenges, system commissioning hurdles between IT and OT and demand careful system hand-off orchestration. In his session at @ThingsExpo, Jeff Smith, Senior Director and a founding member of Incenergy, will discuss some of the key tactics to ensure delivery success based on his experience of the last two years deploying Industrial IoT systems across four continents.
Basho Technologies has announced the latest release of Basho Riak TS, version 1.3. Riak TS is an enterprise-grade NoSQL database optimized for Internet of Things (IoT). The open source version enables developers to download the software for free and use it in production as well as make contributions to the code and develop applications around Riak TS. Enhancements to Riak TS make it quick, easy and cost-effective to spin up an instance to test new ideas and build IoT applications. In addition to...
Identity is in everything and customers are looking to their providers to ensure the security of their identities, transactions and data. With the increased reliance on cloud-based services, service providers must build security and trust into their offerings, adding value to customers and improving the user experience. Making identity, security and privacy easy for customers provides a unique advantage over the competition.
"We've discovered that after shows 80% if leads that people get, 80% of the conversations end up on the show floor, meaning people forget about it, people forget who they talk to, people forget that there are actual business opportunities to be had here so we try to help out and keep the conversations going," explained Jeff Mesnik, Founder and President of ContentMX, in this SYS-CON.tv interview at 18th Cloud Expo, held June 7-9, 2016, at the Javits Center in New York City, NY.
"There's a growing demand from users for things to be faster. When you think about all the transactions or interactions users will have with your product and everything that is between those transactions and interactions - what drives us at Catchpoint Systems is the idea to measure that and to analyze it," explained Leo Vasiliou, Director of Web Performance Engineering at Catchpoint Systems, in this SYS-CON.tv interview at 18th Cloud Expo, held June 7-9, 2016, at the Javits Center in New York Ci...
Internet of @ThingsExpo, taking place November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with the 19th International Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world and ThingsExpo Silicon Valley Call for Papers is now open.
I wanted to gather all of my Internet of Things (IOT) blogs into a single blog (that I could later use with my University of San Francisco (USF) Big Data “MBA” course). However as I started to pull these blogs together, I realized that my IOT discussion lacked a vision; it lacked an end point towards which an organization could drive their IOT envisioning, proof of value, app dev, data engineering and data science efforts. And I think that the IOT end point is really quite simple…
"My role is working with customers, helping them go through this digital transformation. I spend a lot of time talking to banks, big industries, manufacturers working through how they are integrating and transforming their IT platforms and moving them forward," explained William Morrish, General Manager Product Sales at Interoute, in this SYS-CON.tv interview at 18th Cloud Expo, held June 7-9, 2016, at the Javits Center in New York City, NY.
You think you know what’s in your data. But do you? Most organizations are now aware of the business intelligence represented by their data. Data science stands to take this to a level you never thought of – literally. The techniques of data science, when used with the capabilities of Big Data technologies, can make connections you had not yet imagined, helping you discover new insights and ask new questions of your data. In his session at @ThingsExpo, Sarbjit Sarkaria, data science team lead ...
Extracting business value from Internet of Things (IoT) data doesn’t happen overnight. There are several requirements that must be satisfied, including IoT device enablement, data analysis, real-time detection of complex events and automated orchestration of actions. Unfortunately, too many companies fall short in achieving their business goals by implementing incomplete solutions or not focusing on tangible use cases. In his general session at @ThingsExpo, Dave McCarthy, Director of Products...
WebRTC is bringing significant change to the communications landscape that will bridge the worlds of web and telephony, making the Internet the new standard for communications. Cloud9 took the road less traveled and used WebRTC to create a downloadable enterprise-grade communications platform that is changing the communication dynamic in the financial sector. In his session at @ThingsExpo, Leo Papadopoulos, CTO of Cloud9, discussed the importance of WebRTC and how it enables companies to focus...