java « Intelligrape Groovy & Grails Blogs

Posts Tagged ‘ java ’

Getting property class from property name

Posted by on September 26th, 2012

Recently in one of my project i had a requirement of identifying the class of a property of an object with object class and property name and then determining whether it’s an Enum class or not. I found an easy solution for this using Reflection API. Using Java Reflection you can inspect the fields (member variables) of classes. This is done via the Java class java.lang.reflect.Field and calling geType() on this Field object gives the class of  that property.


class Utils {

public static def getClass(Class objectClass, String propertyName) {

def propertyClass = null

try {

propertyClass = objectClass.getDeclaredField(propertyName)?.type

}

catch (NoSuchFieldException ex){

log.error("No such property exist in this object class&"+objectClass)

}

return propertyClass

}

}

//Checking enum class or not

Utils.getClass(object.class,"someFieldName")?.isEnum()

There is one more benefit. One can also check whether particular property exists in a class or not as getDeclaredField throws NoSuchFieldException if there is no such property with given name in the object class.

(more…)

Posted in Grails, Groovy

How to implement AOP Profiling in Grails application

Posted by on September 25th, 2012

In one of my recent project, i want to profile method execution time. I have used Spring AOP to profile method execution time.

It’s very easy to implement AOP profiling in grails

1. Suppose we have below mentioned service class, we want to log execution time of method saveDataStudent,saveDataUpdated methods in service class. We need to write aspect for it.

package com.service

import com.test.Student
class StudentService {
    Student saveDataStudent(Student student) throws Exception{
        return student.save(flush: true,failOnError: true)
    }

    Student saveDataUpdated(Student student){
        return student.save(flush: true,failOnError: true)
    }
}

2. Use following aspect code for profiling.

package com.spring3.base.test

import org.aspectj.lang.JoinPoint
import org.aspectj.lang.ProceedingJoinPoint
import org.springframework.stereotype.Component
import org.springframework.util.StopWatch
import org.aspectj.lang.annotation.*

@Aspect
@Component
class LoggerInterceptor {

     @Around("execution(* saveData*(..))")
    public Object profileSaveMethod(ProceedingJoinPoint call) throws Throwable {
        StopWatch clock = new StopWatch("Profiling:::::" + call.signature + ":::::Args::::::" + call.args
        );
        try {
            clock.start(call.toShortString());
            return call.proceed();
        } finally {
            clock.stop();
            System.out.println(clock.prettyPrint());
        }
    }

}

@Around(“execution(* saveData*(..))”) : It represents that this advice will execute for those methods whose name is starting with saveData.

Hope this code will help you :)

To know more about AOP, you can take the reference from following links:

http://www.intelligrape.com/blog/2012/08/27/integrating-of-spring-aop-with-grails-application/
http://static.springsource.org/spring/docs/2.5.5/reference/aop.html

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

Posted in Grails

Normalization Forms for Accented Characters in java

Posted by on June 29th, 2012

Text Normalization is the process of “standardizing” text to a certain form, so as to enable, searching, indexing and other types of analytical processing on it. Often working with large quantities of text we encounter character with accents like é , â etc. Unicode provides multiple ways to create such characters . For example we can have é created using Unicode sequence \u00E9 (composite character) or we can create it using a combination of e + acute accent. that would be (e + \u0301).
Now the é created would look same in both the representations and would also mean the same thing, but for a java program they are actually not the same characters so the é created using the two methods are actually not equal for your program. Clearly we need to normalize these two different representations to a fixed standard.

And its here, that java.text.Normalizer class comes to our rescue. All we need to do is normalize things to a normalization form out of these 4 :

  1. NFC – Canonical Decomposition, followed by Canonical Composition.
  2. NFD – Canonical Decomposition
  3. NFKC – Compatibility Decomposition, followed by Canonical Composition
  4. NFKD – Compatibility Decomposition



Canonical Decomposition means, taking a character and decomposing it into its component characters



Compatibility decomposition means taking a character and decomposing it by compatibility and arranging them in specific order


