Saturday, November 4, 2017

Configuring Grails DDL | Table Configuration | Grails DDL Schema Configuration | Table Schema Structure

Configuring Grails DDL | Table Configuration | Grails DDL Schema Configuration | Table Schema Structure


You need to create your own configuration class as below:


package com.multidb.gorm

import org.codehaus.groovy.grails.commons.GrailsApplication
import org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsAnnotationConfiguration
import org.hibernate.HibernateException
import org.hibernate.cfg.Configuration
import org.hibernate.dialect.Dialect
import org.hibernate.tool.hbm2ddl.DatabaseMetadata
import org.hibernate.tool.hbm2ddl.SchemaUpdateScript

class MyDbConfigClass extends GrailsAnnotationConfiguration {
    private GrailsApplication grailsApplication
    public static Configuration configuration = null

    @Override
    protected void secondPassCompile() {
        super.secondPassCompile()
        if (!configuration) {
            configuration = this
        }
    }

    @Override
    String[] generateDropSchemaScript(Dialect dialect) throws HibernateException {
        return checkAndRemoveIgnoredTables(super.generateDropSchemaScript(dialect));
    }

    @Override
    String[] generateSchemaCreationScript(Dialect dialect) throws HibernateException {
        return checkAndRemoveIgnoredTables(super.generateSchemaCreationScript(dialect));
    }

    @Override
    List<SchemaUpdateScript> generateSchemaUpdateScriptList(Dialect dialect, DatabaseMetadata databaseMetadata) throws HibernateException {
        return super.generateSchemaUpdateScriptList(dialect, databaseMetadata)
    }

    @Override
    String[] generateSchemaUpdateScript(Dialect dialect, DatabaseMetadata databaseMetadata) throws HibernateException {
        List<SchemaUpdateScript> scripts = super.generateSchemaUpdateScriptList(dialect, databaseMetadata)
        return SchemaUpdateScript.toStringArray(scripts)
    }

    private static String[] checkAndRemoveIgnoredTables(String[] sqlStatements) {
        println(sqlStatements)
        return sqlStatements
    }

    @Override
    void setGrailsApplication(GrailsApplication application) {
        // Run superclass method
        super.setGrailsApplication(application)

        // Inject Grails application reference
        this.grailsApplication = application
    }
}


Below is DataSource configuration:


dataSource {
    configClass = com.multidb.gorm.MyDbConfigClass
    driverClassName = "com.mysql.jdbc.Driver"
    dbCreate = "create"
    url = "jdbc:mysql://localhost/grails_db"
    username = "grails"
    password = "grails"
}

Thursday, November 2, 2017

JavaScript jQuery Phone Number Validation Using Regex Pattern

Below is the regex to check valid phone number:


var regex = /(^(\+?[0-9]+)?((\s|\-|\.)[0-9]+)+$)|(^\(\+?[0-9]+\)((\s|\-|\.)[0-9]+)+$)|(^[0-9]+$)/i;


Regex check result as below:


+39 347 12 34 567 is valid = true
(+333)-696 900 is valid = true
(+333) -696 900 is valid = false
(+333)-696 900 is valid = true
(+333-696 900 is valid = false
+333-696 900 is valid = true
+333-696 900 is valid = true
+333-696 900 is valid = true
333-696 900 is valid = true
333-696 900 is valid = true
333-696 90 is valid = true
333-696 9 is valid = true
333-696 is valid = true
333-69 is valid = true
333-6 is valid = true
333- is valid = false
333 is valid = true

JavaScript | jQuery Validate Email Address Using Regex Pattern Check


var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;





And you can check your desired input by:




pattern.test("pritomkucse@gmail.com"); 

Java Timer TimerTask Example | Use java.util.Timer to schedule a task to execute every 1 second interval

Java Timer TimerTask Example | Use java.util.Timer to schedule a task to execute every 1 second interval



package com.pkm;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by pritom on 31/10/2017.
 */
public class JavaTimerTask {
    static ThreadLocal threadLocal = new ThreadLocal();

    public static void main(String[] args) throws Exception {
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                Integer count = threadLocal.get() != null ? Integer.parseInt(threadLocal.get().toString()) : 0;
                threadLocal.set((count + 1));
                System.out.println("Executed-at=" + (new Date()) +
                        ", Name=" + Thread.currentThread().getName() +
                        ", ThreadLocal=" + threadLocal.get());
                if (count >= 9) {
                    this.cancel();
                }
            }
        };
        new Timer().schedule(task, 1000L, 1000L);

        task = new TimerTask() {
            @Override
            public void run() {
                Integer count = threadLocal.get() != null ? Integer.parseInt(threadLocal.get().toString()) : 0;
                threadLocal.set((count + 1));
                System.out.println("Executed-another-at=" + (new Date()) +
                        ", Name=" + Thread.currentThread().getName() +
                        ", ThreadLocal=" + threadLocal.get());
                if (count >= 9) {
                    this.cancel();
                }
            }
        };
        new Timer().schedule(task, 5000L, 1000L);
        /**
         * First parameter is task
         * Second parameter is delay time
         * Third parameter (optional) if you want some periodic execution of task
         *
         * And you finally noticed that though "ThreadLocal" is a static field in main class
         * but value for each thread is different, that means "ThreadLocal" is a variable
         * that is unique for each thread, its scope is thread wise, not class wise
         */

        /* You can cancel timer if you need */
        /* timer.cancel(); */
    }
}


