Groovy « Intelligrape Groovy & Grails Blogs

Posts Tagged ‘ Groovy ’

Using Ftp with Grails

Posted by on April 4th, 2013

In one of my Grails project I need to drop files over ftp server. Using JSch one can easily transfer files over sftp. Just follow the below steps.
1. Add the below dependency to Grails project “grails-app/conf/BuildConfig.groovy” file

dependencies {
        compile 'com.jcraft:jsch:0.1.49'
    }

2. Create a class for adding ftp credentials information. e.g. “FtpCredentail”

class FtpCredential {

    String server
    String username
    String password
    String remoteBaseDir
    Integer port
}

3. Create a service named “FtpService” and add the following code into it

import com.jcraft.jsch.Channel
import com.jcraft.jsch.ChannelSftp
import com.jcraft.jsch.JSch
import com.jcraft.jsch.Session

class FtpService {
    def grailsApplication

    static transactional = true

    def save(InputStream inputStream, String fileName, FtpCredential ftpCredential) {
        connect(ftpCredential) { ChannelSftp sftp ->
            sftp.put inputStream, fileName
        }
    }

    def load(String fileName, FtpCredential ftpCredential) {
        connect(ftpCredential, { ChannelSftp sftp ->
            File outputFile = File.createTempFile(fileName,'')
            outputFile?.newOutputStream() << sftp.get(fileName)
            outputFile
        }, false)
    }

    def delete(String fileName, FtpCredential ftpCredential) throws Throwable {
        connect(ftpCredential) { ChannelSftp sftp ->
            sftp.rm fileName
        }
    }

    def makeDir(String directoryName, FtpCredential ftpCredential) {
        connect(ftpCredential) { ChannelSftp sftp ->
            sftp.mkdir directoryName
        }
    }

    private def connect(FtpCredential ftpCredential, Closure c, boolean disconnectOnFinish = true) {
        Session session = null
        ChannelSftp sftp = null
        try {
            JSch jSch = new JSch()
            session = jSch.getSession username, ftpCredential?.server, ftpCredential?.port
            session.setConfig "StrictHostKeyChecking", "no"
            File keyFile = new File("${grailsApplication.config.pathToKeyFile}")
            if (ftpCredential?.password) {
                session.password = ftpCredential?.password
            } else {
                jSch.addIdentity(keyFile?.absolutePath)
            }
            session.connect()
            Channel sFtpChannel = session.openChannel "sftp"
            sFtpChannel.connect()
            sftp = sFtpChannel as ChannelSftp
            sftp.cd ftpCredential?.remoteBaseDir
            c.call sftp
        } catch (Exception ex) {
            ex.printStackTrace()
        } finally {
            if (disconnectOnFinish) {
                sftp?.exit()
                session?.disconnect()
            }
        }
    }
}

Note: In the above code at line number 44.

File keyFile = new File("${grailsApplication.config.pathToKeyFile}")

The code looks for private key provided by ftp server for password-less log in. One should define the property named “pathToKeyFile” in “grails-app/conf/Config.groovy” with value equals to the path of key file.

Now you are ready to use the newly created FtpService service methods. Such as:

  1. save(inputStream, fileName, ftpCredential) for saving file over ftp.
  2. load(fileName, ftpCredential) for getting file from ftp.
  3. delete(fileName, ftpCredential) for deleting file over ftp.
  4. makeDir(directoryName, ftpCredential) for creating directory over ftp.

Example

For saving file over ftp one can use FtpService save method as shown below

 File file = File.createTempFile("temp","txt")
 FtpCredential ftpCredential = new FtpCredential(server: <server>, username: <username>, password: <password>, port: <server_port>, remoteBaseDir: <remote_base_directory>)
 InputStream inputStream = new BufferedInputStream(new FileInputStream(file))
 ftpService.save(inputStream, "fileNameToBeSavedOverFTPServer", ftpCredential)

