Tuesday, October 1, 2013

Grails pagination on a ArrayList

In my recent grails project, i needed to paginate on an array list, so I wrote a function and thought would share it with you all.

public List getFilteredList(int max, int offset) {
    max = Math.min(max ?: 25, 100)
    offset = (offset && offset > 0) ?: 0

    List names = getNames() //Loads the complete list
    int total = names.size()
    int upperLimit = findUpperIndex(offset, max, total)
    List filteredNames = names.getAt(offset..upperLimit)
    return filteredNames
}

private static int findUpperIndex(int offset, int max, int total) {
    max = offset + max - 1
    if (max >= total) {
        max -= max - total + 1
    }
    return max
}
So now if offset=20 and max=10, total = 28 so this will generate a list from 21st to 28th elements of the main list.

Grails: get class object by string/class name

grailsApplication.classLoader.loadClass("au.com.test.package.ClassName")

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.