Tuesday, December 31, 2013

Hibernate/grails left join or inner join when using create criteria

Hibernate/grails left join or inner join or join when using create criteria. If you do not use
'CriteriaSpecification.LEFT_JOIN', then it would be a inner join. 
Here is the example as suppose 'User' belongsTo 'Role' which is nullable.
Now you want to left join 'Role' when creating criteria on 'User', then do 
the following. It would take all 'User' row where 'Role' is null or not.
But if you do not use 'CriteriaSpecification.LEFT_JOIN', then it would take only
'User.role' is not null. 


import org.hibernate.criterion.CriteriaSpecification;

List userList = User.createCriteria().list {
    eq("isActive", true);
    createAlias("role", "__role", CriteriaSpecification.LEFT_JOIN)
    eq("__role.someProperty", "some value");
}

Thursday, December 19, 2013

SOAP request in PHP with CURL

Php code to soap action via curl:


<?php
$xml = '<?xml version="1.0" encoding="utf-8"?>'.
    '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'.
    ' xmlns:xsd="http://www.w3.org/2001/XMLSchema"'.
    ' xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'.
        '<soap:Body>'.
            '<GetShirtInfo xmlns="http://api.soap.website.com/WSDL_SERVICE/">'.
                '<ItemId>15</ItemId>'.
            '</GetShirtInfo>'.
        '</soap:Body>'.
    '</soap:Envelope>';

$url = "https://api.soap.website.com/soap.asmx?wsdl";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

$headers = array();
array_push($headers, "Content-Type: text/xml; charset=utf-8");
array_push($headers, "Accept: text/xml");
array_push($headers, "Cache-Control: no-cache");
array_push($headers, "Pragma: no-cache");
array_push($headers, "SOAPAction: http://api.soap.website.com/WSDL_SERVICE/GetShirtInfo");
if($xml != null) {
    curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml");
    array_push($headers, "Content-Length: " . strlen($xml));
}
curl_setopt($ch, CURLOPT_USERPWD, "user_name:password"); /* If required */
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
?>

And output would be like this:


<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope
    xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <ShirtInfoResponse
            xmlns="http://api.soap.website.com/WSDL_SERVICE/">
            <ShirtInfo>
                <ItemId>15</ItemId>
                <ItemName>Some Item Name</ItemName>
                <ItemPrice>658.7</ItemPrice>
                <ItemCurrency>AUD</ItemCurrency>
            </ShirtInfo>
        </ShirtInfoResponse>
    </soap:Body>
</soap:Envelope>

Wednesday, December 18, 2013

Grails withNewSession


Please follow the following scenario:
1. You are saving a domain object 'User'.
2. You are trying to save another domain object 'Activities', indicates that 
   who is saving 'User'.
3. First, 'User' created, so now time to save 'Activities'.
4. But activities failed, what would be the saved user? 'User' would be roll 
   back even if 'Activities' saving between try catch, because of hibernate 
   session?
5. In this scenario you must save your 'Activities' under try catch with 
   'new session', such:

