Wednesday, August 22, 2018

Grails on Groovy > Way in Grails to Eager Fetch the Whole Record | Load Related Entity With Single Query

I am trying to find if there is any way in Grails to eager fetch complete records instead of a left Join.
For example, let you have domain named Tabel1 with following structure and another domain named Table3 below:
package com.pkm

class Table1 {
    Long id
    String name
    String roll

    static mapping = {
        table("table1")
    }

    static belongsTo = [
            table3: Table3
    ]

    static constraints = {
        table3 nullable: true
    }
}



package com.pkm

class Table3 {
    Long id
    String name
}
So when you get/list Table1, what will be the default behavior? It will load only Table1 data, not other associated data like Table3.
There is a procedure to load selected associated by joining them. See the below example, enabled eager face data when creating criteria:
package com.pkm

import grails.transaction.Transactional
import org.hibernate.FetchMode
import org.hibernate.sql.JoinType
import org.springframework.transaction.TransactionStatus

@Transactional
class HomeService {
    TransactionStatus transactionStatus

    void callMe() {
        List list = Table1.createCriteria().list {
            createCriteria("table3", "j3", JoinType.LEFT_OUTER_JOIN)
            setFetchMode("j3", FetchMode.JOIN)
            order("id", "desc")
            setMaxResults(20)
        }
        list.each { Table1 table1 ->
            println("Name=${table1.name}, Table3=${table1.table3?.name}")
        }
    }
}
Now we will print the query generated:
select this_.id as id1_0_1_, this_.name as name2_0_1_, this_.roll as roll3_0_1_, this_.table3_id as table4_0_1_, j3x1_.id as id1_2_0_, j3x1_.name as name2_2_0_ from table1 this_ left outer join table3 j3x1_ on this_.table3_id=j3x1_.id order by this_.id desc limit ?
You observed that in select query, both Table1 and Table3 exists. And this is how we can implement eager face data when creating criteria builder to get data.

Saturday, August 11, 2018

Setting Up Recaptcha 2.0 with JavaScript and PHP

reCAPTCHA need to verify bots (automatic system) can't take advantage of your site. reCAPTCHA 2.0 is somewhat different than the old reCAPTCHA. In version 1.0 it required to type text but now in 2.0 it’s simply a click of a button as below image.

The term of verifying front end users is a bit different. A variable named "g-recaptcha-response" is sent through a POST request to your server-side script, and along with your reCAPTCHA secret key that you get when you sign up for your website, you need to pass that secret key along to Google to tell that the user is a bot or not to determine by system. The response from Google is a JSON response on success for failure both case, so that we will be using file_get_contents() and json_decode() to fetch and parse the response and decide that front user is valid or not.


