Thursday, June 4, 2015

Java Implementation of String Next Sequence


package time.zone;

import java.util.ArrayList;
import java.util.List;

public class JavaNextCharacter {
    public static void main (String[] args) throws Exception {
        List<String> codes = new ArrayList<String>();
        long started = System.currentTimeMillis();
        String s1 = "IjKl", s2 = "P.R.I.T.O.M", s3 = "{AB374}", s4 = "{ZZ}{U8U}", s5 = "Tp9";
        for (int i = 0; i < 20000; i++) {            
            System.out.println(formatAsLength(("#" + (i + 1)), 10) + 
                    formatAsLength(s1, 7) + " " + 
                    formatAsLength(s2, 12) + " " + 
                    formatAsLength(s3, 10) + " " + 
                    formatAsLength(s4, 12) + " " + 
                    formatAsLength(s5, 10));
            
            if (codes.contains(s1)) {
                throw new Exception("Duplicate code#1: " + s1 + " after generating " + codes.size() + " codes");
            }
            else if (codes.contains(s2)) {
                throw new Exception("Duplicate code#2: " + s2 + " after generating " + codes.size() + " codes");
            }
            else if (codes.contains(s3)) {
                throw new Exception("Duplicate code#3: " + s3 + " after generating " + codes.size() + " codes");
            }
            else if (codes.contains(s4)) {
                throw new Exception("Duplicate code#4: " + s4 + " after generating " + codes.size() + " codes");
            }
            else if (codes.contains(s5)) {
                throw new Exception("Duplicate code#5: " + s5 + " after generating " + codes.size() + " codes");
            }
            
            codes.add(s1);
            codes.add(s2);
            codes.add(s3);
            codes.add(s4);
            codes.add(s5);
            
            s1 = next(s1);
            s2 = next(s2);
            s3 = next(s3);
            s4 = next(s4);
            s5 = next(s5);
        }
        System.out.println("Total time taken: " + (System.currentTimeMillis() - started) + " milli to generate"
                + " " + codes.size() + " codes");
    }
 
    public static String next(String text) {
        int len = text.length();
        if (len == 0) {
            return text;
        }
        boolean alphaNum = false;
        int alphaNumPos = -1;
        for (char c : text.toCharArray()) {
            alphaNumPos++;
            if (Character.isDigit(c) || Character.isLetter(c)) {
                alphaNum = true;
                break;
            }
        }
        StringBuilder buf = new StringBuilder(text);
        if (!alphaNum || alphaNumPos == 0 || alphaNumPos == len) {
            next(buf, buf.length() - 1, alphaNum);
        }
        else {
            String prefix = text.substring(0, alphaNumPos);
            buf = new StringBuilder(text.substring(alphaNumPos));
            next(buf, buf.length() - 1, alphaNum);
            buf.insert(0, prefix);
        }
        return buf.toString();
    }
 
    private static void next(StringBuilder buf, int pos, boolean alphaNum) {
        if (pos == -1) {
            char c = buf.charAt(0);
            String rep = null;
            if (Character.isDigit(c))
                rep = "1";
            else if (Character.isLowerCase(c))
                rep = "a";
            else if (Character.isUpperCase(c))
                rep = "A";
            else
                rep = Character.toString((char) (c + 1));
            buf.insert(0, rep);
            return;
        }

        char c = buf.charAt(pos);
        if (Character.isDigit(c)) {
            if (c == '9') {
                buf.replace(pos, pos + 1, "0");
                next(buf, pos - 1, alphaNum);
            } 
            else {
                buf.replace(pos, pos + 1, Character.toString((char)(c + 1)));
            }
        }
        else if (Character.isLowerCase(c)) {
            if (c == 'z') {
                buf.replace(pos, pos + 1, "a");
                next(buf, pos - 1, alphaNum);
            } 
            else {
                buf.replace(pos, pos + 1, Character.toString((char)(c + 1)));
            }
        } 
        else if (Character.isUpperCase(c)) {
            if (c == 'Z') {
                buf.replace(pos, pos + 1, "A");
                next(buf, pos - 1, alphaNum);
            } 
            else {
                buf.replace(pos, pos + 1, Character.toString((char)(c + 1)));
            }
        } 
        else {
            if (alphaNum) {
                next(buf, pos - 1, alphaNum);
            } 
            else {
                if (c == Character.MAX_VALUE) {
                    buf.replace(pos, pos + 1, Character.toString(Character.MIN_VALUE));
                    next(buf, pos - 1, alphaNum);
                } 
                else {
                    buf.replace(pos, pos + 1, Character.toString((char)(c + 1)));
                }
            }
        }
    }
    
