Saturday, November 11, 2017

JavaScript Interval Example | SetInterval And ClearInterval

JavaScript setInterval & clearInterval example:



var i = 3;

var interval = setInterval(function() {
  if (i > 0) {
    $("div").html("Running " + i--);
  }
  else {
    clearInterval(interval);

    $("div").html("Stopped");
  }
}, 2000);


JSFiddle example link

Thursday, November 9, 2017

jQuery Number Text Field Validation Using Regex On Input Field

jQuery Number Text Field Validation Using Regex

Below is the full example of how to validate number using regex


var pattern = new RegExp("(^(\-?)([0-9]{0,12}?)(\\.)([0-9]){0,12}$)|(^(\-?)([0-9]){0,12}$)");

$(document.body).on("keypress", "input[type='text'].number", function (e) {
    if (e.which == 0 || e.which == 8) return true;
    var v = getTextFieldValue(this, String.fromCharCode(e.which));
    $("div").html(v);
    return pattern.test(v);
});

document.addEventListener("paste", function (e) {
    var v, f = $(e.target), ov = f.val();
    if (window.clipboardData && window.clipboardData.getData) { // IE
        v = window.clipboardData.getData('Text');
    }
    else if (e.originalEvent && e.originalEvent.clipboardData && e.originalEvent.clipboardData.getData) {
        v = e.originalEvent.clipboardData.getData('text/plain');
    }
    else if (e.clipboardData && e.clipboardData.getData) {
        v = e.clipboardData.getData('text/plain');
    }
    v = getTextFieldValue(f[0], v);
    if (!pattern.test(v)) e.preventDefault();
    $("div").html(v);
});

function getTextFieldValue(input, nv) {
    var v = input.value, i = input.selectionStart, j = input.selectionEnd;

    if (i == 0 && j == v.length) return nv;
    else if (i != j || i > 0) return v.substr(0, i) + nv + v.substr(j);
    else if (i == 0) return nv + v;
    else return v + nv;
}

$("input[type='text'].number").focus();


And finally you can use below regex to test your number:
^[-+]?(?:\.[0-9]{1,12}|[0-9]{1,12}(?:\.[0-9]{0,12})?)(?:[eE][-+]?[0-9]{1,12})?$

You can experience above example in JsFiddle

You can also check in regex test environment





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.