Please share your feedback and suggestions.


Click here to read more JSch examples »



Puneet Behl
puneet.behl@intelligrape.com
https://twitter.com/puneetbhl
http://in.linkedin.com/in/puneetbhl

Posted in Grails

Regular Expression – Slides Uploaded on SlideShare

Posted by on October 31st, 2012

Hi Guys,

 

I took a session on Regular Expressions in the company, i have shared my slide on slideshare. You can see it here :
http://www.slideshare.net/rajdgreat007/regular-expressions-14971247

 

I have discussed following topics in that slide :

  1. What are regular expressions
  2. Need for regular expressions
  3. Basic rules
  4. Regular expression groups
  5. search()
  6. match()
  7. replace()

 

I have thrown light on some practical examples in which we can use regular expressions. Hope you will like it.

 

Regards
Raj Gupta

Posted in Groovy

@Canonical annotation

Posted by on September 27th, 2012

@Canonical: It’s very useful annotation. It provides the combination of features of @ToString (default implementation of toString() method based upon the fields in the class), @EqualsAndHashCode(default implementation of equals() and hashCode() method of the class based upon the fields in the class) and @TupleConstructor (provides the classical constructor with default properties).

import groovy.transform.Canonical

@Canonical
class Person {
String name
String address
String city

}

Person person = new Person(name:"Mohit Garg",address:"Address",city: "city")
Person person1 = new Person("Mohit Garg","Address","city")

println("Check two objects are equal:::"+(person.equals(person1)))  // Both objects will be equal because of same hashCode. (Output:true)

println("person object:::"+person) //Output:Person(Mohit Garg, Address, city)

Hope this will help you :)

Thanks & Regards,
Mohit Garg
mohit@intelligrape.com
@gargmohit143

Posted in Groovy

Cool way to get/set processed HTML Markup in filters

Posted by on September 27th, 2012

Hi,

 

There was a case where i had to encrypt the HTML output of the GSP before displaying it to user. There are a lot of ways to do it, but i wanted to make is as simple as possible. Hence here is the pattern i used:

 

Note: This is just an example, you can use this concept to do thousands of cool things, like: pdf export etc..

 

ON THE GSP

<html>
<head>
<meta name="encrypt" value="true" />   
    ...
</head>
 .... misc code
</html>

Here what is did is, i created a GSP and just added a meta property to it saying “encrypt true”.

 

Now here is the Code for the Grails Filters (See inline comments)

def filters = {
        all(controller: '*', action: '*') {
            before = {                
            }
            after = { Map model ->
                try {
                    //Get the Site Mesh Page Instance
                    GSPSitemeshPage sitemeshPage = response?.getContent() as GSPSitemeshPage
                   
                    //Check if it is actual sitemest page, not just plain rendered content
                    if (sitemeshPage && sitemeshPage.getPage()) {
                        //Get the meta property value.
                        String metaPropValue = sitemeshPage.getProperty("meta.encrypt")
                        if (metaPropValue && metaPropValue == "true") {
                            //This is how you can get html contents of head/body after all tags resolved.
                            String head = new String(sitemeshPage.getHead())
                            String body = new String(sitemeshPage.getBody())

                            //Buffer for new body
                            StreamCharBuffer writer = new StreamCharBuffer()
                            //Write to buffer new content
                            writer.getWriter().write(encryptionService.encrypt(body))
                            sitemeshPage.setBodyBuffer(writer)
                        }
                    }
                } catch (Throwable ex) {
                    ex.printStackTrace()
                }
            }
            afterView = { Exception e ->

            }
        }
    }

 

And hence we have this processed content in response :)

 

 

Regards
Kushal Likhi

Posted in Grails

Groovy: Overriding “Plus” operator in a class with interesting example

Posted by on September 26th, 2012

Have you ever wondered how to overload “plus” operator in Groovy ? It is as easy as adding toppings to your favourite pizza. Let me explain. Let us taka a class for Pizza:

 

