Monday, April 22, 2013

Grails create criteria on model

def c = Account.createCriteria()
List results = c.list {
    like("name", "%Name Like%")
    and {
        between("amount", 500, 1000)
        eq("address", "London")
    }
    setFirstResult(0)
    setMaxResults(10)
    order("name", "desc")
    order("id", "asc")
    
    projections {
        property("id")
        groupProperty("invoice.id")
    }
}


Below is a node reference for each criterion method:

Node

Description

between
Where the property value is between to distinct values
between("balance", 500, 1000)
eq
Where a property equals a particular value
eq("branch", "London")
eqProperty
Where one property must equal another
eqProperty("lastTransaction","firstTransaction")
gt
Where a property is greater than a particular value
gt("balance",1000)
gtProperty
Where a one property must be greater than another
gtProperty("balance","overdraft")
ge
Where a property is greater than or equal to a particular value
ge("balance",1000)
geProperty
Where a one property must be greater than or equal to another
geProperty("balance","overdraft")
idEq
Where an objects id equals the specified value
idEq(1)
ilike
A case-insensitive 'like' expression
ilike("holderFirstName","Steph%")
in
Where a one property is contained within the specified list of values note: 'in' is a groovy reserve word, we must escape it by quotes.
'in'("holderAge",[18..65])
isEmpty
Where a collection property is empty
isEmpty("transactions")
isNotEmpty
Where a collection property is not empty
isNotEmpty("transactions")
isNull
Where a property is null
isNull("holderGender")
isNotNull
Where a property is not null
isNotNull("holderGender")
lt
Where a property is less than a particular value
lt("balance",1000)
ltProperty
Where a one property must be less than another
ltProperty("balance","overdraft")
le
Where a property is less than or equal to a particular value
le("balance",1000)
leProperty
Where a one property must be less than or equal to another
leProperty("balance","overdraft")
like
Equivalent to SQL like expression
like("holderFirstName","Steph%")
ne
Where a property does not equals a particular value
ne("branch", "London")
neProperty
Where one property does not equal another
neProperty("lastTransaction","firstTransaction")
order
Order the results by a particular property
order("holderLastName", "desc")
sizeEq
Where a collection property's size equals a particular value
sizeEq("transactions", 10)
sizeGt
Where a collection property's size is greater than a particular value
sizeGt("transactions", 10)
sizeGe
Where a collection property's size is greater than or equal to a particular value
sizeGe("transactions", 10)
sizeLt
Where a collection property's size is less than a particular value
sizeLt("transactions", 10)
sizeLe
Where a collection property's size is less than or equal to a particular value
sizeLe("transactions", 10)
sizeNe
Where a collection property's size is not equal to a particular value
sizeNe("transactions", 10)

With dynamic finders, you have access to options such as max, sort, etc. These are available to criteria queries as well, but they have different names:

Name Description
order(String, String)
Specifies both the sort column (the first argument) and the sort order (either 'asc' or 'desc').
order "age", "desc"
firstResult(int)
Specifies the offset for the results. A value of 0 will return all records up to the maximum specified.
firstResult 20
maxResults(int)
Specifies the maximum number of records to return.
maxResults 10
cache(boolean)
Indicates if the query should be cached (if the query cache is enabled).
cache true


Criteria also support the notion of projections. A projection is used to change the nature of the results. For example the following query uses a projection to count the number of distinct branch names that exist for each Account:


Name Description
property
Returns the given property in the returned results
property("firstName")
distinct
Returns results using a single or collection of distinct property names
distinct("fn") or distinct(['fn', 'ln'])
avg
Returns the average value of the given property
avg("age")
count
Returns the count of the given property name
count("branch")
countDistinct
Returns the count of the given property name for distinct rows
countDistinct("branch")
groupProperty
Groups the results by the given property
groupProperty("lastName")
max
Returns the maximum value of the given property
max("age")
min
Returns the minimum value of the given property
min("age")
sum
Returns the sum of the given property
sum("balance")
rowCount
Returns count of the number of rows returned
rowCount()