Canonical Composition means recomposing characters based on their canonical equivalence.


Canonical equivalence further means that characters have the same appearance and meaning when printed or displayed.


To Fully summarize this in an example,

Consider, the Angstrom sign “Å”, (U+212B) and  the Swedish letter “Å” (U+00C5), both are expanded by NFD (or NFKD) into “A” and “°” (U+0041 and U+030A) which is then reduced by NFC (or NFKC) to the Swedish letter “Å” (U+00C5)  (Swedish Letter “Å” is canonically equivalent to Angstrom sign “Å” as they are printed and displayed as exactly same, though they are different).

Now we know how we can normalize unicode characters to a standard form wherever required.



Sachin Anand

@babasachinanand

sachin[at]intelligrape[dot]com

Posted in Java tools

How to configure SSL on Tomcat server and run Grails/Java application on HTTPS

Posted by on June 29th, 2012

To run your Java/Grails application on SSL, firstly you need to configure the Tomcat server.

Here in this example I will show how to configure Tomcat instance and run Grails/Java application.

For SSL/HTTPS:

  1. We need .keystore file. You can generate it by using command“keytool -genkey”. Run this command on linux terminal or window cmd, follow the instructions. Fill the desire information and it will generate the .keystore file on following path: Linux: /home/[user]/.keystore file Window: /Documents and Settings/[user]/.keystore
  2. One thing you would have to remember is the password that is used while generating the .keystore file because this password will be used in configuring Tomcat server instance
  3. After the generation of .keystore file, copy .keystore file to webapp of tomcat directory.
  4. Then open server.xml of Tomcat from conf/server.xml and uncomment ssl port connector which is like

<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150"  scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" keystoreFile="webapps/.keystore"
keystorePass="password-of-.keystore-file" />

Add following line keystoreFile=”webapps/.keystore” & keystorePass=”password-of-.keystore-file

Here keystoreFile is the location of .keystore file, and keystorePass is the password which initially used for creating .keystore file.


5. Now SSL has been configured on Tomcat

6. Now configure your web application as SSL enabled. If you are working on Java application,  add the following lines in web.xml file of your web-application

