Monday, September 30, 2013

[Java/Grails] Class ConstrainedProperty

org.codehaus.groovy.grails.validation

[Java/Grails] Class ConstrainedProperty

java.lang.Object
  org.codehaus.groovy.grails.validation.ConstrainedProperty 
 


Method Summary
void addMetaConstraint(java.lang.String name, java.lang.Object value)
Obtains the value of the named meta constraint.
void applyConstraint(java.lang.String constraintName, java.lang.Object constrainingValue)
Applies a constraint for the specified name and consraint value.
Constraint getAppliedConstraint(java.lang.String name)
@param constraintName The name of the constraint to check
java.util.Collection getAppliedConstraints()
Obtains an applied constraint by name.
java.util.Map getAttributes()
java.lang.String getFormat()
java.util.List getInList()
@return Returns the inList.
java.lang.String getMatches()
@return Returns the matches.
java.lang.Comparable getMax()
java.lang.Integer getMaxSize()
java.lang.Object getMetaConstraintValue(java.lang.String name)
java.lang.Comparable getMin()
@return Returns the min.
java.lang.Integer getMinSize()
@return Returns the minSize.
java.lang.Object getNotEqual()
@return Returns the notEqual.
int getOrder()
@param order The order to set.
java.lang.String getPropertyName()
@return Returns the propertyName.
java.lang.Class getPropertyType()
@return Returns the max.
groovy.lang.Range getRange()
@return Returns the range.
java.lang.Integer getScale()
@return The scale, if defined for this property; null, otherwise
groovy.lang.Range getSize()
@param size The size to set.
java.lang.String getWidget()
boolean hasAppliedConstraint(java.lang.String constraintName)
@return Returns the propertyType.
static boolean hasRegisteredConstraint(java.lang.String constraintName)
@return Returns the appliedConstraints.
boolean isBlank()
@return the blank.
boolean isCreditCard()
boolean isDisplay()
@return Returns the display.
boolean isEditable()
@param editable The editable to set.
boolean isEmail()
@return Returns the email.
boolean isNullable()
@return Returns the nullable.
boolean isPassword()
boolean isUrl()
static void registerNewConstraint(java.lang.String name, java.lang.Class constraintClass)
static void registerNewConstraint(java.lang.String name, ConstraintFactory factory)
static void removeConstraint(java.lang.String name, java.lang.Class constraintClass)
static void removeConstraint(java.lang.String name)
void setAttributes(java.util.Map attributes)
void setBlank(boolean blank)
void setCreditCard(boolean creditCard)
void setDisplay(boolean display)
@return Returns the editable.
void setEditable(boolean editable)
@return Returns the order.
void setEmail(boolean email)
void setFormat(java.lang.String format)
void setInList(java.util.List inList)
void setMatches(java.lang.String regex)
void setMax(java.lang.Comparable max)
@param max The max to set.
void setMaxSize(java.lang.Integer maxSize)
@param maxSize The maxSize to set.
void setMessageSource(org.springframework.context.MessageSource source)
void setMin(java.lang.Comparable min)
@param min The min to set.
void setMinSize(java.lang.Integer minSize)
@param minSize The minLength to set.
void setNotEqual(java.lang.Object notEqual)
@param notEqual The notEqual to set.
void setNullable(boolean nullable)
void setOrder(int order)
void setPassword(boolean password)
void setPropertyName(java.lang.String propertyName)
@return Returns the url.
void setRange(groovy.lang.Range range)
void setSize(groovy.lang.Range size)
void setUrl(boolean url)
void setWidget(java.lang.String widget)
boolean supportsContraint(java.lang.String constraintName)
Checks with this ConstraintedProperty instance supports applying the specified constraint.
java.lang.String toString()
void validate(java.lang.Object target, java.lang.Object propertyValue, org.springframework.validation.Errors errors)

Grails: how to get/set a meta-constraint on domain class property such as belongsTo or other variables

In the scaffolding templates there is a property domainClass from type org.codehaus.groovy.grails.commons.DefaultGrailsDomainClass. These object has the property constrainedProperties. To have access to any properties such in this example: 'readonly' you have to do this:

Your domain class:


class Contact {
   static belongsTo = [subscription: Subscription]

   static constraints = {
       subscription(nullable: false, attributes: [readonly: true])  
   }

   String description
}


The DefaultGrailsDomainClass has a constructor with a attribute from type Class maybe you can do this:


def domainClass = new DefaultGrailsDomainClass(Contact.class)
def ro = domainClass.constrainedProperties.subscription.attributes.readonly



