Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

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

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.


Saturday, October 7, 2017

Java HttpsURLConnection and TLS 1.2 | Enable TLS 1.1 and 1.2 for Clients on Java 7 | Enabling TLSv1.2 with HttpsUrlConnection

You will have to create an SSLContext to set the Protocoll:

then you just have to set the SSLContext to the HttpsURLConnection:

httpsCon.setSSLSocketFactory(sc.getSocketFactory());


package com.pkm;

import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;

public class TLSRequest {
    public static void main(String[] args) throws Exception {
        HttpsURLConnection connection = (HttpsURLConnection) new URL("https://pritom.com").openConnection();
        // TLSv1 | TLSv1.1 | TLSv1.2
        SSLContext sc = SSLContext.getInstance("TLSv1");
        sc.init(null, null, new java.security.SecureRandom()); 
        connection.setSSLSocketFactory(sc.getSocketFactory());
    }
}

Stripe Payment API: Create Charge Or Payment Using Java Code

You need a Token (Saved credit card instance) to create a Payment which is known as Charge in Stripe API. Creating Charge in Stripe is equal to creating a Payment. 

Payment API documentation:
https://stripe.com/docs/api#charges 


package com.pkm;

import common.HttpJavaClient;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author PRITOM
 */
public class StripeCreatePayment {
    static final String API_KEY = "sk_test_eXF5nNyXat29WjWrqHK92rcj";
    static final String TOKEN_URL = "https://api.stripe.com/v1/tokens";
    static final String PAYMENT_URL = "https://api.stripe.com/v1/charges";
    
    public static void main(String[] args) {        
        Map params = new HashMap();
        params.put("amount", "210");
        params.put("currency", "aud");
        params.put("source", createToken());
        params.put("description", (new Date()).toString());
        String paramString = HttpJavaClient.buildParameters(params);
        
        Map headers = new HashMap();
        headers.put("Authorization", "Bearer " + API_KEY);
        headers.put("tls", "TLSv1.2");
        
        HttpJavaClient.Response response = HttpJavaClient.doPost(PAYMENT_URL, paramString, HttpJavaClient.Type.URL_ENCODED, headers);
        HttpJavaClient.println(response);
    }
    
    static String createToken() {
        Map params = new HashMap();
        params.put("card[name]", "Pritom Kumar");
        params.put("card[number]", "4242424242424242");
        params.put("card[exp_month]", "12");
        params.put("card[exp_year]", "19");
        params.put("card[cvc]", "123");
        String paramString = HttpJavaClient.buildParameters(params);
        
        Map headers = new HashMap();
        headers.put("Authorization", "Bearer " + API_KEY);
        headers.put("tls", "TLSv1.2");
        
        HttpJavaClient.Response response = HttpJavaClient.doPost(TOKEN_URL, paramString, HttpJavaClient.Type.URL_ENCODED, headers);
        if (response.getCode() == 200) {
            String token = response.getBody().substring(response.getBody().indexOf("\"id\": \"") + 7);
            return token.substring(0, token.indexOf("\""));
        }
        return null;
    }
}

And output would be for successful transaction line below:


  "id": "ch_1BACCFFIwfarG3vBdzS2A09q",
  "object": "charge",
  "amount": 210,
  "amount_refunded": 0,
  "application": null,
  "application_fee": null,
  "balance_transaction": "txn_1BACCFFIwfarG3vBWUtFsX4N",
  "captured": true,
  "created": 1507359243,
  "currency": "aud",
  "customer": null,
  "description": "Sat Oct 07 12:54:06 BDT 2017",
  "destination": null,
  "dispute": null,
  "failure_code": null,
  "failure_message": null,
  "fraud_details": {},
  "invoice": null,
  "livemode": false,
  "metadata": {},
  "on_behalf_of": null,
  "order": null,
  "outcome": {
    "network_status": "approved_by_network",
    "reason": null,
    "risk_level": "normal",
    "seller_message": "Payment complete.",
    "type": "authorized"
  },
  "paid": true,
  "receipt_email": null,
  "receipt_number": null,
  "refunded": false,
  "refunds": {
    "object": "list",
    "data": [],
    "has_more": false,
    "total_count": 0,
    "url": "/v1/charges/ch_1BACCFFIwfarG3vBdzS2A09q/refunds"
  },
  "review": null,
  "shipping": null,
  "source": {
    "id": "card_1BACCDFIwfarG3vBAnQYrCBR",
    "object": "card",
    "address_city": null,
    "address_country": null,
    "address_line1": null,
    "address_line1_check": null,
    "address_line2": null,
    "address_state": null,
    "address_zip": null,
    "address_zip_check": null,
    "brand": "Visa",
    "country": "US",
    "customer": null,
    "cvc_check": "pass",
    "dynamic_last4": null,
    "exp_month": 12,
    "exp_year": 2019,
    "fingerprint": "CjZNbbCtG5QSnuIS",
    "funding": "credit",
    "last4": "4242",
    "metadata": {},
    "name": "Pritom Kumar",
    "tokenization_method": null
  },
  "source_transfer": null,
  "statement_descriptor": null,
  "status": "succeeded",
  "transfer_group": null
}

Wednesday, May 24, 2017

How to sign string as well sign request body with public key using Java

Below is a code snippet which will sign your request using Public key.


package com.pkm.src;

import Base64OutputStream;
import IOUtil;

import javax.crypto.Cipher;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.security.MessageDigest;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

/**
 * Created by pritom on 24/05/2017.
 */
public class SignatureSigner {
    public static void main(String[] args) throws Exception {
        String certificateFile = ".....\\publickey.cer";
        String requestBody = "Param1=Value_Of_Param1&Param2=Value_Of_param2";
        String signature = encodeRSASHA1(certificateFile, requestBody);
        System.out.println("Signature=" + signature);
    }

    protected static String encodeRSASHA1(String certificateFile, String requestBody) throws Exception {
        FileInputStream certIn1 = new FileInputStream(certificateFile);
        CertificateFactory e = CertificateFactory.getInstance("X509");
        X509Certificate myCertificate = (X509Certificate) e.generateCertificate(certIn1);

        MessageDigest hashGen = MessageDigest.getInstance("SHA1");
        byte[] hash = hashGen.digest(requestBody.getBytes("UTF-8"));
        Cipher rsa = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        rsa.init(1, myCertificate);
        byte[] signature = rsa.doFinal(hash);

        ByteArrayInputStream sigIn = new ByteArrayInputStream(signature);
        ByteArrayOutputStream sigOut = new ByteArrayOutputStream();
        Base64OutputStream base64Out = new Base64OutputStream(sigOut, "");
        IOUtil.copy(sigIn, base64Out);
        base64Out.close();
        return new String(sigOut.toByteArray(), "US-ASCII");
    }
}

Which will output as below:

Signature=7GNccit4cY+rs4t/S0WBv.........+w1rYdiEO8PxuR3SQ=