@ToString
class Pizza {
    String name
    List<Topping> toppings
    double price

}

And another for the Topping:

@ToString
class Topping {
    String name
    double price
}

Now to add toppings to the favourite pizza, let us overload the plus operator in Pizza class like this:

//Method with name "plus" will override the "+" operator. It will return a new pizza with the Toppings added.
    Pizza plus(Topping topping) {
        new Pizza(name: name, toppings: toppings + [topping], price: price + topping.price)
    }

Let us order a pizza:

Pizza pizza = new Pizza(name: "Veg Extravaganza Pizza", price: 323.32, toppings: [])

And our favourite toppings as well:

Topping cheeseBurst = new Topping(name: "cheese Burst", price: 80)
Topping extraCheese = new Topping(name: "Extra Cheese", price: 40.43)
Topping jalepenos = new Topping(name: "Jallepenos", price: 50.33)
Topping capsicum = new Topping(name: "capsicum", price: 20.32)

Can’t wait to add them all:

Pizza specialPizza = pizza + cheeseBurst + extraCheese + jalepenos + capsicum

Let us unbox our pizza:

println (specialPizza)
//OUTPUT
/*

Pizza(Veg Extravaganza Pizza, [Topping(cheese Burst, 80.0), Topping(Extra Cheese, 40.43), Topping(Jallepenos, 50.33), Topping(capsicum, 20.32)], 514.4)
*/

Isn’t it mouth watering.

Hope this helps.

 

Imran Mir
imran[at]intelligrape.com

Posted in Grails, Groovy

FindResults and FindResult Methods of Groovy

Posted by on September 26th, 2012

In almost all the applications that we work on, we have to transform elements of a collection in one way or the other. We can do it in different ways.

Let there be a domain “Employee” with following attributes:

class Employee{
String firstName
String lastName
Double salary
}

And we have 5 Employees:

Employee employee1 = new Employee(firstName:"John", lastName:"Doe", salary:10000)
Employee employee2 = new Employee(firstName:"Tim", lastName:"Kerry", salary:20000)
Employee employee3 = new Employee(firstName:"Kim", lastName:"Terry", salary:30000)
Employee employee4 = new Employee(firstName:"Mary", lastName:"Jin", salary:40000)
Employee employee5 = new Employee(firstName:"James", lastName:"Sally", salary:50000)

If we want full name of all the employees having salary greater than 25000.
If we use collect in following way:

println Employee.list().collect{it.salary>25000?(firstName+' '+lastName):null}
//The gives [null,null,Kim Terry,Mary Jin,James Sally]

The problem with collect is that the size of transformed list is equal to the original list even if the transformed element is null. So we need to have an additional
step to get non-null elements from the transformed list.

Instead of this, we can simply use findResults in following way:

println Employee.list().findResults{it.salary>25000?(firstName+' '+lastName):null}
//This gives a list of size equal to total non-null elements(3 in this case) : [Kim Terry,Mary Jin,James Sally].

Further if we want to get just the first non-null element after transformation, we can use findResult instead of findResults.

println Employee.list().findResult{it.salary>25000?(firstName+' '+lastName):null}
//This gives "Kim Terry".

I found it very useful.

Hope it heps you too,:)

Vivek Sachdeva

Posted in Grails

Using Inject method in Groovy 2.0

Posted by on September 26th, 2012

A very useful enhanced method in Groovy 2.0 is inject method whose key purpose is to pass the outcome of first iteration to next iteration and keep on passing till all the elements of collections are processed.

Lets start with an example, consider a class Employee with name and salary as attributes:

class Employee{
     String name
     Float salary
}

Employee emp1 = new Employee(name:"Divya",salary:50000)
Employee emp2 = new Employee(name:"Priya",salary:30000)
Employee emp3 = new Employee(name:"Ginny",salary:60000)
Employee emp4 = new Employee(name:"Shreya",salary:80000)
Employee emp5 = new Employee(name:"Heena",salary:10000)