The below is just a HTML form you should create to see captcha in your desired page. The div element with the class of "g-recaptcha" is the element where we want to place our Google captcha (reCAPTCHA). You need to replace data-sitekey with the key you get from google when you sign up for reCAPTCHA (https://www.google.com/recaptcha/intro/index.html).
<form method="post" enctype="multipart/form-data">
    <div class="g-recaptcha" data-sitekey="YOUR_KEY"></div>
    <button type="submit">CHECK RECAPTCHA</button>
</form>
But I will show another technique how to show reCAPTCHA using JavaScript. Below is a simple script to show how you can integrate reCAPTCHA using JavaScript. But server side validation using PHP. Use need to create an div with ID (suppose, you can create your div with other ID) captcha_container
<script src='https://www.google.com/recaptcha/api.js'></script>

var captchaContainer = grecaptcha.render('captcha_container', {
    'sitekey' : 'Your sitekey',
    'callback' : function(response) {
        console.log(response);
    }
});
Now time to validate reCAPTCHA from server side.
<?php
$url = 'https://www.google.com/recaptcha/api/siteverify';

$data = array(
    'secret' => 'YOUR_SECRET',
    'response' => $_POST["g-recaptcha-response"]
);

$options = array(
    'http' => array(
        'method' => 'POST',
        'content' => http_build_query($data)
    )
);

$context = stream_context_create($options);
$verify = file_get_contents($url, false, $context);
$captcha_success = json_decode($verify);

if ($captcha_success->success == false) {
    echo "<p>You are a bot! Go away!</p>";
}
else if ($captcha_success->success == true) {
    echo "<p>You are not not a bot!</p>";
}

Thursday, July 12, 2018

Java > Convert text content to Image > Using Java Create An Image And Save To File With Transparent Background

For example, from the string Pritom K Mondal, I would like to generate this simple image:
package com.pkm;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class TextToImage {
    public static void main(String[] args) {
        String text = "Pritom K Mondal";

        BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = img.createGraphics();
        Font font = new Font("Arial", Font.PLAIN, 48);
        g2d.setFont(font);
        FontMetrics fm = g2d.getFontMetrics();
        int width = fm.stringWidth(text) + 20;
        int height = fm.getHeight();
        g2d.dispose();

        img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        g2d = img.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
        g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
        g2d.setFont(font);
        fm = g2d.getFontMetrics();
        g2d.setColor(Color.BLACK);
        g2d.drawString(text, 10, fm.getAscent());
        g2d.dispose();
        try {
            ImageIO.write(img, "png", new File("Image.png"));
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
And output is like below:


Grails on Groovy over Java > Email Address Validation Using Regex

Below is a sample code snippet to validate email address using REGEX
package com.pkm;

import java.util.regex.Pattern;

public class EmailValidationRegex {
    private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+([\\.\\+]?[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    private static Pattern _pattern = null;

    public static void main(String[] args) {
        check("pritomkucse+regex.test@gmail.com");
        check("pkm@c.commmmmmmmmmmmmmmmmmmmm");
        check("pkm@c.commmmmmmmmmmmmmmmmmmmm.");
        check("pkm.+invalid@no.valid");
    }

    static void check(String email) {
        System.out.println(email + " > " + valid(email).toString().toUpperCase());
    }

    static Boolean valid(String email) {
        return getPattern().matcher(email).matches();
    }

    static Pattern getPattern() {
        if (_pattern != null) return _pattern;
        _pattern = Pattern.compile(EMAIL_PATTERN);
        return _pattern;
    }
}

Friday, July 6, 2018

Grails on Groovy > GORM dirty checking of instance and properties > grails - tell me if anything is dirty > Checking for Dirty (Updated) Properties on a Grails Domain

GORM provides Grails developers lots of useful hooks, events, methods, and functionality, very important is domain events that inform you when domain objects are being created, updated, and deleted. Within these events, a common use-case is to determine if a particular domain property has changed, and to act accordingly.
Below is a code snippet of how you validate your domain before insert or update.
package com.pkm

class Table1 {
    Long id
    String name
    String roll

    static mapping = {
        table("table1")
    }

    static hasMany = [
            scores: Table2
    ]

    void beforeValidate(){
        println("BEFORE VALIDATE")
    }

    void beforeInsert(){
        println("BEFORE INSERT")
    }

    void beforeUpdate(){
        println("BEFORE UPDATE")
    }
}
Now, how can you get the actual value of that object? The actual value is modified and you want to get the persisted value. One “not so good” idea is to call refresh() which will load the object from the database again which might be a huge data retrieval in few cases. To solve this problem, GORM has given a simple method which will do the work for you:
Below is a example of how you can see which fields are updating in current transaction using below code snippet
void beforeUpdate(){
    println("BEFORE UPDATE")
    this.dirtyPropertyNames.each { String fieldName ->
        def oldValue = this.getPersistentValue(fieldName)
        def newValue = this.getProperty(fieldName)
        println("\t> VALUE CHANGED FOR $fieldName FROM $oldValue TO $newValue")
    }
}
The best place to check for dirty properties is usually in the beforeUpdate event. The beforeInsert and afterUpdate events may also seem like good choices at first, but they may not be depending on the use-case. Before inserting, all properties are dirty because they are new, so they haven't really changed they have just been created. After updating, none of the properties are dirty because the new values have already been persisted in your database. These events provide plenty of value if used correctly, but may not always be the best place to check for dirty domain properties.
One domain in particular that I always perform dirty property checks on is any User domains that my application requires. For instance, if a User object's password has changed, you may want to be alerted in the beforeUpdate event and encrypt the password before it is inserted into your database.
You also can check if an existing field is dirty or not using
this.isDirty("fieldname")
Be careful not to perform any saves on the domain within these events, as you will get a StackOverflowException. (The event calls .save(), restarting the whole event cycle, where .save() will be called again, and so on. This infinite loop will never end, and the exception will be raised.)
Otherhand you can check if entire session (hibernate session) is dirty or not. so below is an example how to check if whole hibernate session is dirty or not.
package com.pkm

import grails.transaction.Transactional
import org.springframework.transaction.TransactionStatus

import org.hibernate.SessionFactory
import grails.util.Holders

@Transactional
class HomeService {
    TransactionStatus transactionStatus

    void callMe() {
        Table1 table1 = Table1.first()
        table1.roll = System.currentTimeMillis().toString()
        table1.save()

        SessionFactory sessionFactory = Holders.applicationContext.getBean(SessionFactory)
        Boolean isDirty = sessionFactory.currentSession.isDirty()
        println("IS SESSION DIRTY=${isDirty.toString().capitalize()}")
    }
}

Saturday, June 23, 2018

When do I need to call this method Runtime.getRuntime().addShutdownHook() > Java.lang.Runtime.addShutdownHook(Thread hook) Method > Java Shutdown hook – Runtime.addShutdownHook() > Grails on Groovy: Add a ShutdownHook > Runtime: addShutdownHook(Thread hook)

The java.lang.Runtime.addShutdownHook(Thread hook) method registers a new virtual-machine shutdown hook.The Java virtual machine shuts down in response to two kinds of events

> The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked

> The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown
Below is a example of how shutdown hook can be used:
package com.pkm;

public class RegisterShutDownHook {
    public static void main(String[] args) {
        System.out.println("PROGRAM STARTED");

        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                System.out.println("SHUTDOWN HOOK FIRED");
            }
        });

        System.out.println("PROGRAM RUNNING");
    }
}
Output of the above code snippet would be like below:
PROGRAM STARTED
PROGRAM RUNNING
SHUTDOWN HOOK FIRED
When you are using Grails application, you can do that various process. Either registering shutdown hook or implementing DisposableBean
Below is the process using shutdown hook
class BootStrap {
    def init = { servletContext ->
        addShutdownHook {
            println("Running Shutdown Hook");
        }
    }

    def destroy = {

    }
}
Or as below, create another class and registering that from resources.groovy like below:
package com.pkm

import org.springframework.context.ApplicationContextAware
import org.springframework.context.ApplicationContext

class ShutdownHook implements ApplicationContextAware {
    void setApplicationContext(ApplicationContext applicationContext) {
        Runtime.runtime.addShutdownHook {
            println("Application context shutting down...")
            applicationContext.close()
            println("Application context shutdown.")
        }
    }
}

// Adding the following block in grails-app/conf/spring/resources.groovy
// Place your Spring DSL code here
beans = {
    myShutdownHook(com.pkm.ShutdownHook)
}
And my last known process is using DisposableBean
package com.pkm

import grails.transaction.Transactional
import org.springframework.beans.factory.DisposableBean

@Transactional
class HomeService implements DisposableBean {
    @Override
    void destroy() throws Exception {
        println("APPLICATION DESTROYED")
    }
}

How to pass parameters / arguments to your PHP script via the command line

If you want to be able to assign variable names for the values being passed in like php script.php -pvalue1, getopt() is the way to do it. Lets look at a different version of the script now >
$val = getopt("p:");
There are some major differences here. First with getopt() you must specify which command line argument you want to retrieve. In the case of this script, it looks for the "-name" argument, that's specified by the "name:" value passed to getopt(). The colon (:) means that the parameter must have a value. If you're used to doing something like "script.php?name=Name&roll=Roll" this is an equivalent for the command line.
php script.php --name=test --roll="03 d"
$val = getopt("name:roll:");