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.


Monday, October 23, 2017

Grails Link Generator | Generate Links Outside Controllers or Tag Libraries | Using grailsLinkGenerator to generate link | Custom Link Generator

Grails Link Generator | Generate Links Outside Controllers or Tag Libraries | Using grailsLinkGenerator to generate link | Custom Link Generator

It's easy, just need to follow below steps:
First create a properties file named "application.properties" under web-app/WEB-INF as follows:


configs.serverURL=http://localhost:8033/custom-link-generator-bean


Now create a Groovy file named "ConfigurationProperties.groovy" with below contents:


package com.link

import grails.util.Environment

/**
 * Created by pritom on 23/10/2017.
 */
class ConfigurationProperties {
    public static final String DEV_DIR = "web-app/WEB-INF"
    private static Properties ppt

    static getProperty(String name, def defaultV = null) {
        if (ppt == null) {
            ppt = new Properties()
            loadProperties("application.properties")
        }

        def result = ppt.getProperty(name, defaultV?.toString())
        return result == "" ? defaultV : result
    }

    static loadProperties(String fileName) {
        URL url = ConfigurationProperties.class.getResource("ConfigurationProperties.class")
        String thisPath = url.getPath(), path
        if(Environment.current == Environment.DEVELOPMENT || Environment.current == Environment.TEST) {
            path = "file://" + thisPath.substring(0, thisPath.lastIndexOf("target")) + "${DEV_DIR}/${fileName}"
        }
        else {
            path = "file://" + thisPath.substring(0, thisPath.lastIndexOf("classes")) + fileName
        }

        new File(path.toURI()).getCanonicalFile().withInputStream { InputStream stream ->
            ppt.load(stream)
        }
    }
}


Now create a Groovy file named "MyLinkGenerator.groovy" with below contents:


package com.link

import org.codehaus.groovy.grails.web.mapping.DefaultLinkGenerator
import org.codehaus.groovy.grails.web.mapping.LinkGenerator
/**
 * Created by pritom on 23/10/2017.
 */
class MyLinkGenerator extends DefaultLinkGenerator implements LinkGenerator {
    MyLinkGenerator(String serverBaseURL, String contextPath) {
        super(serverBaseURL, contextPath)
    }

    MyLinkGenerator(String serverBaseURL) {
        super(serverBaseURL)
    }

    String makeServerURL() {
        return ConfigurationProperties.getProperty("configs.serverURL")
    }

    String link(Map attrs, String encoding = 'UTF-8') {
        String cp = super.getContextPath()
        String url = super.link(attrs, encoding)
        if (cp) {
            if (cp != null && url.startsWith(cp)) url = url.substring(cp.length())
            if (url.startsWith("/")) url = url.substring(1)
            return makeServerURL() + "/" + url
        }
        return url
    }
}


Now add below lines to BootStrap.groovy


import com.link.MyLinkGenerator
import grails.spring.BeanBuilder
import org.codehaus.groovy.grails.commons.GrailsApplication

import javax.servlet.ServletContext

class BootStrap {
    ServletContext servletContext
    GrailsApplication grailsApplication

    def init = { servletContext ->
        grailsApplication.mainContext.removeBeanDefinition("grailsLinkGenerator")
        BeanBuilder bb = new BeanBuilder()
        bb.beans {
            grailsLinkGenerator(MyLinkGenerator, null)
        }
        bb.registerBeans(grailsApplication.mainContext)
    }

    def destroy = {

    }
}


And create another Groovy file named "AsyncManager.groovy" with below contents to check it in thread:


package com.link

/**
 * Created by pritom on 23/10/2017.
 */
class AsyncManager {
    static void run(Closure closure) {
        TimerTask task = new TimerTask() {
            @Override
            void run() {
                try {
                    closure.call()
                }
                catch (Exception e) {
                    e.printStackTrace()
                }
            }
        }
        new Timer().schedule(task, 1000L)
    }
}


And finally add a controller with below contents:


package com.link

class CustomLinkController {
    def grailsLinkGenerator

    def index() {
        println "In-request"
        println "Generator=${grailsLinkGenerator.class}"
        println "Base-url=${grailsLinkGenerator.serverBaseURL}"
        println "Controller-url=${grailsLinkGenerator.link(controller: "customLink", action: "index", params: [id: 2, name: "Pritom Kumar"])}"

        AsyncManager.run {
            println ""
            println "In-non-request"
            println "Generator=${grailsLinkGenerator.class}"
            println "Base-url=${grailsLinkGenerator.serverBaseURL}"
            println "Controller-url=${grailsLinkGenerator.link(controller: "customLink", action: "index", params: [id: 2, name: "Pritom Kumar"])}"
        }
        render ""
    }
}


Output would be as follows:


--------------WITHOUT CUSTOM LINK GENERATOR-----------------------
In-request
Generator=class asset.pipeline.grails.CachingLinkGenerator
Base-url=http://localhost:8033/custom-link-generator-bean
Controller-url=/custom-link-generator-bean/customLink/index/2?name=Pritom+Kumar

In-non-request
Generator=class asset.pipeline.grails.CachingLinkGenerator
Base-url=http://localhost:8080/custom-link-generator-bean
Controller-url=/custom-link-generator-bean/customLink/index/2?name=Pritom+Kumar


--------------WITH CUSTOM LINK GENERATOR-----------------------
In-request
Generator=class com.link.MyLinkGenerator
Base-url=http://localhost:8033/custom-link-generator-bean
Controller-url=http://localhost:8033/custom-link-generator-bean/customLink/index/2?name=Pritom+Kumar

In-non-request
Generator=class com.link.MyLinkGenerator
Base-url=http://localhost:8033/custom-link-generator-bean
Controller-url=http://localhost:8033/custom-link-generator-bean/customLink/index/2?name=Pritom+Kumar