And output be like below:


Executed-at=Thu Nov 02 08:12:51 BDT 2017, Name=Timer-0, ThreadLocal=1
Executed-at=Thu Nov 02 08:12:52 BDT 2017, Name=Timer-0, ThreadLocal=2
Executed-at=Thu Nov 02 08:12:53 BDT 2017, Name=Timer-0, ThreadLocal=3
Executed-at=Thu Nov 02 08:12:54 BDT 2017, Name=Timer-0, ThreadLocal=4
Executed-at=Thu Nov 02 08:12:55 BDT 2017, Name=Timer-0, ThreadLocal=5
Executed-another-at=Thu Nov 02 08:12:55 BDT 2017, Name=Timer-1, ThreadLocal=1
Executed-at=Thu Nov 02 08:12:56 BDT 2017, Name=Timer-0, ThreadLocal=6
Executed-another-at=Thu Nov 02 08:12:56 BDT 2017, Name=Timer-1, ThreadLocal=2
Executed-at=Thu Nov 02 08:12:57 BDT 2017, Name=Timer-0, ThreadLocal=7
Executed-another-at=Thu Nov 02 08:12:57 BDT 2017, Name=Timer-1, ThreadLocal=3
Executed-at=Thu Nov 02 08:12:58 BDT 2017, Name=Timer-0, ThreadLocal=8
Executed-another-at=Thu Nov 02 08:12:58 BDT 2017, Name=Timer-1, ThreadLocal=4
Executed-another-at=Thu Nov 02 08:12:59 BDT 2017, Name=Timer-1, ThreadLocal=5
Executed-at=Thu Nov 02 08:12:59 BDT 2017, Name=Timer-0, ThreadLocal=9
Executed-at=Thu Nov 02 08:13:00 BDT 2017, Name=Timer-0, ThreadLocal=10
Executed-another-at=Thu Nov 02 08:13:00 BDT 2017, Name=Timer-1, ThreadLocal=6
Executed-another-at=Thu Nov 02 08:13:01 BDT 2017, Name=Timer-1, ThreadLocal=7
Executed-another-at=Thu Nov 02 08:13:02 BDT 2017, Name=Timer-1, ThreadLocal=8
Executed-another-at=Thu Nov 02 08:13:03 BDT 2017, Name=Timer-1, ThreadLocal=9
Executed-another-at=Thu Nov 02 08:13:04 BDT 2017, Name=Timer-1, ThreadLocal=10


Wednesday, November 1, 2017

Java FutureTask Example With ExecutorService | Java Callable Future Example With ExecutorService

Here Executor framework used to execute 5 tasks in parallel in 2 thread pool (not more than 2 thread will be execute at the same time) and use Java Future to get the result of the submitted tasks. SJava Callable Future interfaces used to get the concurrent processing benefits of threads and we know that they are capable of returning value to the calling program. Also we can use of isDone() method to check make sure thread ends once all the tasks are executed.



package com.pkm;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

/**
 * Created by pritom on 31/10/2017.
 */
public class FutureExecutorService implements Callable {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        List<Future<String>> list = new ArrayList<Future<String>>();
        FutureExecutorService callable = new FutureExecutorService();
        for (Integer i = 0; i < 5; i++) {
            Future<String> future = executor.submit(callable);
            list.add(future);
        }
        for (Future<String> future : list) {
            Object object = future.get();
        }
        executor.shutdown();
    }

    @Override
    public Object call() throws Exception {
        System.out.println("Thread started at = " + (new Date()));
        Thread.sleep(1000L * (1 + (new SecureRandom().nextInt(2))));
        System.out.println("Thread finished at = " + (new Date()) + ", thread=" + Thread.currentThread().getName());
        return "Thread executed at = " + (new Date()) +
                ", name=" + Thread.currentThread().getName();
    }
}


