Thursday, September 19, 2013

Grails access something.properties settings under conf directory in BuildConfig.groovy

Create a file named 'config.properties' under conf direcotry with the following properties:

dataSource.driverClassName = com.mysql.jdbc.Driver
dataSource.username = root
tomcatVersion = 2.2.4 

Write the following code in 'BuildConfig.groovy' file:


def props = new Properties();
new File("grails-app/conf/config.properties").withReader {
    props.load(it);
}
def conf = new ConfigSlurper().parse(props);
println conf; 
println conf.dataSource.driverClassName;
println conf.dataSource.username;
println conf.tomcatVeriosn; 

And output will be as:


[dataSource:[driverClassName:com.mysql.jdbc.Driver, username:root], tomcatVersion: 2.2.4]
com.mysql.jdbc.Driver
root
2.2.4 

Then you can use this settings in your 'BuildConfig.groovy' files like this (highlighted yellow):


plugins {
    runtime ":hibernate:2.2.4"
    runtime ":jquery:1.8.3"
    runtime ":resources:1.2"

    // Uncomment these (or add new ones) to enable additional resources capabilities
    //runtime ":zipped-resources:1.0"
    //runtime ":cached-resources:1.0"
    //runtime ":yui-minify-resources:0.1.5"

    build ":tomcat:"+conf.tomcatVersion 
    /* OR USE */
    build ":tomcat:${conf.tomcatVersion}"
 
    runtime ":database-migration:1.3.2" 
    compile ':cache:1.0.1'
}

Grails Access Config.groovy settings in BuildConfig.groovy

Include the following lines in 'BuildConfig.groovy' file


def directory = new File(getClass().protectionDomain.codeSource.location.path).parent;
def config = new ConfigSlurper(grailsSettings.grailsEnv).parse(new File(directory + File.separator + "Config.groovy").toURI().toURL())
println "| Tomcat Version (API): " + config.grails.tomcat.version;

Include the following lines in 'Config.groovy'

grails.tomcat.version = "2.2.4"

Then when run the program it prints like:

| Tomcat Version (API): 2.2.4

Then you can use this settings in your 'BuildConfig.groovy' files like this (highlighted yellow):
plugins {
    runtime ":hibernate:2.2.4"
    runtime ":jquery:1.8.3"
    runtime ":resources:1.2"

    // Uncomment these (or add new ones) to enable additional resources capabilities
    //runtime ":zipped-resources:1.0"
    //runtime ":cached-resources:1.0"
    //runtime ":yui-minify-resources:0.1.5"

    build ":tomcat:"+config.grails.tomcat.version

    runtime ":database-migration:1.3.2"

    compile ':cache:1.0.1'
}

Wednesday, September 18, 2013

Java - String/Regex matches() for Starts With/Ends With/Contains Check

Parameter:

regex -- the regular expression to which this string is to be matched.

Return Value:

This method returns true if, and only if, this string matches the given regular expression. 

Example:


public class TestRegex {
    public static void main(String args[]){
        String Str = new String("Welcome to pritomkumar.blogspot.com");

        System.out.print("Contains 'pritom': " );
        System.out.println(Str.matches("(.*)pritom(.*)"));

        System.out.print("Starts with 'Welcome': " );
        System.out.println(Str.matches("Welcome(.*)"));

        System.out.print("Ends with '.com': " );
        System.out.println(Str.matches("(.*).com"));

        System.out.print("Starts with small characters: " );
        System.out.println(Str.matches("[a-z](.*)"));

        System.out.print("Starts with cap characters: " );
        System.out.println(Str.matches("[A-Z](.*)"));

        System.out.print("Starts with digits: " );
        System.out.println(Str.matches("[0-9](.*)"));
    }
} 
 

OUTPUT:

Contains 'pritom': true
Starts with 'Welcome': true
Ends with '.com': true
Starts with small characters: false
Starts with cap characters: true
Starts with digits: false 
 
Table 1.  Common matching symbols

