Anshul Sharma « Intelligrape Groovy & Grails Blogs
Subscribe via E-Mail:

anshul

http://www.intelligrape.com

Posts by anshul:

  • File Compression

    14 Feb 2011 in Grails

    Creating a zip file using AntBuilder.

            def ant = new AntBuilder()
            ant.zip(
                    destfile: destPath,
                    basedir: basePath,
                    includes: includeFiles, // Comma seperated file names
                    excludes: excludeFiles, // Comma seperated file names
                    level: 9     // maximum compression
            )
    For unzipping the file:

            def ant = new AntBuilder();
            ant.unzip(
    		src: srcPath,
                    dest: destDir,
                    overwrite: "true"
    	)

    Hope this helped!

    Cheers!

    Anshul Sharma

    • Share/Bookmark
  • Posting messages on facebook wall using graph api

    14 Dec 2010 in Grails

    Firstly ,you need to connect with facebook.

    Once you have facebook access token you can post messages on the facebook wall using the below code.

    void postMessage(String facebookAccessToken, String message, String facebookId)  {
                StringBuilder stringBuilder = new StringBuilder("access_token=");
                stringBuilder.append(URLEncoder.encode(facebookAccessToken, "UTF-8"));
                stringBuilder.append("&message=");
                stringBuilder.append(URLEncoder.encode(message, "UTF-8"));
                URL url = new URL("https://graph.facebook.com/${facebookId}/feed");
                HttpURLConnection connection
                try {
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setDoOutput(true);
                    connection.setRequestMethod("POST");
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    connection.setRequestProperty("Content-Length", "" + stringBuilder.toString().length());
                    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(connection.getOutputStream());
                    outputStreamWriter.write(stringBuilder.toString());
                    outputStreamWriter.flush();
                } finally {
                    connection?.disconnect()
                }
        }

    Hope this helped!

    Cheers!

    Anshul Sharma

    • Share/Bookmark
  • Integrate java application with Facebook using graph api.

    14 Nov 2010 in Groovy

    These are few basic steps which will help you to integrate your java application with facebook using facebook graph api.

    Steps :

    1) Register your application at http://www.facebook.com/developers/
    2) Facebook will return Consumer Key and Consumer Secret for your application.

    3) Create a login action:

    String facebookPermissions = FacebookPermissions

    // Login Action
    String callbackUrl = "ApplicationUrl/controller/action"
    String facebookAuthorizeUrl = "https://graph.facebook.com/oauth/authorize?client_id=FacebookApiKey&redirect_uri=callbackUrl&scope=facebookPermissions"  //             
    redirect(url: facebookAuthorizeUrl)

    4) Create a callback action .

    ///  Call back action: Where the facebook will redirect after succesful authentication.
     
    String authCode = parms.code
    String facebookTokenUrl = "https://graph.facebook.com/oauth/access_token?client_id=FacebookApiKey&client_secret=FacebookSecretKey&code=${authCode}&redirect_uri=callbackUrl&scope=facebookPermissions"            
    URL url = new URL(facebookTokenUrl)
    String response = url.text
    // Retrieve the access token from the response

    6) Persist the access token for future use. The access token never expire until the user explicitly rejects the application from his settings.

    Hope this helped!

    Cheers!

    Anshul Sharma

    • Share/Bookmark
  • Grails: execute sql script in Bootstrap

    14 Sep 2010 in Grails& Groovy

    This blog might help you to speed up your bootstrap process, especially when you need to populate records in tables.
    Earlier we used populate our database table by reading line by line from a CSV file and creating Domain Class object ad Save. But this was taking a huge time. And in our case, this data (more like a static information) was always same. So we came up with an idea – we took mysqldump for this particular table and saved it to our application’s web-app/data directory. Now the thing was, we just need to execute this “sql” file during bootstrap!

    Below is the example how to execute database dump files in bootstrap!

    import groovy.sql.Sql
    import org.codehaus.groovy.grails.commons.ConfigurationHolder as CH
     
    String sqlFilePath = ApplicationHolder.application.parentContext.servletContext.getRealPath("/data/table_dump.sql")
    String sqlString = new File(sqlFilePath).text
    Sql sql = Sql.newInstance(CH.config.dataSource.url, CH.config.dataSource.username,
    CH.config.dataSource.password, CH.config.dataSource.driverClassName)
    sql.execute(sqlString)

    Hope this helped!

    Cheers!
    Anshul Sharma

    • Share/Bookmark
  • Image comparison

    14 Aug 2010 in Grails& Groovy& Java tools

    In one of our projects, we need to compare images which comes from various sources and remove the duplicate one.

    The below algo helps us to remove the duplicate images.

     boolean compareImage(String firstPhotoUrl, String secondPhotoUrl) {
            boolean result = true;
            BufferedImage bi1 = ImageIO.read(new URL(firstPhotoUrl))
            BufferedImage bi2 = ImageIO.read(new URL(secondPhotoUrl))
            int size1 = bi1.getData().getDataBuffer().size;
            int size2 = bi2.getData().getDataBuffer().size;
            if ((size1 == size2) && (bi1.width == bi2.width) && (bi1.height == bi2.height)) {
                Raster r1 = bi1.getData();
                Raster r2 = bi2.getData();
                DataBuffer db1 = r1.getDataBuffer();
                DataBuffer db2 = r2.getDataBuffer();
                int size = db1.getSize();
                for (int i = 0; i < size; i++) {
                    int px1 = db1.getElem(i);
                    int px2 = db2.getElem(i);
                    if (px1 != px2) {
                        result = false;
                        break;
                    }
                }
            } else {
                result = false;
            }
        }
        return result;
    }

    Hope this helped!

    Cheers!
    Anshul Sharma

    • Share/Bookmark
  • Integrating Java Application with Twitter

    13 Jul 2010 in Grails

    These are few basic steps which will help you to integrate your java application with twitter using twitter4j.

    Twitter4J is a Java library for the Twitter API.
    With Twitter4J, you can easily integrate your Java application with the Twitter.

    Steps :

    1) Register your application at http://twitter.com/apps
    2) Twitter will return Consumer Key and Consumer Secret for your application.
    3) Download the twitter4j jar and place that jar file in the classpath.
    4) Create a login action:

    // Login Action
    Twitter twitter = new Twitter();
    twitter.setOAuthConsumer(ConsumerKey,ConsumerSecret);
    RequestToken requestToken = twitter.getOAuthRequestToken('callbackurl');
    String authUrl = requestToken.getAuthorizationURL(); 
    session.setAttribute("request-token",  requestToken);
    redirect(url: authUrl);

    5) Create a callback action .

    ///  Call back action: Where the twitter will redirect after successfull authentication.
    RequestToken requestToken = (RequestToken) session.getAttribute("request-token");
    String verifier = request.getParameter("oauth_verifier")
    AccessToken accessToken = twitter.getOAuthAccessToken(requestToken,verifier)

    6) Persist the access token and token secret for future use. (accessToken.token ,accessToken.tokenSecret). The access token never expire until the user explicitly rejects the application from his settings.

    7) Now whenever you want to create the twitter client , just follow the steps below:

    Twitter twitter = new Twitter()
    twitter.setOAuthConsumer(ConsumerKey, ConsumerSecret)
    twitter.setOAuthAccessToken(token, secretToken)  //  token, secretToken which you have persisted in step 6.
    // For Example: to search someone on twitter.
    List<User> users = twitter.searchUsers(name, 1)

    Hope this helped!

    Cheers!

    Anshul Sharma

    • Share/Bookmark
  • Implementing feedback functionality using uservoice.

    Hi,

    Recently in our project , we need to implement the feedback functionality.
    We implemented it using uservoice https://uservoice.com.

    Steps for implementing user’s feedback :
    1) Create the uservoice account https://uservoice.com/users/new
    2) On admin dashboard under the widget tab you will get a generated javascript.
    The format of the script will be as follows:

    <script type="text/javascript">
        var uservoiceOptions = {
            /* required */
            key: 'appName',
            host: 'appName.uservoice.com',
            forum: '',
            showTab: true,
            /* optional */
            alignment: 'left',
            background_color:'#f00',
            text_color: 'white',
            hover_color: '#06C',
            lang: 'en'
        };
     
        function _loadUserVoice() {
            var s = document.createElement('script');
            s.setAttribute('type', 'text/javascript');
            s.setAttribute('src', ("https:" == document.location.protocol ? "https://" : "http://") + "cdn.uservoice.com/javascripts/widgets/tab.js");
            document.getElementsByTagName('head')[0].appendChild(s);
        }
        _loadSuper = window.onload;
        window.onload = (typeof window.onload != 'function') ? _loadUserVoice : function() {
            _loadSuper();
            _loadUserVoice();
        };
    </script>

    3) Copy the generated javascript in your webpage where you wants to display the feedback button.

    Hope this will help you.

    Cheers!

    Anshul Sharma
    anshul@intelligrape.com

    • Share/Bookmark
  • Serializing objects to XML

    14 May 2010 in Grails& Groovy

    XStream is a simple Java library to serialize objects to XML and back again.
    Suppose we have a Person class as follows:

      public class Person {
      private String name
      private int age
      private Address address
    }
     
    public class Address {
      private String street
      private String city
      private String state
      private String country
    }

    The following code will convert instance to XML:

    XStream xstream = new XStream();   // instantiate the XStream class
    xstream.alias("person", Person.class);  //the alias will be the root node.
     
    Person personInstance = new Person()
    // populate the person object
     
    String xml = xstream.toXML(personInstance)

    XML will look like :

    <person>
      <name></name>
        <age></age>
        <address>
        	<street></street>
        	<city></city>
        	<state></state>
        	<country></country>
         </address>
     </person>

    To reconstruct an object, from the XML:

    Person person = (Person)xstream.fromXML(xml)

    Hope this helpled!

    Cheers!

    Anshul Sharma

    • Share/Bookmark