    public static String formatAsLength(String text, Integer minLength) {
        return String.format("%-" + minLength + "s", text);
    }
}



#1        IjKl    P.R.I.T.O.M  {AB374}    {ZZ}{U8U}    Tp9       
#2        IjKm    P.R.I.T.O.N  {AB375}    {ZZ}{U8V}    Tq0       
#3        IjKn    P.R.I.T.O.O  {AB376}    {ZZ}{U8W}    Tq1       
#4        IjKo    P.R.I.T.O.P  {AB377}    {ZZ}{U8X}    Tq2       
#5        IjKp    P.R.I.T.O.Q  {AB378}    {ZZ}{U8Y}    Tq3       
#6        IjKq    P.R.I.T.O.R  {AB379}    {ZZ}{U8Z}    Tq4       
#7        IjKr    P.R.I.T.O.S  {AB380}    {ZZ}{U9A}    Tq5       
#8        IjKs    P.R.I.T.O.T  {AB381}    {ZZ}{U9B}    Tq6       
#9        IjKt    P.R.I.T.O.U  {AB382}    {ZZ}{U9C}    Tq7       
#10       IjKu    P.R.I.T.O.V  {AB383}    {ZZ}{U9D}    Tq8       
#11       IjKv    P.R.I.T.O.W  {AB384}    {ZZ}{U9E}    Tq9       
#12       IjKw    P.R.I.T.O.X  {AB385}    {ZZ}{U9F}    Tr0       
#13       IjKx    P.R.I.T.O.Y  {AB386}    {ZZ}{U9G}    Tr1       
..................................
#19918    JmWm    P.R.J.X.A.N  {AV291}    {AAC}{T4V}   CSf6      
#19919    JmWn    P.R.J.X.A.O  {AV292}    {AAC}{T4W}   CSf7      
#19920    JmWo    P.R.J.X.A.P  {AV293}    {AAC}{T4X}   CSf8      
#19921    JmWp    P.R.J.X.A.Q  {AV294}    {AAC}{T4Y}   CSf9      
#19922    JmWq    P.R.J.X.A.R  {AV295}    {AAC}{T4Z}   CSg0      
#19923    JmWr    P.R.J.X.A.S  {AV296}    {AAC}{T5A}   CSg1      
#19924    JmWs    P.R.J.X.A.T  {AV297}    {AAC}{T5B}   CSg2      
#19925    JmWt    P.R.J.X.A.U  {AV298}    {AAC}{T5C}   CSg3      
#19926    JmWu    P.R.J.X.A.V  {AV299}    {AAC}{T5D}   CSg4      
#19927    JmWv    P.R.J.X.A.W  {AV300}    {AAC}{T5E}   CSg5      
#19928    JmWw    P.R.J.X.A.X  {AV301}    {AAC}{T5F}   CSg6      
#19929    JmWx    P.R.J.X.A.Y  {AV302}    {AAC}{T5G}   CSg7      
#19930    JmWy    P.R.J.X.A.Z  {AV303}    {AAC}{T5H}   CSg8      
#19931    JmWz    P.R.J.X.B.A  {AV304}    {AAC}{T5I}   CSg9      
#19932    JmXa    P.R.J.X.B.B  {AV305}    {AAC}{T5J}   CSh0      
#19933    JmXb    P.R.J.X.B.C  {AV306}    {AAC}{T5K}   CSh1      
#19934    JmXc    P.R.J.X.B.D  {AV307}    {AAC}{T5L}   CSh2      
#19935    JmXd    P.R.J.X.B.E  {AV308}    {AAC}{T5M}   CSh3      
#19936    JmXe    P.R.J.X.B.F  {AV309}    {AAC}{T5N}   CSh4      
#19937    JmXf    P.R.J.X.B.G  {AV310}    {AAC}{T5O}   CSh5      
#19938    JmXg    P.R.J.X.B.H  {AV311}    {AAC}{T5P}   CSh6      
#19939    JmXh    P.R.J.X.B.I  {AV312}    {AAC}{T5Q}   CSh7      
#19940    JmXi    P.R.J.X.B.J  {AV313}    {AAC}{T5R}   CSh8      
#19941    JmXj    P.R.J.X.B.K  {AV314}    {AAC}{T5S}   CSh9      
#19942    JmXk    P.R.J.X.B.L  {AV315}    {AAC}{T5T}   CSi0      
#19943    JmXl    P.R.J.X.B.M  {AV316}    {AAC}{T5U}   CSi1      
#19944    JmXm    P.R.J.X.B.N  {AV317}    {AAC}{T5V}   CSi2      
#19945    JmXn    P.R.J.X.B.O  {AV318}    {AAC}{T5W}   CSi3      
#19946    JmXo    P.R.J.X.B.P  {AV319}    {AAC}{T5X}   CSi4      
#19947    JmXp    P.R.J.X.B.Q  {AV320}    {AAC}{T5Y}   CSi5      
#19948    JmXq    P.R.J.X.B.R  {AV321}    {AAC}{T5Z}   CSi6      
#19949    JmXr    P.R.J.X.B.S  {AV322}    {AAC}{T6A}   CSi7      
#19950    JmXs    P.R.J.X.B.T  {AV323}    {AAC}{T6B}   CSi8      
#19951    JmXt    P.R.J.X.B.U  {AV324}    {AAC}{T6C}   CSi9      
#19952    JmXu    P.R.J.X.B.V  {AV325}    {AAC}{T6D}   CSj0      
#19953    JmXv    P.R.J.X.B.W  {AV326}    {AAC}{T6E}   CSj1      
#19954    JmXw    P.R.J.X.B.X  {AV327}    {AAC}{T6F}   CSj2      
#19955    JmXx    P.R.J.X.B.Y  {AV328}    {AAC}{T6G}   CSj3      
#19956    JmXy    P.R.J.X.B.Z  {AV329}    {AAC}{T6H}   CSj4      
#19957    JmXz    P.R.J.X.C.A  {AV330}    {AAC}{T6I}   CSj5      
#19958    JmYa    P.R.J.X.C.B  {AV331}    {AAC}{T6J}   CSj6      
#19959    JmYb    P.R.J.X.C.C  {AV332}    {AAC}{T6K}   CSj7      
#19960    JmYc    P.R.J.X.C.D  {AV333}    {AAC}{T6L}   CSj8      
#19961    JmYd    P.R.J.X.C.E  {AV334}    {AAC}{T6M}   CSj9      
#19962    JmYe    P.R.J.X.C.F  {AV335}    {AAC}{T6N}   CSk0      
#19963    JmYf    P.R.J.X.C.G  {AV336}    {AAC}{T6O}   CSk1      
#19964    JmYg    P.R.J.X.C.H  {AV337}    {AAC}{T6P}   CSk2      
#19965    JmYh    P.R.J.X.C.I  {AV338}    {AAC}{T6Q}   CSk3      
#19966    JmYi    P.R.J.X.C.J  {AV339}    {AAC}{T6R}   CSk4      
#19967    JmYj    P.R.J.X.C.K  {AV340}    {AAC}{T6S}   CSk5      
#19968    JmYk    P.R.J.X.C.L  {AV341}    {AAC}{T6T}   CSk6      
#19969    JmYl    P.R.J.X.C.M  {AV342}    {AAC}{T6U}   CSk7      
#19970    JmYm    P.R.J.X.C.N  {AV343}    {AAC}{T6V}   CSk8      
#19971    JmYn    P.R.J.X.C.O  {AV344}    {AAC}{T6W}   CSk9      
#19972    JmYo    P.R.J.X.C.P  {AV345}    {AAC}{T6X}   CSl0      
#19973    JmYp    P.R.J.X.C.Q  {AV346}    {AAC}{T6Y}   CSl1      
#19974    JmYq    P.R.J.X.C.R  {AV347}    {AAC}{T6Z}   CSl2      
#19975    JmYr    P.R.J.X.C.S  {AV348}    {AAC}{T7A}   CSl3      
#19976    JmYs    P.R.J.X.C.T  {AV349}    {AAC}{T7B}   CSl4      
#19977    JmYt    P.R.J.X.C.U  {AV350}    {AAC}{T7C}   CSl5      
#19978    JmYu    P.R.J.X.C.V  {AV351}    {AAC}{T7D}   CSl6      
#19979    JmYv    P.R.J.X.C.W  {AV352}    {AAC}{T7E}   CSl7      
#19980    JmYw    P.R.J.X.C.X  {AV353}    {AAC}{T7F}   CSl8      
#19981    JmYx    P.R.J.X.C.Y  {AV354}    {AAC}{T7G}   CSl9      
#19982    JmYy    P.R.J.X.C.Z  {AV355}    {AAC}{T7H}   CSm0      
#19983    JmYz    P.R.J.X.D.A  {AV356}    {AAC}{T7I}   CSm1      
#19984    JmZa    P.R.J.X.D.B  {AV357}    {AAC}{T7J}   CSm2      
#19985    JmZb    P.R.J.X.D.C  {AV358}    {AAC}{T7K}   CSm3      
#19986    JmZc    P.R.J.X.D.D  {AV359}    {AAC}{T7L}   CSm4      
#19987    JmZd    P.R.J.X.D.E  {AV360}    {AAC}{T7M}   CSm5      
#19988    JmZe    P.R.J.X.D.F  {AV361}    {AAC}{T7N}   CSm6      
#19989    JmZf    P.R.J.X.D.G  {AV362}    {AAC}{T7O}   CSm7      
#19990    JmZg    P.R.J.X.D.H  {AV363}    {AAC}{T7P}   CSm8      
#19991    JmZh    P.R.J.X.D.I  {AV364}    {AAC}{T7Q}   CSm9      
#19992    JmZi    P.R.J.X.D.J  {AV365}    {AAC}{T7R}   CSn0      
#19993    JmZj    P.R.J.X.D.K  {AV366}    {AAC}{T7S}   CSn1      
#19994    JmZk    P.R.J.X.D.L  {AV367}    {AAC}{T7T}   CSn2      
#19995    JmZl    P.R.J.X.D.M  {AV368}    {AAC}{T7U}   CSn3      
#19996    JmZm    P.R.J.X.D.N  {AV369}    {AAC}{T7V}   CSn4      
#19997    JmZn    P.R.J.X.D.O  {AV370}    {AAC}{T7W}   CSn5      
#19998    JmZo    P.R.J.X.D.P  {AV371}    {AAC}{T7X}   CSn6      
#19999    JmZp    P.R.J.X.D.Q  {AV372}    {AAC}{T7Y}   CSn7      
#20000    JmZq    P.R.J.X.D.R  {AV373}    {AAC}{T7Z}   CSn8      
Total time taken: 74740 milli to generate 100000 codes