XXXXXXXXXXXXXXXX

Convert string to date format java SimpleDaeFormat

String string = "January 2, 2010";
Date date = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(string);
System.out.println(date); // Sat Jan 02 00:00:00 BOT 2010


DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); 

String newDateString = df.format(date);



Date and Time Pattern Result
"yyyy.MM.dd G 'at' HH:mm:ss z" 2001.07.04 AD at 12:08:56 PDT
"EEE, MMM d, ''yy" Wed, Jul 4, '01
"h:mm a" 12:08 PM
"hh 'o''clock' a, zzzz" 12 o'clock PM, Pacific Daylight Time
"K:mm a, z" 0:08 PM, PDT
"yyyyy.MMMMM.dd GGG hh:mm aaa" 02001.July.04 AD 12:08 PM
"EEE, d MMM yyyy HH:mm:ss Z" Wed, 4 Jul 2001 12:08:56 -0700
"yyMMddHHmmssZ" 010704120856-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSZ" 2001-07-04T12:08:56.235-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX" 2001-07-04T12:08:56.235-07:00
"YYYY-'W'ww-u" 2001-W27-3

Letter Date or Time Component Presentation Examples
G Era designator Text AD
y Year Year 1996; 96
Y Week year Year 2009; 09
M Month in year Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day name in week Text Tuesday; Tue
u Day number of week (1 = Monday, ..., 7 = Sunday) Number 1
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800
X Time zone ISO 8601 time zone -08; -0800; -08:00

cakephp call controller action from ctp file

$this->requestAction(array('controller' => 'users', 'action' => 'get_category/10/20'));

Convert string to sha1 using java

<?php
public static String hash(String toHash) {
    if (toHash == null || toHash.equals(""))
        return null;
    
    StringBuffer hexString = new StringBuffer();
    
    try {
        java.io.StringReader sr =  new java.io.StringReader(toHash);
        java.io.ByteArrayOutputStream baos =  new java.io.ByteArrayOutputStream();
        int ch;

        while ((ch = sr.read()) != -1) {
            baos.write(ch);
        }

         //SHA-1 Hash value of data 
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        sha.reset();
        sha.update(baos.toByteArray());

        byte[] digest = sha.digest();

        /*  NB: This conversion strips the leading 0 from any 
         *  digest byte with a value less than 16.
         *  
         *  This weakens the security of the SHA-1 hash and requires
         *  workarounds on the server to overcome this.
         *  
         *  It's all quite embarrassing. -- PB
         */
        for (int i=0;i<digest.length;i++) {
            hexString.append(Integer.toHexString(0xFF & digest[i]).toUpperCase());
        }
    } catch (java.io.IOException ioE) {
        System.out.println(ioE);
    } catch (NoSuchAlgorithmException algE) {
        System.out.println(algE);
    }
    
    return hexString.toString();
}
?>

How to add Meta Description Tags

  1. Go to Settings > Search Settings and Enable Meta Tags. In the Text area give a 150 character description which will describe your Blog. This text might be used by Search engines when your Blog’s home page is displayed on Search Engines. Here is the snippet that I have given “Blogger Widgets provides you the best quality blogger tutorials.It also provides you with free blogger widgets and  gadgets to build a better blog.”
  2. Now when you make a Post, you can set the Meta Description from the Post Editor’s Post
  3. If you are having a custom template, make sure that the following line of code is present in your template. To do that go to Template and Proceed to Edit HTML . Find
    <b:include data='blog' name='all-head-content'/>
    If it's not present, add it just before </head>

Sunday, April 21, 2013

Yii throw 404 custom exception

You need to define a view file under protected/views/site folder (any folder and that shoud be configured in config/main.php file as below) suppose named error.php, and throw CHttpException from where you want to show error page.