Output as below:


Thread started at = Wed Nov 01 09:33:50 BDT 2017
Thread started at = Wed Nov 01 09:33:50 BDT 2017
Thread finished at = Wed Nov 01 09:33:51 BDT 2017, thread=pool-1-thread-1
Thread started at = Wed Nov 01 09:33:51 BDT 2017
Thread finished at = Wed Nov 01 09:33:52 BDT 2017, thread=pool-1-thread-2
Thread started at = Wed Nov 01 09:33:52 BDT 2017
Thread finished at = Wed Nov 01 09:33:52 BDT 2017, thread=pool-1-thread-1
Thread started at = Wed Nov 01 09:33:52 BDT 2017
Thread finished at = Wed Nov 01 09:33:54 BDT 2017, thread=pool-1-thread-2
Thread finished at = Wed Nov 01 09:33:54 BDT 2017, thread=pool-1-thread-1


As you can show in output that 2 thread are running at a time and once one of them finished another one started execution. So is the use of ExecutorService to maintain thread pool.


Tuesday, October 31, 2017

Callable and Future in Java | Callable vs Runnable | Java Callable Future Example

Callable and Future in Java | Callable vs Runnable | Java Callable Future Example

Java Callable and Future are used a lot in multithreaded programming. Java 5 introduced java.util.concurrent.Callable interface in concurrency package that is similar to Runnable interface but it can return any Object and able to throw Exception. Java Callable tasks return java.util.concurrent.Future object. Using Java Future object, we can find out the status of the Callable task and get the returned Object. It provides get() method that can wait for the Callable to finish and then return the result.
Below is a simple example:


package com.pkm;

import java.security.SecureRandom;
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/**
 * Created by pritom on 31/10/2017.
 */
public class CallableTest implements Callable {
    private Integer n;

    public static void main(String[] args) throws Exception {
        FutureTask[] futureTasks = new FutureTask[5];
        for (Integer i = 0; i < 5; i++) {
            CallableTest callable = new CallableTest(i);
            futureTasks[i] = new FutureTask(callable);
            Thread thread = new Thread(futureTasks[i]);
            thread.start();
        }
        for (Integer i = 0; i < 5; i++) {
            System.out.println(futureTasks[i].get());
        }
    }

    public CallableTest(Integer n) {
        this.n = n;
    }

    @Override
    public Object call() throws Exception {
        System.out.println("Thread called at = " + (new Date()));
        Thread.sleep(1000L * (1 + (new SecureRandom().nextInt(5))));
        return "Thread executed at = " + (new Date()) +
                ", name=" + Thread.currentThread().getName() + "." + n;
    }
}


Output is below:


Thread called at = Tue Oct 31 16:02:08 BDT 2017
Thread called at = Tue Oct 31 16:02:08 BDT 2017
Thread called at = Tue Oct 31 16:02:08 BDT 2017
Thread called at = Tue Oct 31 16:02:08 BDT 2017
Thread called at = Tue Oct 31 16:02:08 BDT 2017
Thread executed at = Tue Oct 31 16:02:13 BDT 2017, name=Thread-0.0
Thread executed at = Tue Oct 31 16:02:13 BDT 2017, name=Thread-1.1
Thread executed at = Tue Oct 31 16:02:11 BDT 2017, name=Thread-2.2
Thread executed at = Tue Oct 31 16:02:10 BDT 2017, name=Thread-3.3
Thread executed at = Tue Oct 31 16:02:09 BDT 2017, name=Thread-4.4


Java Thread Example by extending Thread class | Java Thread Example by implementing Runnable interface

Java Thread Example by extending Thread class



package com.pkm;

import java.util.Date;

/**
 * Created by pritom on 31/10/2017.
 */
public class ThreadTest extends Thread {
    public static void main(String[] args) throws Exception {
        System.out.println("Thread called at = " + (new Date()));
        new ThreadTest().start();
    }

    public void run() {
        try {
            sleep(10000L);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Thread executed at = " + (new Date()));
    }
}


Java Thread Example by implementing Runnable interface


package com.pkm;

import java.util.Date;

/**
 * Created by pritom on 31/10/2017.
 */
public class RunnableTest implements Runnable {
    public static void main(String[] args) throws Exception {
        System.out.println("Thread called at = " + (new Date()));
        new Thread(new RunnableTest()).start();
    }

    @Override
    public void run() {
        try {
            Thread.sleep(10000L);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Thread executed at = " + (new Date()));
    }
}

So we can use "Runnable" interface, it will help us inherit another class, because if we use "Thread" inheritance then we should loose one scope to inherit another class if we need.