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:");

Friday, June 22, 2018

Header only retrieval in php via curl | PHP CURL get content type from URL | PHP CURL retrieve headers information from URL

Response headers can contain valuable information and may help to keep your API responses simpler by separating the actual response data from accessory metadata.
For instance, when querying the API for a list of posts, the response body includes just the content but there are also some other valualbe information sent as headers:
The PHP code for the CURL request would look something like this:
$agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36 X-Client-Data: CIa2yQEIpLbJAQjBtskBCKmdygEIqKPKARiSo8oB";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_FILETIME, true);
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_USERAGENT, $agent);
$header = curl_exec($curl);
$info = curl_getinfo($curl);
curl_close($curl);
Which will output as below:
HTTP/1.1 200 OK
Date: Fri, 22 Jun 2018 06:47:27 GMT
Server: Apache/2.4.33 (Win32) OpenSSL/1.0.2n PHP/5.6.35
Last-Modified: Sun, 11 Feb 2018 16:39:41 GMT
ETag: "5ae6f-564f2687e28f8"
Accept-Ranges: bytes
Content-Length: 372335
Content-Type: application/pdf

Array
(
    [url] => http://localhost/text-finder/download.pdf
    [content_type] => application/pdf
    [http_code] => 200
    [header_size] => 265
    [request_size] => 258
    [filetime] => 1518367181
    [ssl_verify_result] => 0
    [redirect_count] => 0
    [total_time] => 0.016
    [namelookup_time] => 0.016
    [connect_time] => 0.016
    [pretransfer_time] => 0.016
    [size_upload] => 0
    [size_download] => 0
    [speed_download] => 0
    [speed_upload] => 0
    [download_content_length] => 372335
    [upload_content_length] => -1
    [starttransfer_time] => 0.016
    [redirect_time] => 0
    [redirect_url] => 
    [primary_ip] => ::1
    [certinfo] => Array
        (
        )

    [primary_port] => 80
    [local_ip] => ::1
    [local_port] => 51877
)


HTTP/1.1 200 OK
Date: Fri, 22 Jun 2018 06:48:11 GMT
Server: Apache/2.4.33 (Win32) OpenSSL/1.0.2n PHP/5.6.35
Last-Modified: Fri, 22 Jun 2018 04:18:28 GMT
ETag: "92-56f3352eebe85"
Accept-Ranges: bytes
Content-Length: 146
Content-Type: text/html

Array
(
    [url] => http://localhost/text-finder/test2.html
    [content_type] => text/html
    [http_code] => 200
    [header_size] => 253
    [request_size] => 256
    [filetime] => 1529641108
    [ssl_verify_result] => 0
    [redirect_count] => 0
    [total_time] => 0.015
    [namelookup_time] => 1.0E-6
    [connect_time] => 0.015
    [pretransfer_time] => 0.015
    [size_upload] => 0
    [size_download] => 0
    [speed_download] => 0
    [speed_upload] => 0
    [download_content_length] => 146
    [upload_content_length] => -1
    [starttransfer_time] => 0.015
    [redirect_time] => 0
    [redirect_url] => 
    [primary_ip] => ::1
    [certinfo] => Array
        (
        )

    [primary_port] => 80
    [local_ip] => ::1
    [local_port] => 51944
)