List<Employee> employees = [emp1,emp2,emp3,emp4,emp5]

And if we have to find out sum of salaries of those employees whose salary is greater than 40000, then most cleaner way of doing the same is using the inject method which also prevent us to define a new variable for doing the same.

Float totalSalaryOfUsers = employees*.salary.inject{accumulator,currentValue-> accumulator  + (currentValue > 40000 ? currentValue : 0) }

println totalSalaryOfUsers

// Output : 190000.0

In previous version of Groovy(<2.0), there was need to initialize the inject method with a value, but in Groovy 2.0, inject method initializes itself with the first element of collection.

Consider one more example of inject method for clear understanding, i.e. ,converting list to String is:

List<String> thought = ["Don't","put","off","till","tomorrow","what","you","can","do","today"]

String strThought = thought.inject{accumulator,currentValue-> accumulator + " " + currentValue }

println strThought

// Output: Don't put off till tomorrow what you can do today

Posted in Groovy

@Log annotation

Posted by on September 26th, 2012

@Log : This annotation provides the log object in groovy class. By using it you don’t need to create the Logger object, it automatically provides log object.

Example:

import groovy.util.logging.Log

@Log
class Person {
    String name
    String address
    String city

    public void logDetails(){
        log.info("Name:::${name}--->Address ::: ${address}---> city :::${city}")
    }
}

new Person(name:"Mohit Garg",address:"Address",city: "city").logDetails()

It logs the details of the person object.

Hope this will help you :)

Thanks & Regards,
Mohit Garg
mohit@intelligrape.com
@gargmohit143

Posted in Groovy

TupleConstructor annotation in Groovy

Posted by on September 25th, 2012

@TupleConstructor annotation provides the classical constructor with default properties. It will create the constructor with first parameter as address, second parameter as name etc. Constructor implementation depends upon the order of the variable declaration. One thing you need to ensure that you need to pass the value in same order as used in variable declaration.

Here is the example:

import groovy.transform.TupleConstructor
@TupleConstructor
class Person {
    String address
    String name
    String city
    int age
}

Person person1 = new Person('ADDD','MOHIT','CITY',1)

println("name:::"+person1.name)
println("adreess:::"+person1.address)
println("city:::"+person1.city)
println("age:::"+person1.age)

Hope this code will help you :)

Thanks & Regards,
Mohit Garg
mohit@intelligrape.com
@gargmohit143

Tags:
Posted in Groovy

Static Type Checking in Groovy 2.0

Posted by on September 25th, 2012

Groovy is a dynamic language. We can’t check any typo error, method or property missing error at compile time. To check typo error, method or  property missing at compile time, Groovy 2.0 introduces new features named as Static Type Checking which helps to check errors at compile time.

To use static type checker in groovy
You have to write @TypeChecked annotation above the method. It enables method to check errors at compile time.

import groovy.transform.TypeChecked

void findData() {}

@TypeChecked
int testData() {
    // compilation error:
    // cannot find matching method findssssData()
    findssssData()

    def name = "Hello"

    // compilation error:
    // the variable naaammme is undeclared
    println naaammme

// compilation error
// cannot return string value if method return type is integer
return "hello"
}

This code will give the errors at compile time for method missing (findssssData), variable missing (variable name) and invalid return type.

You can use static type checking in following case:

  1. To check the return type of any method
  2. Assignment type checking
  3. Method missing
  4. Variable missing

To know more about static type checking, you can use following links:-

http://www.infoq.com/articles/new-groovy-20

http://www.infoq.com/news/2011/11/groovy-updates

http://docs.codehaus.org/display/GroovyJSR/GEP+8+-+Static+type+checking

Thanks & Regards,
Mohit Garg
mohit@intelligrape.com
@gargmohit143

Tags:
Posted in Grails