Wednesday, June 3, 2015

Validate URL Using Java & Regex


class UrlValidator {
    public static void main (String[] args) {
        check("http://google.com");
        check("http://google.com?a=b#99");
        check("http://google.com?a=b#99#sty");
        check("http://www.google.com?a=1&b=2 / 3");
        check("http://www.google.com?a=1&orderRate=orderRateUUID");
    }

    public static void check(String url) {
        String Regex = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";

        Boolean matches = url.matches(Regex);

        if(matches) {
            System.out.println("URL (YES): " + url);
        }
        else {
            System.out.println("URL (NOT): " + url);
        }
    }
}


URL (YES): http://google.com
URL (YES): http://google.com?a=b#99
URL (YES): http://google.com?a=b#99#sty
URL (NOT): http://www.google.com?a=1&b=2 / 3
URL (YES): http://www.google.com?a=1&orderRate=orderRateUUID

Wednesday, May 27, 2015

javax.net.ssl.SSLException: Received fatal alert: unexpected_message

This seems like a protocol version mismatch, this exception normally happens when there is a mismatch between SSL protocol version used by the client and the server. your clients should use a protocol version supported by the server.

You could probably enable the SSLv2 protocol at the JVM but that is  is a serious security risk. The clients are using an outdated and insecure protocol and should be updated to TLSv1.1 or TLSv.1.2.

