Monday, January 13, 2014

Html5 & jQuery form validation and get all error at a time


Html code


<form method='post'>
    <ul class="errorMessages"></ul>
    <div class="one">
        <label for="name">Name:</label>
        <input id="name" type="text" required="required"/>
    </div>
    <div class="two">
        <label for="comments">Comments:</label>
        <textarea id="comments" required="required"></textarea>
    </div>
    <div class="three">
        <label for="roll">Name:</label>
        <input id="roll" type="text" required="required"/>
    </div>
    <div class="four">
        <label for="email">Email:</label>
        <input id="email" type="email" required="required"/>
    </div>
    <div class="five">
        <label>Group:</label>
        <input type='radio' name='group' required="required"/> Group 1
        <input type='radio' name='group' required="required"/> Group 2
        <input type='radio' name='group' required="required"/> Group 3
    </div>
    <div class="buttons">
        <button type="submit" class="submit">Submit</button>
        <button type="button">Check</button>
    </div>
</form>

jQuery code


var createAllErrors = function() {
    var form = $( this ), errorList = $( "ul.errorMessages", form);
    var showAllErrorMessages = function() {
        errorList.empty();
        
        // Find all invalid fields within the form.
        var invalidFields = form.find( ":invalid" ).each( function( index, node ) {
            // Find the field's corresponding label
            var label = $( "label[for=" + node.id + "] ").html();
            if(label === undefined) {
                label = "";
            }
            // Opera incorrectly does not fill the validationMessage property.
            var message = node.validationMessage || 'Invalid value.';
            errorList.append( "<li><span>" + label + "</span> " + message + "</li>" );
        });
        errorList.show();
        return errorList.find("li").size();
    };

    form.find("button[type='button']").click(function() {
        var errorLength = showAllErrorMessages();
        errorList.show().prepend( "<li><span>Total Errors: </span> " + errorLength + "</li>" );
        form.find( "button.submit").click();
    });
    
    // Support Safari
    form.on( "submit", function( event ) {
        if ( this.checkValidity && !this.checkValidity() ) {
            $( this ).find( ":invalid" ).first().focus();
            event.preventDefault();
        }
    });
};
$( "form" ).each( createAllErrors );

Sunday, January 12, 2014

Using php download a temporary file


<?php
$dataArray = array(
    "name" => "Pritom K Mondal",
    "company" => "Some Company"
);
$tmpName = tempnam(sys_get_temp_dir(), 'data');

$tmpFile = fopen($tmpName, 'w');
fputcsv($tmpFile, $dataArray);

header('Content-Description: File Transfer');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename=download.csv');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($tmpName));

ob_clean();
flush();
readfile($tmpName);
unlink($tmpName);
?>

Saturday, January 11, 2014

Using java copy array using copyOf

byte[] src = {1, 2, 3, 4};
byte[] dst = Arrays.copyOf(src, src.length);
System.out.println(Arrays.toString(dst));

Wednesday, January 8, 2014

Grails, finding available views (.gsp's) at runtime

This is not a important post. I just need to do some googling to achieve this and i found at: http://stackoverflow.com/questions/1577872/grails-finding-available-views-gsps-at-runtime. Thanks Burt Beckwith. I put this here to not search in google again.


import org.codehaus.groovy.grails.web.context.ServletContextHolder as SCH

def viewGsp() {
    List gspFileList = []
    if (grailsApplication.isWarDeployed()) {
        findWarGspList ('/WEB-INF/grails-app/views', gspFileList);
    } else {
        findDevGspList ('grails-app/views', gspFileList);
    }
    gspFileList.each {
        render it.toString() + "<br/>";
    }
    render "";
}
private void findDevGspList(String location, List gspFileList) {
    for (file in new File(location).listFiles()) {
        if (file.path.endsWith('.gsp')) {
            gspFileList << file.path - 'grails-app/views/';
        } else {
            findDevGspList (file.path, gspFileList);
        }
    }
}

private void findWarGspList(String location, List gspFileList) {
    def servletContext = SCH.servletContext
    for (path in servletContext.getResourcePaths(location)) {
        if (path.endsWith('.gsp')) {
            gspFileList << path - '/WEB-INF/grails-app/views/';
        } else {
            findWarGspList (path, gspFileList);
        }
    }
}

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();
    }
}