def domainClass = new DefaultGrailsDomainClass(it.metaClass.getTheClass())
def constrainedProperties = domainClass.constrainedProperties;
if(constrainedProperties.containsKey("subscription")) {
    ConstrainedProperty v = (ConstrainedProperty) constrainedProperties.get("subscription");
    /**
     * Now check
     */
    if(v.isNullable()) {
        println "Nullable";
    }
    if(v.isBlank()) {
        println "Blank";
    }
    /**
     * There are may other constraints
     * http://grails.org/doc/latest/api/org/codehaus/groovy/grails/validation/ConstrainedProperty.html 
     * Java/Grails Class ConstrainedProperty
     */ 
 }

Monday, September 23, 2013

Groovy Check If Method or Property is Available

In Groovy we can easily see if a method or property is available for an object. We can use the respondsTo() and hasProperty() methods to see if the method or property can be invoked or accessed. We can not check for methods or properties which are added by overriding the methodMissing()/propertyMissing() or invokeMethod()/getProperty() methods.
Assume a service: TestService.groovy:

class TestService {
    String someProperty;
    def serviceMethod() {

    }

    def printString(String str) {
        println "String: " + str;
    }

    def printString(String str, Integer count, Integer map) {
        println "String: " + str;
    }
}

Now test if specific method existing:

TestService testService = new TestService();

println testService.metaClass.respondsTo(testService, "noMethodExists") ? "Exists: noMethodExists()" : "Not Exists: noMethodExists()";

println testService.metaClass.respondsTo(testService, "printString", String) ? "Exists: printString()" : "Not Exists: printString()";

ArrayList arrayList = new ArrayList();
arrayList.push(String);
arrayList.push(Integer);
def args = arrayList as Object[];
println (testService.metaClass.respondsTo(testService, "printString", args) ? "Exists: printString(String, Integer)" : "Not Exists: printString(String, Integer)");

arrayList = new ArrayList();
arrayList.push(String);
arrayList.push(Integer);
arrayList.push(Integer);
args = arrayList as Object[];
println (testService.metaClass.respondsTo(testService, "printString", args) ? "Exists: printString(String, Integer, Integer)" : "Not Exists: printString(String, Integer, Integer)");

And output will be as:

Not Exists: noMethodExists()
Exists: printString()
Not Exists: printString(String, Integer)
Exists: printString(String, Integer, Integer)

Now check specific property exists:

TestService testService = new TestService(); 

if(testService.metaClass.hasProperty(testService, "someProperty")) {
    println "Property: someProperty exists";
} else {
    println "Property: someProperty not exists";
} 
 
if(testService.metaClass.hasProperty(testService, "someName")) {
    println "Property: someName exists";
} else {
    println "Property: someName not exists";
}

And output will be as:

Property: someProperty exists
Property: someName not exists

Saturday, September 21, 2013

PHP Custom Error Handling

Creating a Custom Error Handler

Creating a custom error handler is quite simple. We simply create a special function that can be called when an error occurs in PHP.
This function must be able to handle a minimum of two parameters (error level and error message) but can accept up to five parameters (optionally: file, line-number, and the error context):

 Syntax

error_function(error_level,error_message,error_file,error_line,error_context)

ParameterDescription
error_levelRequired. Specifies the error report level for the user-defined error. Must be a value number. See table below for possible error report levels
error_messageRequired. Specifies the error message for the user-defined error
error_fileOptional. Specifies the filename in which the error occurred
error_lineOptional. Specifies the line number in which the error occurred
error_contextOptional. Specifies an array containing every variable, and their values, in use when the error occurred

Error Report levels

These error report levels are the different types of error the user-defined error handler can be used for:
ValueConstantDescription
2E_WARNINGNon-fatal run-time errors. Execution of the script is not halted
8E_NOTICERun-time notices. The script found something that might be an error, but could also happen when running a script normally
256E_USER_ERRORFatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error()
512E_USER_WARNINGNon-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error()
1024E_USER_NOTICEUser-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error()
4096E_RECOVERABLE_ERRORCatchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler())
8191E_ALLAll errors and warnings (E_STRICT became a part of E_ALL in PHP 5.4)

Now lets create a function to handle errors:



<?php
error_reporting(E_ALL);

