Vishal Sahu « Intelligrape Groovy & Grails Blogs
Subscribe via E-Mail:

Vishal Sahu

http://www.intelliGrape.com/

Software developer by profession , passionate about Groovy, Grails and Java/J2EE technologies and a great lover of Open Source.

Posts by Vishal Sahu:

  • Custom ‘Share’ button on Facebook wall post

    16 Jan 2012 in Grails

    Hi,
    In one of my Grails project, i needed to have Share feature on the messages/post published by our application on facebook wall.
    In Facebook, if the message/text published is simple text, then Share link appears on it, but if it contains any link/URL attached to it, then Facebook do not provides Share button on it.

    
    

    To implement it, i created my own Share button and thought it worth sharing.

    
    

    Publishing to facebook wall post requires facebook access_token and we have to do a post call to publish it on facebook wall.
    I am assuming that you already have the access_token, if not you can find how to get access_token from here

    
    

    Basic URL to share somthing on facebook wall is as below

    
        private static final String SHARE_BUTTON_BASIC_URL = "http://www.facebook.com/sharer.php?u="
        private static final String BUTTON_NAME = "Share This" // name to appear on the Share button
    

    To create our own ‘Share’ button, we have to oass the custom button parameters in ‘actions’ attribute of the post call.

    Code to publish message/post which contains any link attachment is as :-

          String message=  //Message to be published on facebook wall
          String access_token= // facebook access token
          String attachmentImageUrl= // Url of the image to be published in the wall post
          String attachmentLink= // Link attached with the message
    
           StringBuilder sb = new StringBuilder("access_token=");
            sb.append(URLEncoder.encode(access_token, "UTF-8"));
            sb.append("&message=");
            sb.append(URLEncoder.encode(message, "UTF-8"));
            sb.append("&picture=");
            sb.append(URLEncoder.encode(attachmentImageUrl, "UTF-8"));
            sb.append("&link=");
            sb.append(URLEncoder.encode(attachmentLink, "UTF-8"));
            sb.append("&actions=")
            sb.append(URLEncoder.encode("[{name: '${BUTTON_NAME}', link: '${SHARE_BUTTON_BASIC_URL}${attachmentLink}' }]", "UTF-8"));
    
                URL url = new URL('https://graph.facebook.com/feed');
                HttpURLConnection connection
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connection.setRequestProperty("Content-Length", "" + sb.toString().length());
                OutputStreamWriter outputStreamWriter = new OutputStreamWriter(connection.getOutputStream());
                outputStreamWriter.write(sb.toString());
                outputStreamWriter.flush();
                connection?.disconnect()
    

    So, whatever we provide in the ‘actions’ property of post call, will appear in the wall post with the defined action. Here we are using it as link to Share a facebook wall post.

    
    

    Sample post with custom ‘Share This’ link on facebook Wall

    
    
    
    

    This worked in my case.
    Hope it helps.

    Cheers!!!

    Vishal Sahu
    vishal@intelligrape.com
    www.intelligrape.com
    http://www.linkedin.com/in/vishalsahu

    • Share/Bookmark
  • Way to check if user has “Liked” the Facebook Fan Page or Not

    22 Dec 2011 in Grails

    Hi,
    In my recent grails project, i was working on creating Apps for Facebook Fan Page and needed to show data to the user in such a way so that if he/she has “Liked” the page, then the content would be different from the case when the user has not liked it.

    
    

    In simple words, if user is Fan of any Facebook Page, then the content of App Tab would be different from the user who is not Fan of that Page.

    
    

    I searched a lot about it, and came across various solutions suggesting using JavaScript way to handle it but they didn’t worked for me, because although the User is logged in the facebook, but has not authorized the App and hence, we cannot fetch user_id of that user from facebook session.

    
    

    The only way i left with is to fetch the User status from the signed_request served in the params. This is the easiest way i got, to check whether User has ‘Liked’ the page or not, on server side.

    
    

    A signed_request is passed in params to the application URL registered in App on Facebook when they are loaded into the Facebook environment. It is of the form of long sequence of string concatenation of a HMAC SHA-256 signature string, a period (.), and a base64url encoded JSON object.

    
    

    Code to decode signed_request

    
            String signedRequest= SIGNED_REQUEST_OBTAINED_IN_PARAMS
            boolean hasLikedPage = false
            String payload = signedRequest.split("[.]", 2)[1]
            payload = payload.replace("-", "+").replace("_", "/").trim()
            String jsonString = new String(Base64.decodeBase64(payload.getBytes()))
    

    The above code will gives a string containing all the data in the signed_request(as in below example).
    Example:

    {
       "algorithm":"HMAC- SHA256",
        "expires":1324555200,
        "issued_at":1324551348,
        "oauth_token":"some-random-string-of-oauth-token",
        "page": {
                "id":"XXXXXXXXXXX594",
                 "liked":true, // field to decide if user has "Liked" the fan page or not
                 "admin":false
              },
        "user":{
                "country":"in",
                "locale":"en_US",
                "age":{
                         "min":21
                        }
                  },
        "user_id":"XXXXXXX3285"
    }
    

    With the above JSON, we can see if the user has “Liked” the Fan Page or Not.

    
    

    This worked for me.
    Hope it helps

    
    

    Cheers!!
    Vishal Sahu
    vishal@intelligrape.com
    http://www.intelligrape.com
    http://www.linkedin.com/in/vishalsahu

    • Share/Bookmark
  • Detecting mobile browsers in Javascript

    Hi,

    In my recent grails project, i was working on mobile version of the application and needed to redirect users to the mobile version of our application, if they are accessing the application from any mobile device. I looked at various techniques/codes to detect mobile device and redirect users to the specific URL.

    
    

    I encountered a simplest piece of code which worked in my case and thought it worth sharing.

    
    

    Just put this code in the head section of you web page and it will redirect it to the specified URL if the device is mobile browser.

    Code is:

    <script type="text/javascript">
    
    if (screen.width <= 699) {
    document.location = "http://www.example.com/mobile-version.html";
    }
    
    </script>
    
    
    

    References:-
    http://css-tricks.com/snippets/javascript/redirect-mobile-devices
    http://www.ianfernando.com/2011/how-to-redirect-mobile-traffic-to-a-mobile-friendly-page/
    http://www.warriorforum.com/offline-marketing-discussions/376351-redirection-script-mobile-site.html

    
    

    This worked for me.
    Hope it helps.

    
    

    Cheers!!!
    Vishal Sahu
    vishal@intelligrape.com
    http://www.intelligrape.com

    • Share/Bookmark
  • Install Apps on Facebook Fan page using API

    18 Dec 2011 in Grails& Groovy

    Hi,
    In my current grails project, we are using Facebooks Apps for our application so that any user who wish to use that app, can attach it with his/her Facebook Fan Page manually by visiting the App Profile Page and then adding it to the Fan Page. Then the attached facebook app can fetch data from our project.

    
    

    But few days ago, Facebook announced that it is Removing App Profile Pages.
    Now for adding facebook apps to fan page, we can either Create an Profile page for app or Add the app to Fan page using API.

    
    

    I implemented the feature to attach any Facebook App to Facebook Fan page using API and thought it worth sharing.

    
    

    I am assuming that you already have the Facebook Page Access Token with you, if not you can see how to Integrate facebook with web application and get access token here.

    
    

    Get App Id from Facebook App page:-

    
    

    To attach any Facebook Fan page, we need to issue an HTTP POST request to the facebook URL.
    URL for POST request

    URL :  https://graph.facebook.com/${FACEBOOK_PAGE_ID}/tabs
    

    Values we will be requiring :

    
    String FAN_PAGE_ACCESS_TOKEN = fan page access token.
    String APP_ID = app id from the registered app.
    String FACEBOOK_PAGE_ID = id of the facebook page to which app is to be attached.
    

    Code to issue post request at the given URL:

    
            StringBuilder sb = new StringBuilder("access_token=");
            sb.append(URLEncoder.encode(FAN_PAGE_ACCESS_TOKEN, "UTF-8"));
            sb.append("&app_id=");
            sb.append(URLEncoder.encode(APP_ID, "UTF-8"));
    
            URL url = new URL("https://graph.facebook.com/${FACEBOOK_PAGE_ID}/tabs");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            String publishedPostId
            try {
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connection.setRequestProperty("Content-Length", "" + sb.toString().length());
                OutputStreamWriter outputStreamWriter = new OutputStreamWriter(connection.getOutputStream());
                outputStreamWriter.write(sb.toString());
                outputStreamWriter.flush();
                log.debug("Response code ${connection.responseCode} , Message : ${connection.responseMessage}")
                if (connection.responseCode != 200) {
                    log.debug("Unable to attach app to facebook fan page")
                }
            } finally {
                connection?.disconnect()
            }
    
    
    

    So, we can attach any Facebook App to the Facebook Fan Page using the above code.

    
    

    This worked for me.
    Hope it helps.

    
    

    Cheers !!!
    Vishal Sahu
    vishal@intelligrape.com
    http://www.linkedin.com/in/vishalsahu
    http://www.intelligrape.com

    • Share/Bookmark
  • Integrating Google plus in grails application

    In my current project, i needed to integrate Google+ in the application using server-side API. Google uses OAuth2.0 protocol for authorization when our application tries to access the data. All we require is an access token to fetch data from Google using REST calls which serves data in JSON format.

    I implemented it using Web Server Applications API and thought it worth sharing.

    
    

    There are basically 3 steps to fetch data from Google.

    
    

    1. Register an application.

    We need to register an application at Google API Console. Go to the Google console page using the link provided and create an aplication.

    
    

    Steps involve in registering an application are:-

    
    

    a.) Create project by providing name to the project.

    
    

    
    

    b.) Turn ON the service required, in our case it is Google Plus API.

    
    

    
    

    c.) Create a Oauth 2.0 Client ID.

    
    

    
    

    d.) Create the OAuth 2.0 ClientId and provide the callback URL where google will send the authorization token.

    
    

    
    

    e.) Note down Client ID and Client Secret as generated in the above step.

    
    

    
    

    2. Obtain an Access Token from the Google Authorization Server.

    
    

    Obtaining an access token involves 2 steps.

    
    

    a.) Request for Authorization Code.

    
    

    In this step, we will request the Google server for authorization code by providing registered application client ID in the URL to Google server.

    I created an action to redirect to Goolge, when someone want to connect to google plus.

    String CLIENT_ID =client_id_obtained from registered app
    String CALLBACK_URL = callback_url_as_mentioned in the registered app.
    String GOOGLE_PLUS_SCOPE='https://www.googleapis.com/auth/plus.me'    // scope is the permissions we are requesting.
    
    
    

    Action code is as:

    def registerOnGooglePlus = {
    String authorizeUrl = "https://accounts.google.com/o/oauth2/auth?scope=${GOOGLE_PLUS_SCOPE}&
    redirect_uri=${CALLBACK_URL}&response_type=code&client_id=${CLIENT_ID}&access_type=offline"
    URL urlForGooglePlus = new URL(authorizeUrl)
    redirect(url: urlForGooglePlus)
    }
    

    The Redirect will take user to permissions page, if the user is already logged-in or will take to login page and then permissions page.

    After approving the required permissions, user will redirect back to the application’s registered Callback URL with the authorization code.

    
    

    
    

    b.) Request for Access Token with the authorization code obtained from the above action.

    
    

    Access Token can be received by a POST request using the Client Secret and authorization code received.

    The POST call requires 5 properties to be send in the body of the request in the encoded form.

    
    	code : The authorization code returned from the initial request
    	client_id : The client_id obtained during application registration
    	client_secret : The client secret obtained during application registration
    	redirect_uri : The URI registered with the application
    	grant_type : authorization_code
    
    
    // Sample action to receive authorization code
    
    def callBack={
    StringBuilder sb = new StringBuilder("code=");
    sb.append(URLEncoder.encode(code, "UTF-8"));
    sb.append("&client_id=");
    sb.append(URLEncoder.encode(clientId, "UTF-8"));
    sb.append("&client_secret=");
    sb.append(URLEncoder.encode(clientSecret, "UTF-8"));
    sb.append("&redirect_uri=");
    sb.append(URLEncoder.encode(callbackUrl, "UTF-8"));
    sb.append("&grant_type=");
    sb.append(URLEncoder.encode('authorization_code', "UTF-8"));
    
    String URL_TO_REQUEST_TOKEN= 'https://accounts.google.com/o/oauth2/token'
    
    URL url = new URL(URL_TO_REQUEST_TOKEN);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    try {
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    connection.setRequestProperty("Content-Length", "" + sb.toString().length());
    connection.setRequestProperty("Host", "accounts.google.com");
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(connection.getOutputStream());
    outputStreamWriter.write(sb.toString());
    outputStreamWriter.flush();
    log.debug("Response code ${connection.responseCode} , Message : ${connection.responseMessage}")
    String resultData = connection.content.text
    def responseJson = JSON.parse(resultData)
    String ACCESS_TOKEN = responseJson?.access_token
    }
    catch (Exception e) {
    e.printStackTrace()
    }
    }
    
    
    

    3. Calling Google API.

    Now, with the help of access token, we can call google API to fetch Data by appending the access token in the GET request.

    Example:

    
    

    To fetch person’s profile data

    GET :  https://www.googleapis.com/oauth2/v1/userinfo?access_token=ACCESS_TOKEN
    
    
    

    To get list of profile acitivties

     GET :  https://www.googleapis.com/plus/v1/people//activities/public?access_token=ACCESS_TOKEN
    
    
    

    References:-
    http://code.google.com/apis/accounts/docs/OAuth2WebServer.html

    http://code.google.com/apis/accounts/docs/OAuth2.html

    
    

    Hope this helps..!!!

    
    

    Vishal Sahu
    vishal[at]intelligrape[dot]com
    www.intelligrape.com

    • Share/Bookmark
  • Setting System property from command line in grails

    24 Aug 2011 in Grails& Java tools& Linux& System

    Hi,

    In one of my recent grails project, i needed to set System property from command line while running the grails application.
    I looked for it and found a simple solution to do so and found it worth sharing.


    Suppose we want to set any property, say app.property=”propertyValue”, then the command to set the property in grails application would be:

      grails  -Dapp.property="propertyValue" run-app
    

    Similarly to retrieve the value of System property, we use

    String myPropertyValue= System.getProperty("app.property")
    

    It helped me a lot..
    Hope it helps


    Vishal Sahu
    vishal@intelligrape.com
    www.intelligrape.com

    • Share/Bookmark
  • Generating EAN-8 standard barcode using Barcode4J

    14 Apr 2011 in Grails& Groovy& Java tools& System

    Hi,

    In one of my project i needed to generate EAN-8 standard bar-code for identifying the various products. I searched for various libraries available for generating bar-code and found a library to do so. The library i used for generating the bar-code is Barcode4J.
    You can download it from here

    Barcode4J is a flexible generator for barcodes written in Java. It’s free, available under the Apache License, version 2.0.
    The bar-code generated with the help of of this library uses eight digit number hence EAN-8.

    To generate bar-code image from this library is quite simple. Just put the barcode4j.jar in the lib folder of the application.

    
    

    Code to generate image is:-

    public File generateBarcode(Long codeDigits){
    try {
          //'codeDigits' is the code for which we want to generate bar-code image
         EAN8Bean bean = new EAN8Bean();
         final int dpi = 150;
         bean.setModuleWidth(UnitConv.in2mm(1.0f / dpi));
         bean.setFontSize(2.0)
         bean.doQuietZone(true)
         File outputFile = new File(filepath) // existing file in the file system
         OutputStream out = new FileOutputStream(outputFile)
    
         // class to convert provided image into barcode image
         BitmapCanvasProvider canvas = new BitmapCanvasProvider(out, "image/jpeg", dpi,   BufferedImage.TYPE_BYTE_BINARY, false, 0)
         bean.generateBarcode(canvas, codeDigits)
         canvas.finish()
         return outputFile
    }
    

    So, here it takes a file from the file system and convert it into the required barcode image. Now, the user can simply display this image on the items.

    In my case, i needed to generate a bar-code image for each product, so i create new file for every item, and stored it on the file system with unique name.

    This works in my case.
    Hope it helps

    
    

    Cheers..!!!
    Vishal Sahu
    vishal@intelligrape.com

    • Share/Bookmark
  • Paypal Integration : Auto redirecting to application after processing payment

    15 Mar 2011 in Grails& Groovy& Java tools

    Hi,

    In my recent grails project, i needed to return back to the application after processing payment at the paypal website. I searched a lot about it. Then i found the solution to do so and thought it worth sharing.

    Here are the steps i followed:-

    1. The Paypal button:-
    This is the code for putting the paypal button in any web-page

    Here:
    The email of merchant’s account or the seller account, the account to which payment is to be made and the email by which the account is registered is given in the hidden field “business”.

    
    

    The URL to which we want application to return after processing payment is provided in the hidden field with the name “return” i.e.

    
    

    This completes the application side implementation for paypal.

    2. Paypal Account Configuration
    Now we have to configure the Merchant’s account to Auto-redirect to the provided URL after processing the payment.

    Steps to configure account are:-

    1. Log in to Paypal Account
    2. Click the Profile Link in sub-menu of My Account.


    3. Under “Selling Preferences” click ‘Website Payment Preferences’ link.

    4. Select the Auto-Return radio button to enable the auto return feature.

    This enables the auto-redirect feature in the paypal account.

    This worked for me.
    Hope it helps.

    Vishal Sahu
    vishal@intelligrape.com

    • Share/Bookmark
  • Converting date from one timezone to another in groovy

    09 Feb 2011 in Grails& Groovy& Java tools& System

    Hi,
    In my recent grails project, i came across the situation where i needed to convert the date in given timezone to the date in another timezone. I searched a lot about it and got many solutions for this problem and then i came out with a simple way to do so.

    Lets i have a date in TimeZone say oldTimeZone and i want to convert it to another timeZone say newTimeZone, so to convert it to another timezone, i wrote the method given below.

    
    public Date convertToNewTimeZone(Date date, TimeZone oldTimeZone, TimeZone newTimeZone){
    
          long oldDateinMilliSeconds=date.time - oldtimeZone.rawOffset
          // oldtimeZone.rawOffset returns the difference(in milliSeconds) of time in that timezone with the time in GMT
          // date.time returns the milliseconds of the date
    
          Date dateInGMT=new Date(oldDateinMilliSeconds)
    
          long convertedDateInMilliSeconds = dateInGMT.time + newTimeZone.rawOffset
          Date convertedDate = new Date(convertedDateInMilliSeconds)
    
        return convertedDate
    }
    

    This Works for me.
    Hope it helps.

    Cheers..!!!
    Vishal Sahu
    vishal@intelligrape.com
    www.intelligrape.com

    • Share/Bookmark
  • JQuery script to put focus on first field of any page

    Hi,

    In my recent grails project, i needed to put focus on the first field of any page whenever the page loads. The requirement is such that if the page contains errors then the focus should be on the first input field which has errors.

    I searched a lot and with the help of my colleague we came out with a simple JQuery script to put focus on the first input field on any page whenever the page loads.

    The script i used is:-

    
       if (jQuery('.errors').size() > 0) {
           jQuery('input.errors:first').focus();
           jQuery('.errors input:visible:first').focus();
         }
       else {
          jQuery('input:text:visible:first').focus();
        }
    

    I put it in the layout and it works for every gsp which has that layout.

    It worked for me.
    Hope it Helps.

    Vishal Sahu
    vishal@intelligrape.com
    www.intelligrape.com

    • Share/Bookmark