Regular ExpressionDescription
.Matches any character
^regexregex must match at the beginning of the line
regex$Finds regex must match at the end of the line
[abc]Set definition, can match the letter a or b or c
[abc][vz]Set definition, can match a or b or c followed by either v or z
[^abc]When a "^" appears as the first character inside [] when it negates the pattern. This can match any character except a or b or c
[a-d1-7]Ranges, letter between a and d and figures from 1 to 7, will not match d1
X|ZFinds X or Z
XZFinds X directly followed by Z
$Checks if a line end follows


Table 2:  Meta-characters
Regular ExpressionDescription
\dAny digit, short for [0-9]
\DA non-digit, short for [^0-9]
\sA whitespace character, short for [ \t\n\x0b\r\f]
\SA non-whitespace character, for short for [^\s]
\wA word character, short for [a-zA-Z_0-9]
\WA non-word character [^\w]
\S+Several non-whitespace characters
\bMatches a word boundary. A word character is [a-zA-Z0-9_] and \b matches its bounderies.
Table 3: Quantifier
Regular ExpressionDescriptionExamples
*Occurs zero or more times, is short for {0,}X* - Finds no or several letter X, .* - any character sequence
+Occurs one or more times, is short for {1,}X+ - Finds one or several letter X
?Occurs no or one times, ? is short for {0,1}X? -Finds no or exactly one letter X
{X}Occurs X number of times, {} describes the order of the preceding liberal\d{3} - Three digits, .{10} - any character sequence of length 10
{X,Y}Occurs between X and Y times,\d{1,4}- \d must occur at least once and at a maximum of four
*?? after a quantifier makes it a reluctant quantifier, it tries to find the smallest match.

Tuesday, September 17, 2013

Build xml using java code from hashmap

Download XmlBuilder.java class

Follow the following link to parse all type of xml file to map/list


package xmlparser;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Pritom K Mondal
 * @created 28th August 2014
 */
public class XmlBuilder {
    private Map dataMap;
    private String xmlString = "";
    private static final String NEW_LINE = "\n";
    private static final String MATCHER_REPLACE = "[^0-9a-zA-Z:\\.]+";
    private static final String MATCHER_1 = "[a-zA-Z:\\_](.*)";
    
    public static void main(String[] args) {
        Map dataMap = new HashMap();
        for(int index = 1; index <= 2; index ++) {
            HashMap tempMap = new HashMap();
            tempMap.put("id", index);
            tempMap.put("name", "Name: " + index);
            tempMap.put("roll", "Roll: " + index);
            
            HashMap attMap = new HashMap();
            attMap.put("id", index * 10);
            attMap.put("attr-name", "Name == " + (index * 20));
            tempMap.put("<<attributes>>", attMap);  

            dataMap.put("user" + index, tempMap);
        }
        
        List dataList = new ArrayList();
        for (int index = 0; index < 2; index++) {
            HashMap tempMap = new HashMap();
            tempMap.put("id", index);
            tempMap.put("name", "Name: " + index);
            tempMap.put("roll", "Roll: " + index);

            dataList.add(tempMap);
        }
        dataMap.put("listMap", dataList);

        HashMap resultMap = new HashMap();
        resultMap.put("success", true);
        resultMap.put("message", "Thank you for generating this XML.");
        resultMap.put("dataMap", dataMap);
        resultMap.put("dataList", dataList);
        
        Map finalMap = new HashMap();
        finalMap.put("rootTag", resultMap);
        
        String xmlString = new XmlBuilder(finalMap).toXML();
        System.out.println(xmlString);
    }

    XmlBuilder(Map dataMap) {
        this.dataMap = dataMap;
    }

    public String toXML() {
        /*System.out.println(this.dataMap);*/
        this.renderMapAsXml(this.dataMap, "data", 0);
        /*System.out.println(this.xmlString);*/
        return this.xmlString;
    }
    