function myErrorHandler($errorNo, $errorStr, $errFile, $errLine) {
    switch ($errorNo) {
        case E_USER_ERROR:
            echo '<BR>E_USER_ERROR';
            echo "<BR>Error no: ".$errorNo;
            echo "<BR>Error str: ".$errorStr;
            echo "<BR>Error file: ".$errFile;
            echo "<BR>Error line: ".$errLine;
            break;
        case E_WARNING:
        case E_USER_WARNING:
            echo '<BR>E_WARNING, E_USER_WARNING';
            echo "<BR>Error no: ".$errorNo;
            echo "<BR>Error str: ".$errorStr;
            echo "<BR>Error file: ".$errFile;
            echo "<BR>Error line: ".$errLine;
            break;
        case E_NOTICE:
        case E_USER_NOTICE:
            echo '<BR>E_NOTICE, E_USER_NOTICE';
            echo "<BR>Error no: ".$errorNo;
            echo "<BR>Error str: ".$errorStr;
            echo "<BR>Error file: ".$errFile;
            echo "<BR>Error line: ".$errLine;
            break;
        default :
            echo '<BR>default';
            echo "<BR>Error no: ".$errorNo;
            echo "<BR>Error str: ".$errorStr;
            echo "<BR>Error file: ".$errFile;
            echo "<BR>Error line: ".$errLine;
            break;
    }
    echo "<BR>";
    /* Don't execute PHP internal error handler */
    return true;
}
set_error_handler("myErrorHandler");

$x = $y + 3;

$f = fopen("a.txt", "r");
?>

And output would be like:

E_NOTICE, E_USER_NOTICE
Error no: 8
Error str: Undefined variable: y
Error file: C:\xampp\htdocs\index.php
Error line: 42

E_WARNING, E_USER_WARNING
Error no: 2
Error str: fopen(a.txt) [function.fopen]: failed to open stream: No such file or directory
Error file: C:\xampp\htdocs\index.php
Error line: 44

Friday, September 20, 2013

HTTP Status Codes Handling and Htaccess ErrorDocuments

Error handling using .htacces:

Here are some basic rule, use other rules if you need.

ErrorDocument 404 /Subtitle/php/error-msg.php
ErrorDocument 500 /location/php/error-msg.php
ErrorDocument 400 /location/php/error-msg.php
ErrorDocument 401 /location/php/error-msg.php
ErrorDocument 403 /location/php/error-msg.php

And the error-msg.php like this:

Here are some basic rule, use other rules if you need.

<?php
$HttpStatus = $_SERVER["REDIRECT_STATUS"] ;
  if($HttpStatus==200) {
      echo "Document has been processed and sent to you.";      
  } else if($HttpStatus==400) {
      echo "Bad HTTP request ";      
  } else if($HttpStatus==401) {
      echo "Unauthorized - Iinvalid password";      
  } else if($HttpStatus==403) {
      echo "Forbidden";      
  } else if($HttpStatus==500) {
      echo "Internal Server Error";      
  } else if($HttpStatus==418) {
      echo "I'm a teapot! - This is a real value, defined in 1998";      
  } else if($HttpStatus==404) {
      echo "Page not found here";      
  } else {
      $HttpStatus = 500;
      echo "Internal server Error";
  }
  echo "<BR>Status: ".$HttpStatus;
  exit; 
?>

Error Distribute from php file (named: mac_address.php)

If you need to show error like above one, please see below example php code:

<?php
/* UnCaught error handler */
set_exception_handler('exc_handler');

/* Error handler function */
function exc_handler(Exception $exception) {
    /* Set http status code such 404, 500 etc. */
    header("HTTP/1.1 ".$exception->getCode()." ".$exception->getMessage());
    /**
     * As 'REDIRECT_STATUS' is using in 'error-msg.php' file,
     * so we are providing this manually.
     * But it will automatically set when come from .htaccess
     */
    $_SERVER["REDIRECT_STATUS"] = $exception->getCode();
    /**
     * Including 'error-msg.php' file.
     */
    include './error-msg.php';
}
/**
 * Extentd 'Exception' to my own class 'NotFoundException'
 */
class NotFoundException extends Exception {
    public function NotFoundException($message = "Page not found") {
        throw new Exception($message, 404);
    }
}
/**
 * Throwing 'NotFoundException'
 */
//throw new NotFoundException();

/**
 * Another way to throw exception as bellow, where 
 * 'Server error' is the message and
 * '500' is the error code.
 */
throw new Exception("Server error", 500);
?>

Example output in browser (Custom 500 error using php code):

I wrote the code in mac_address.php to show 500 internal server error.














Example output in browser (404 error using .htaccess):

No file in that location named 'mac.php', .htaccess handling this internally.

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.