def saveUser = [
    User user = new User(name: "Pritom").save();
    try {
        Activites.withNewSession { sesstion -> 
            new Activities(createdBy: "some name").save();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

Grails access HttpSession from service or from other src files


import org.springframework.web.context.request.RequestContextHolder; 
HttpSession session = RequestContextHolder.currentRequestAttributes().getSession();

##### 
/* Code */
session.properties.each {
    println it;
}

/* Output from above code */
creationTime=1387331940863
maxInactiveInterval=1800
sessionContext=org.apache.catalina.session.StandardSessionContext@1ff04376
attributeNames=java.util.Collections$2@2aec16fa
class=class org.codehaus.groovy.grails.web.servlet.mvc.GrailsHttpSession
servletContext=org.apache.catalina.core.ApplicationContextFacade@3dc6e9f8
new=false
id=A2791167D1EC3D21025078895357147D
valueNames=[Ljava.lang.String;@71d88d19
lastAccessedTime=1387332146960

#####
/* Code */
session.attributeNames.each {
    println it;
}

/* Output from above code */
SETTING
org.codehaus.groovy.grails.FLASH_SCOPE
USER

#####
/* Code */
session.attributeNames.each {
    println session.getAttribute(it.toString());
}

/* Output from above code */
[paginationCount:10, generateClientID:On]
[:]
[name:Admin, id:1, username:admin, isSystemAdmin:true]

Friday, December 13, 2013

Convert string to ascii and ascii to string using JAVA

Java code to convert string to ascii code and ascii code to string back

Java Regex to convert string to ascii code and ascii code to string back



/**
 *
 * @author Pritom K Mondal
 */
public class AsciiString {
    public static void main(String[] args) {
        String inputString = "Hi, THAI(คุณ), HINDI:(तुम मेरी हो), HANGERIO:(تو مال منی), CHINA:(您), ARBI(أنت), FARSI(شما)";
        System.out.println("ORIGINAL:      " + inputString);
        String encoded = AsciiString.encode(inputString);
        System.out.println("ASCII ENCODED: " + encoded);
        String decoded = AsciiString.decode(encoded);
        System.out.println("ASCII DECODED: " + decoded);
    }
    
    public static String encode(String word) {
        String encoded = "";
        for(Integer index = 0; index < word.length(); index++) {
            int ascii = (int) word.charAt(index);
            Boolean keepAscii = true;
            if(ascii >= 48 && ascii <= 57) {
                keepAscii = false;
            }
            if(ascii >= 65 && ascii <= 90) {
                keepAscii = false;
            }
            if(ascii >= 97 && ascii <= 122) {
                keepAscii = false;
            }
            if(ascii == 32 || ascii == 43 || ascii == 45 || ascii == 46) {
                keepAscii = false;
            }
            if(keepAscii) {
                encoded += "&#" + ascii + ";";
            } else {
                encoded += word.charAt(index);
            }
        }
        return encoded;
    }
    
    public static String decode(String word) {
        String decoded = "";
        for(Integer index = 0; index < word.length(); index++) {
            String charAt = "" + word.charAt(index);
            if(charAt.equals("&") && index < word.length() && ("" + word.charAt(index + 1)).equals("#")) {
                try {
                    Integer length = word.indexOf(";", index);
                    String sub = word.substring(index + 2, length);
                    decoded += Character.toString((char) Integer.parseInt(sub));
                    index = length;
                } catch (Exception ex) {
                    decoded += charAt;
                }
            } else {
                decoded += charAt;
            }
        }
        return decoded;
    }
}

Output for the above program is as following:


ORIGINAL:      Hi, THAI(คุณ), HINDI:(तुम मेरी हो), HANGERIO:(تو مال منی), CHINA:(您), ARBI(أنت), FARSI(شما)
ASCII ENCODED: Hi&#44; THAI&#40;&#3588;&#3640;&#3603;&#41;&#44; HINDI&#58;&#40;&#2340;&#2369;&#2350; &#2350;&#2375;&#2352;&#2368; &#2361;&#2379;&#41;&#44; HANGERIO&#58;&#40;&#1578;&#1608; &#1605;&#1575;&#1604; &#1605;&#1606;&#1740;&#41;&#44; CHINA&#58;&#40;&#24744;&#41;&#44; ARBI&#40;&#1571;&#1606;&#1578;&#41;&#44; FARSI&#40;&#1588;&#1605;&#1575;&#41;
ASCII DECODED: Hi, THAI(คุณ), HINDI:(तुम मेरी हो), HANGERIO:(تو مال منی), CHINA:(您), ARBI(أنت), FARSI(شما)

Now create a html file named 'index.html' such:


<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <title>String and ASCII</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    </head>
    <body>
        <div>ORIGINAL:      Hi, THAI(คุณ), HINDI:(तुम मेरी हो), HANGERIO:(تو مال منی), CHINA:(您), ARBI(أنت), FARSI(شما)</div>
        <div>ASCII ENCODED: Hi&#44; THAI&#40;&#3588;&#3640;&#3603;&#41;&#44; HINDI&#58;&#40;&#2340;&#2369;&#2350; &#2350;&#2375;&#2352;&#2368; &#2361;&#2379;&#41;&#44; HANGERIO&#58;&#40;&#1578;&#1608; &#1605;&#1575;&#1604; &#1605;&#1606;&#1740;&#41;&#44; CHINA&#58;&#40;&#24744;&#41;&#44; ARBI&#40;&#1571;&#1606;&#1578;&#41;&#44; FARSI&#40;&#1588;&#1605;&#1575;&#41;</div>
        <div>ASCII DECODED: Hi, THAI(คุณ), HINDI:(तुम मेरी हो), HANGERIO:(تو مال منی), CHINA:(您), ARBI(أنت), FARSI(شما)</div>
    </body>
</html>

Now showing in browser:


In browser they are appearing same. Such original string, after ascii conversion and the back to again string. So why you convert them?
  • It is easy to maintain them.
  • Easy to insert to and get from database.
  • You have no worry about what characters are you inserting to database.
  • If you create xml from those data, you do not need to worry about what characters support in xml file, specially when you transport data via api server.

Thursday, December 12, 2013

Base64 encode/decode with JAVA

Java code to encode and decode base64


package pritom;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * Created with IntelliJ IDEA.
 * User: pritom
 * Date: 12/12/13
 * Time: 10:41 AM
 * To change this template use File | Settings | File Templates.
 */
public class EncodeDecodeBase64 {
    public static void main(String[] args) throws Exception{
        String baseString = "TESTING BASE 64 ENCODING AND DECODING WITH JAVA";
        System.out.println("Base string:     " + baseString);

        /**
         * Encoding to base 64
         */
        BASE64Encoder base64Encoder = new BASE64Encoder();
        String encodedString = base64Encoder.encodeBuffer(baseString.getBytes());
        System.out.print("Encoded base 64: " + encodedString);

        /**
         * Decoding from base 64
         */
        BASE64Decoder base64Decoder = new BASE64Decoder();
        String decodedString = new String(base64Decoder.decodeBuffer(encodedString), "UTF-8");
        System.out.println("Decoded base 64: " + decodedString);
    }
}

Output


Base string:     TESTING BASE 64 ENCODING AND DECODING WITH JAVA
Encoded base 64: VEVTVElORyBCQVNFIDY0IEVOQ09ESU5HIEFORCBERUNPRElORyBXSVRIIEpBVkE=
Decoded base 64: TESTING BASE 64 ENCODING AND DECODING WITH JAVA

Checking if an element is hidden with jQuery

Html

<form style='display: none'>
<input id='name' type='text' style='display: inline-block' />
</form>

jQuery code


if( $("input#name").is(":visible") ) {
    /* do something, selector is not hidden */
}

This will select the input field and then test correctly whether it is visible in the DOM. This check will make sure all parent elements are visible too, as well as the original CSS display attribute.