    private void renderListAsXml(List dataList, String wrapper, int cycle) {
        wrapper = wrapper.trim();
        if (!wrapper.matches(MATCHER_1)) {
            wrapper = "obj_" + wrapper;
        }
        for (int index = 0; index < dataList.size(); index++) {
            Object dataMapValue = dataList.get(index);
            if (dataMapValue instanceof List) {
                this.xmlString += this.makeTabSpace(cycle - 1) + "<" + wrapper + '>' + NEW_LINE;
                this.renderListAsXml((List) dataMapValue, wrapper, cycle + 1);
                this.xmlString += this.makeTabSpace(cycle - 1) + "</" + wrapper + '>' + NEW_LINE;
            }
            else if (dataMapValue instanceof Map || dataMapValue instanceof HashMap) {
                this.renderMapAsXml((Map) dataMapValue, wrapper, cycle);
                this.xmlString += NEW_LINE;
            }
            else {
                this.xmlString += this.makeTabSpace(cycle - 1) + "<" + wrapper + "><![CDATA[";
                this.xmlString += dataMapValue;
                this.xmlString += "]]></" + wrapper + '>' + NEW_LINE;
            }
        }
    }

    private void renderMapAsXml(Map dataMap, String wrapper, int cycle) {
        if (cycle == 0) {
            this.xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + NEW_LINE;
        }
        wrapper = "" + wrapper;
        wrapper = wrapper.trim();
        if (!wrapper.matches(MATCHER_1)) {
            wrapper = "obj_" + wrapper;
        }
        wrapper = wrapper.replaceAll(MATCHER_REPLACE, "_");
        if (cycle > 0) {
            this.xmlString += this.makeTabSpace(cycle - 1) + '<' + wrapper;
        }
        for (Object object : dataMap.entrySet()) {
            Map.Entry entry = (Map.Entry) object;
            Object dataMapKey = entry.getKey();
            Object dataMapValue = entry.getValue();
            if (dataMapKey.toString().equalsIgnoreCase("<<attributes>>")) {
                Map attributeMap = (Map) dataMapValue;
                for (Object objectAttribute : attributeMap.entrySet()) {
                    Map.Entry entryAttribute = (Map.Entry) objectAttribute;
                    this.xmlString += " " + entryAttribute.getKey() + "='" + entryAttribute.getValue() + "'";
                }
            }
        }
        if (cycle > 0) {
            this.xmlString += '>' + NEW_LINE;
        }
        int otherTags = 0;
        try {
            for (Object object : dataMap.entrySet()) {
                Map.Entry entry = (Map.Entry) object;
                Object dataMapKey = entry.getKey();
                Object dataMapValue = entry.getValue();

                if (!dataMapKey.toString().equalsIgnoreCase("<<attributes>>")) {
                    if (dataMapValue instanceof List) {
                        this.renderListAsXml((List) dataMapValue, "" + dataMapKey, cycle + 1);
                        otherTags++;
                    } 
                    else if (dataMapKey.toString().startsWith("<<")) {
                        this.xmlString = this.xmlString.substring(0, this.xmlString.length() - this.NEW_LINE.length());
                        this.xmlString += "<![CDATA[";
                        this.xmlString += dataMapValue + "]]>";
                    }
                    else if (dataMapValue instanceof Map || dataMapValue instanceof HashMap) {
                        this.renderMapAsXml((HashMap) dataMapValue, "" + dataMapKey, cycle + 1);
                        this.xmlString += NEW_LINE;
                        otherTags++;
                    }
                    else {
                        dataMapKey = "" + dataMapKey;
                        dataMapKey = dataMapKey.toString().trim();
                        if (!dataMapKey.toString().matches(MATCHER_1)) {
                            dataMapKey = "obj_" + dataMapKey;
                        }
                        dataMapKey = dataMapKey.toString().replaceAll(MATCHER_REPLACE, "_");
                        if (dataMapValue != null) {
                            dataMapValue = "" + dataMapValue;
                            dataMapValue = dataMapValue.toString().replaceAll("]]>", "]]&gt;");
                        }
                        this.xmlString += this.makeTabSpace(cycle);
                        this.xmlString += ('<' + dataMapKey.toString() + "><![CDATA[");
                        this.xmlString += dataMapValue + "]]></";
                        this.xmlString += dataMapKey.toString() + '>' + NEW_LINE;
                        otherTags++;
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (cycle > 0) {
            this.xmlString += this.makeTabSpace(otherTags == 0 ? otherTags : cycle - 1) + "</" + wrapper + ">";
        }
    }

    private String makeTabSpace(int numberOfTabs) {
        String returnString = "";
        for (int index = 1; index <= numberOfTabs; index ++) {
            returnString += "    ";
        }
        return returnString;
    }
}

Output would be as following:


<?xml version="1.0" encoding="UTF-8" ?>
<rootTag>
    <dataList>
        <id><![CDATA[0]]></id>
        <roll><![CDATA[Roll: 0]]></roll>
        <name><![CDATA[Name: 0]]></name>
    </dataList>
    <dataList>
        <id><![CDATA[1]]></id>
        <roll><![CDATA[Roll: 1]]></roll>
        <name><![CDATA[Name: 1]]></name>
    </dataList>
    <message><![CDATA[Thank you for generating this XML.]]></message>
    <dataMap>
        <user2 id='20' attr-name='Name == 40'>
            <id><![CDATA[2]]></id>
            <roll><![CDATA[Roll: 2]]></roll>
            <name><![CDATA[Name: 2]]></name>
        </user2>
        <user1 id='10' attr-name='Name == 20'>
            <id><![CDATA[1]]></id>
            <roll><![CDATA[Roll: 1]]></roll>
            <name><![CDATA[Name: 1]]></name>
        </user1>
        <listMap>
            <id><![CDATA[0]]></id>
            <roll><![CDATA[Roll: 0]]></roll>
            <name><![CDATA[Name: 0]]></name>
        </listMap>
        <listMap>
            <id><![CDATA[1]]></id>
            <roll><![CDATA[Roll: 1]]></roll>
            <name><![CDATA[Name: 1]]></name>
        </listMap>
    </dataMap>
    <success><![CDATA[true]]></success>
</rootTag>

Access Grails Application in BootStrap

Accessing the Grails application object in BootStrap.groovy is easy. 
We only have to define a variable named grailsApplication and Spring's 
name based injection takes care of everything.
 
class BootStrap {
    // Reference to Grails application.
    def grailsApplication

    def init = { servletContext ->
        // Access Grails application properties.
        grailsApplication.serviceClasses.each {
            println it 
        } 
    }

    def destroy = {}
}

Monday, September 16, 2013

Grails Controller allow Declarative Exception Handling with Filters

I guess you can handle declarative exception from Controllers but Filters. You can use response instead to send the error code
class AuthorizationFilters {
    def filters = {
        auth(controller: '*' /* or controller name */
            action: '*' /* or action name */, invert: true) {
            before = {
                HashMap map = new HashMap();
                map.put("success", false);
                map.put("message", "Error occurred"); 
                if(1){ //If auth fails
                    response.sendError(5000) /* Custom error code */
                    response.errorMessage = "Error message to error controller";
 
                    // OR 
                    //render(status: 403);
                    //render(contentType: "text/json", text: map.toJSON());
 
                    // OR 
                    //redirect(controller: 'error', action: 'errorDisplay');
                }
                return false
            }
        }
    }
}
Above logic will render the response from ErrorController's errorDisplay action based on the UrlMapping that is provided below.
Make sure you are excluding error controller from filters.

Make sure you have the entry in UrlMappings.groovy:
"5000"(controller: "error", action: "errorDisplay")

And ErrorController.groovy:
class ErrorController {
    def errorDisplay() {
        render(status: 500); /* Change error code to 500 from custom code: 5000 */
        render("Error: "+response.errorMessage);
        //response.errorMessage would be "Error message to error controller";
        return;
    }
}