Below is nice solution to resolve the error javax.net.ssl.SSLException: Received fatal alert: unexpected_message.


System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2,SSLv3,SSLv2Hello");

OR

System.setProperty("com.sun.net.ssl.enableECC","false");
System.setProperty("jsse.enableSNIExtension","false");

AND

import javax.net.ssl.*
import java.security.SecureRandom
import java.security.cert.CertificateException
import java.security.cert.X509Certificate;

HttpsURLConnection connection = (HttpsURLConnection) new URL(requestURL).openConnection();
setAcceptAllVerifier(connection);

private static SSLSocketFactory sslSocketFactory = null;

private static void setAcceptAllVerifier(HttpsURLConnection connection) throws Exception {
    if (sslSocketFactory == null) {
        TrustManager trustManager = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        SSLContext sslContext = SSLContext.getInstance("SSLv3");
        sslContext.init(null, trustManager as TrustManager[], new SecureRandom());
        sslSocketFactory = sslContext.getSocketFactory();
    }
    connection.setSSLSocketFactory(sslSocketFactory);
    connection.setHostnameVerifier(ALL_TRUSTING_HOSTNAME_VERIFIER);
}

private static final HostnameVerifier ALL_TRUSTING_HOSTNAME_VERIFIER = new HostnameVerifier() {
    public boolean verify(String hostname, SSLSession session) {
        return true;
    }
};

Sunday, May 17, 2015