<security-constraint>
		<web-resource-collection>
			<http-method>GET</http-method>
			<http-method>POST</http-method>
			<url-pattern>/*</url-pattern>
		</web-resource-collection>

  		<user-data-constraint>
      		<transport-guarantee>CONFIDENTIAL</transport-guarantee>
   		 </user-data-constraint>
  	</security-constraint>

If you are working on grails application,you need to run following command to generate the web.xml file because grails framework does not contain any web.xml file and web.xml file automatically generated when you are creating war file

Run following command to get web.xml file in your grails application


grails install-templates


web.xml file will be generated on the following location of your grails application /src/templates/war/web.xml

Then add above mentioned snippet in web.xml, create the war file and deploy on tomcat server. Now your application will successfully run on SSL. You can access your application using following url: https://localhost:8443/<application-name>


Reference:-

http://www.intelligrape.com/blog/2012/05/31/set-up-ssl-communication-between-two-server-using-keytool-command/

http://www.intelligrape.com/blog/2012/06/01/how-to-set-up-ssl-certificates-on-your-server/

http://java.dzone.com/articles/setting-ssl-tomcat-5-minutes


Mohit Garg

mohit@intelligrape.com

    If you are working on grails application,you need to run following command to generate the web.xml file because grails framework does not contain any web.xml file and web.xml file automatically generated when you are creating war file

    Run following command to get web.xml file in your grails application

grails install-templates

    web.xml file generated on following location of your grails application /src/templates/war/web.xml

    Then add above mention snipplet in web.xml, create the war file and deploy on tomcat server.

    Now your application will successfully run on SSL

Access your application using following url’s:

https://localhost:8443/application-name

Reference:- http://java.dzone.com/articles/setting-ssl-tomcat-5-minutes

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

Posted in Grails

Set-up SSL Communication between two Linux servers Using Keytool Command

Posted by on May 31st, 2012

In one of my project, My front end application runs on one server and back end application runs on another. Both application have to communicate with each other through SSL(Secure Sockets Layer). SSL is a way to secure internet communication from your browser to a secure website. The websites using SSL will have https:// to their name.

In comes the Java keytool command, which is a key and certificate management utility. Keytool is a java security tool, which is used to create and manage public keys,private keys,and security certificate. It manages a keystore (database) of cryptographic keys, X.509 certificate chains, and trusted certificates.

Using the Java keytool command you can add the certicate into your keystore as trusted certificate.

Following are the steps to perform https communication between two application on different servers:
1. Copy server1-site.crt file to Server 2.
2. Now, Import this root or intermediate CA certificate to an existing Java keystore, using the command:
    Default keystore password is changeit

keytool -import -trustcacerts -keystore cacerts -storepass YOUR_KEYSTORE_PASSWORD -noprompt -alias webAppCertificate -file www.web-app.mydomain.com.crt

3. Restart apache by issuing command: /etc/init.d/apache2 restart OR apache2ctl restart
4. Repeat, Steps 1 to 3 on server1 with server2-site.crt file.

Using the keytool command you can add , delete ,list certificate from your keystore.

Refrence: http://www.sslshopper.com/article-most-common-java-keytool-keystore-commands.html

Hope it Helps!

Regards,
Gautam Malhotra
gautam@intelligrape.com

Posted in Linux, System

Dealing with immutable collections in Java

Posted by on April 11th, 2012

Perhaps, you know it before or just skipped it after going through Java API. But I really found it very helpful at this point.

 

Recently, I had a requirement in an open-source project, where users can iterate through the objects saved in collections (esp. List). But the problem was, we really didn’t want users to directly or indirectly update those collection objects. Or in other words, we wanted to provide them collections with Read-Only behavior.

 

So to fulfill this requirement, I had few solutions -
1) Writing a wrapper class for iterating the objects in collection, in a manner that it behaves like Immutable collection objects.
2) Implementing your own Collection classes to support read-only behavior.
3) Returning the output as Iterable.
4) And many more – as complicated as we want to make it.

 

Well, need not to worry guys!
Java provides an in-built class “java.util.Collections – to deal with such kind of problems.

Collections class comes up with a good list of static methods. Like, for converting a modifiable list to unmodifiable list (read-only list), we have following method:

List myUnmodifiableList = Collections.unmodifiableList(myModifiableList)

and now, if anyone will try to modify ‘myUnmodifiableList’, it will throw UnsupportedOperationException.
Similarly, there are other methods to handle different types of collections.

 

I hope this might help someone.

 

Please put your comment, if there’s any better way out there.

 

Cheers!
Salil Kalia
Salil [at] IntelliGrape [dot] com
Twitter LinkedIn

Posted in Grails, Groovy

Grails: Dynamically create instance of a POGO class

Posted by on June 15th, 2011

Hi guys,

Recently on a project, I was creating a number of command objects to accept incoming parameters from a POST call from an iPhone with which I needed to sync data. I created a parent class for all command object classes to accept the common properties and created individual command object classes to accept any additional parameters.

The use case was that the name of the command object class was being created dynamically from the URL. Now, when I was trying to create a new instance of a command object in a controller using the following code, I got a ClassNotFoundException to my utter surprise:

DefaultGrailsApplication grailsApplication = ApplicationHolder.application.mainContext.getBean("grailsApplication")
def clazz = grailsApplication.getClassForName("com.intelligrape.co.sync.SyncCO").newInstance()

So I tried going through the Java style of fetching a class instance as follows:

def clazz = Class.forName("com.intelligrape.co.sync.SyncCO").newInstance()

Needless to say, I ran into the same problem again. After a lot of searching on the Internet and headbanging, I realized that classes in the src/groovy or src/java are not available to the grails class loader and they are loaded by the URLClassLoader which is a subclass of Java’s ClassLoader. Along with Uday’s help and a nabble post, I realized that I needed to use the three parameter Class.forName() method to create a new instance of a POGO or a POJO.

I ended up using the following syntax which worked for me in this case:

def clazz = Class.forName("com.intelligrape.co.sync.SyncCO", true, Thread.currentThread().getContextClassLoader()).newInstance()

The above code gets a reference of the current executing thread’s root class loader to fetch an instance of all classes loaded in the current executing application. Documentation for the method is located here: Class.forName()

I hope this helps any lost soul who has tried and failed at creating a new instance of a POGO.

Cheers
Roni C Thomas
roni[at]intelligrape[dot]com
@ronicthomas

Tags: , ,
Posted in Grails

Groovy: Sort list of objects on the basis of more than one field

Posted by on January 25th, 2011

Usually, when we deal with databases, we don’t face such kind of situation because we query database to get result-set in required order.

But let’s say you have a List of objects that you want to sort on the basis of two fields. Let’s discuss it with an example.


I have a list of Tasks (with date and priority fields). I want to sort these tasks ordered by Date and priority-wise (as second level sorting).

Here, I gonna use Expando class, so I can directly run this in my groovyConsole. But definitely you can use some ‘Task’ class.

Expando a = new Expando(date: Date.parse('yyyy-MM-dd','2011-01-01'), priority:1)
Expando b = new Expando(date: Date.parse('yyyy-MM-dd','2011-01-01'), priority:2)
Expando c = new Expando(date: Date.parse('yyyy-MM-dd','2011-01-02'), priority:1)
Expando d = new Expando(date: Date.parse('yyyy-MM-dd','2011-01-01'), priority:3)

def list = [a,d,c,b]

If sorting was required on the basis of date only, it was very simple.

list.sort(it.date)

But as per our requirements – order by date (first level sorting) and priority (second level sorting). We can do something like following.

list.sort{x,y->
  if(x.date == y.date){
    x.priority <=> y.priority
  }else{
    x.date <=> y.date
  }
}

Well, there could be some better way. If you know please put your comments. But it worked well in my case.



Cheers!
Salil Kalia
Salil [at] IntelliGrape [dot] com
Twitter LinkedIn

Encode Content to MD5 Using GROOVY or GRAILS – with Webhook example

Posted by on November 12th, 2010

Recently I was working on webhooks (which are getting quite popular for sending notifications to other applications using HTTP POST methods). MD5 encoded content is heavily used in webhooks for security concern.

My purpose of writing this blog is neither to explain MD5 nor webhooks. But just to show you -
1. a quicker way in Java/Groovy/Grails – How to encode a String (or Content) using MD5 algorithm.
2. Receive Webhook request (containing MD5 encoded certificate)

      // Below is the content (received in http post request body)
      String contentRecievedInRequest = "StringcontentneedtobeverifiedbaseduponMD5algorithm"
      // Below is your secret key - this is not in request - but something that you and trust-party know only)
      String yourSecretKey = "kfkdjfxx8r7kdf" 
      // Now Mix your secret key with the content received in http post request
      String claimedContent = "StringcontentneedtobeverifiedbaseduponMD5algorithmkfkdjfxx8r7kdf"
      // following is usually a hexa value - find in the same http-request-header
      String certificate = '3df5786adfe37430d8a8d72cb9e7fe56c'

Now, what we need to do here is – Encode claimedContent as MD5.

1. Using Groovy/Java

        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(claimedContent.getBytes());
        BigInteger hash = new BigInteger(1, md5.digest());
        String hashFromContent = hash.toString(16);

2. Using Grails (Single line solution)

        String hashFromContent = claimedContent.encodeAsMD5();

Now what ? Just see if encoded content matches with the certificate received in request-header. If it matches that means it’s valid request (not hacked one).

        if(hashFromContent == certificate){
            println "GOOD REQUEST -- Content Verified"
        }else{
            println "BAD REQUEST"
        }

I hope it might help you somewhere.

Salil Kalia
salil [at] intelligrape [dot] com

Posted in Grails, Groovy