Define error view in config/main.php file:
'errorHandler'=>array(
    // use 'site/error' action to display errors
    'errorAction'=>'site/error',
)
That means a file named error.php shoud be in views/site/ folder.

Throw 404 custom exception using the following php  code:
throw new CHttpException(404,'The requested page does not exist.');

And the error.php file look like:
<?php
$this->pageTitle=Yii::app()->name . ' - Error';
$this->breadcrumbs=array(
    'Error'
);
?>
<h2>Error <?php echo $code; ?></h2>
<div class="error">
<?php echo CHtml::encode($message); ?>
</div>

Yii upload image or file to server

Model Image:
<?php
class Image extends CActiveRecord
{
    public $uploaded_owner_img;
  
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }
    
    public function tableName()
    {
        return 'table_name';
    }
    
    public function rules()
    {
        return array(
            array('owner_img', 'file', 'allowEmpty'=>true,'types'=>'jpg','maxSize'=>1024*1024*1, 'tooLarge'=>'Image must be less than�1MB'),
            array('owner_name, owner_img', 'required'),
            array('owner_name', 'unique'),
            array('owner_name', 'length', 'max'=>20, 'encoding'=>'utf-8'),
            array('owner_name', 'safe', 'on'=>'search'),
        );
    }
    
    public function attributeLabels()
    {
        return array(
            'owner_img' => 'Select image.',
            'owner_name' => 'Name'
        );
    }
    
    protected function beforeSave() {
        if (parent::beforeSave ()) {
            if ($this->isNewRecord) {
                $this->created = date('Ymd');
            }
            return true;
        }else {
            return false;
        }
    }
}
Controller ImageController.php
<?php
class ImageController extends Controller
{
    public function actions()
    {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha'=>array(
                'class'=>'CCaptchaAction',
                'backColor'=>0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page'=>array(
                'class'=>'CViewAction',
            )
        );
    }
        
    public function actionCreate()
    {
        $model=new Image;
        //AJAX validation is needed
        $this->performAjaxValidation($model);
        if(isset($_POST['Image'])) {
            $model->attributes=$_POST['Image'];
            if (@!empty($_FILES['Image']['name']['owner_img'])){
                $model->owner_img = time().".jpg";
                if ($model->validate(array('owner_img'))){
                    $model->uploaded_owner_img = CUploadedFile::getInstance($model, 'owner_img');
                    $model->uploaded_owner_img->saveAs(Yii::app()->basePath.'/'.$model->owner_img);
                    
                    if($model->save()){
                        echo "Model saved"; die(0);
                    }
                }
            }
        }

        $this->render('create',array(
            'model'=>$model,
        ));
    }
    
    protected function performAjaxValidation($model)
    {
        if(isset($_POST['ajax']) && $_POST['ajax']==='map-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
}
View file
<?php
$this->breadcrumbs=array(
    "image/create"
);

$this->menu=array(
);
?>

<h1>Image Upload</h1>

<div class="form">

<?php 
$form=$this->beginWidget('CActiveForm', array(
    'id'=>'map-form',
    'enableAjaxValidation'=>false,
    'htmlOptions' =>array('enctype'=>"multipart/form-data" ),
    'enableAjaxValidation' => false,
    'enableClientValidation'=>true,
    'clientOptions'=>array('validateOnSubmit'=>true)
)); 
?>

<p class="note">Mark <span class="required">*</span> are required.</p>

<?php echo $form->errorSummary($model); ?>

<div class="row">
    <?php echo $form->labelEx($model,'owner_name'); ?>
    <?php echo $form->textField($model,'owner_name',array('size'=>32,'maxlength'=>20)); ?>
    <?php echo $form->error($model,'owner_name'); ?>
</div>

<div class="row">
    <?php echo $form->labelEx($model,'owner_img'); ?>
    <?php echo $form->fileField($model,'owner_img'); ?>
    <?php echo $form->error($model,'owner_img'); ?>
</div>

<div class="row buttons">
    <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>

<?php $this->endWidget(); ?>
</div>