Make A Copy Of A Pdf File Using Java

package com.pkm.concat.two.pdf;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * Created by pritom on 17/05/2015.
 */
public class FileToByteToFile {
    public static void main(String[] args) throws Exception {
        File file = new File("original.pdf");
        FileInputStream fileInputStream = new FileInputStream(file);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        for (int readNum; (readNum = fileInputStream.read(bytes)) != -1;) {
            byteArrayOutputStream.write(bytes, 0, readNum);
        }
        byte[] bytesRead = byteArrayOutputStream.toByteArray();
        File outputFile = new File("Duplicate-" + file.getName().toLowerCase());
        FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
        fileOutputStream.write(bytesRead);
        fileOutputStream.flush();
        fileOutputStream.close();
    }
}

Concat Or Join Or Add Two Or More Pdf File To One Pdf FIle Using Java & Lowagie


package com.pkm.concat.two.pdf;

import java.io.*;
import com.lowagie.text.Document;
import com.lowagie.text.PageSize;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfWriter;

/**
 * Created by pritom on 17/05/2015.
 */
public class ConcatTwoPdfBytes {
    public static void main(String[] args) throws Exception {
        File file = new File("from-1.pdf");
        FileInputStream fileInputStream = new FileInputStream(file);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        Document document = new Document();
        Rectangle rectangle = PageSize.A4;
        document.setPageSize(rectangle);
        PdfWriter pdfWriter = PdfWriter.getInstance(document, byteArrayOutputStream);
        document.open();
        PdfContentByte cb = pdfWriter.getDirectContent();

        PdfReader pdfReader = new PdfReader(fileInputStream);
        for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {
            document.newPage();
            PdfImportedPage page = pdfWriter.getImportedPage(pdfReader, i);
            cb.addTemplate(page, 0, 0);
        }

        File file2 = new File("from-2.pdf");
        fileInputStream = new FileInputStream(file2);
        pdfReader = new PdfReader(fileInputStream);
        for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {
            document.newPage();
            PdfImportedPage page = pdfWriter.getImportedPage(pdfReader, i);
            cb.addTemplate(page, 0, 0);
        }
        document.close();

        byte[] bytesRead = byteArrayOutputStream.toByteArray();
        File outputFile = new File(file.getName() + " And  " + file2.getName());
        FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
        fileOutputStream.write(bytesRead);
        fileOutputStream.flush();
        fileOutputStream.close();
    }
}


from-1.pdf from-2.pdf from-1.pdf And from-2.pdf Download Jar

Saturday, May 16, 2015

Java Create Watermark Text Or Fill Area To An Image


package com.pkm;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

public class WatermarkTextToImage {
    public static void main(String[] args) throws Exception {
 ImageIcon photo = new ImageIcon("100_6929.jpg");
 BufferedImage bufferedImage = new BufferedImage(photo.getIconWidth(),
  photo.getIconHeight(),
  BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = (Graphics2D) bufferedImage.getGraphics();

        g2d.drawImage(photo.getImage(), 0, 0, null);

        AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f);
        g2d.setComposite(alpha);

        g2d.setColor(Color.white);
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
         RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        g2d.setFont(new Font("Arial", Font.BOLD, 100));

        String watermark = "Pritom Kumar Mondal";

        FontMetrics fontMetrics = g2d.getFontMetrics();
        Rectangle2D rect = fontMetrics.getStringBounds(watermark, g2d);

        g2d.drawString(watermark,
         (photo.getIconWidth() - (int) rect.getWidth()) / 2,
         (photo.getIconHeight() - (int) rect.getHeight()) / 2);

        alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.2f);
        g2d.setComposite(alpha);
        g2d.setColor(Color.red);
        g2d.fillOval(0, 0, photo.getIconWidth(), photo.getIconHeight());

        //Free graphic resources
        ImageIO.write(bufferedImage, "JPEG", new File("100_6929_Watermark.JPG"));
        g2d.dispose();
    }
}

Input & Output Image Respectively

Convert RGB Values Of A Color To A Hexadecimal String And Vice Versa Using jQuery

Hex: RGB:
RGB: Hex:


/* RGB Value To Hexa Decimal */
function toHex(n) {
     n = parseInt(n);
     if (isNaN(n)) return "00";
     n = Math.max(0,Math.min(n,255));
     return "0123456789ABCDEF".charAt((n-n%16)/16)
     + "0123456789ABCDEF".charAt(n%16);
}
toHex("20");

/* Hext Decimal Value To RGB Value */
function hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}
var str = "#34F355";
hexToR(str);
hexToG(str);
hexToB(str);