November 17, 2014

Java DES Encryption/Descryption Example

Sometimes we need to encrypt data and save it for later usage.

I have tried several ways and I found a suitable way for my situation that may not fit for others.
I have used the DES (AES may have more features)

Here is my example:
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.spec.KeySpec;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.apache.commons.io.IOUtils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class DESEncryptionSample2 {

    private static final String UNICODE_FORMAT = "UTF8";
    public static final String DES_ENCRYPTION_SCHEME = "DES";
    private KeySpec myKeySpec;
    private SecretKeyFactory mySecretKeyFactory;
    private Cipher cipher;
    byte[] keyAsBytes;
    private String myEncryptionKey;
    private String myEncryptionScheme;
    SecretKey key;

    public DESEncryptionSample2() throws Exception {
        myEncryptionKey = "ThisIsSecretEncryptionKey";
        myEncryptionScheme = DES_ENCRYPTION_SCHEME;
        keyAsBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
        myKeySpec = new DESKeySpec(keyAsBytes);
        mySecretKeyFactory = SecretKeyFactory.getInstance(myEncryptionScheme);
        cipher = Cipher.getInstance(myEncryptionScheme);
        key = mySecretKeyFactory.generateSecret(myKeySpec);
    }

    /**
     * Method To Encrypt The String
     */
    public String encrypt(String unencryptedString) {
        String encryptedString = null;
        try {
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
            byte[] encryptedText = cipher.doFinal(plainText);
            BASE64Encoder base64encoder = new BASE64Encoder();
            encryptedString = base64encoder.encode(encryptedText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encryptedString;
    }

    /**
     * Method To Decrypt An Ecrypted String
     */
    public String decrypt(String encryptedString) {
        String decryptedText = null;
        try {
            cipher.init(Cipher.DECRYPT_MODE, key);
            BASE64Decoder base64decoder = new BASE64Decoder();
            byte[] encryptedText = base64decoder.decodeBuffer(encryptedString);
            byte[] plainText = cipher.doFinal(encryptedText);
            decryptedText = bytes2String(plainText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return decryptedText;
    }

    /**
     * Returns String From An Array Of Bytes
     */
    private static String bytes2String(byte[] bytes) {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            stringBuffer.append((char) bytes[i]);
        }
        return stringBuffer.toString();
    }

    public static void saveEncrypted(String value) {
        try {
            File file = new File("Encrypted.txt");
            IOUtils.write(value, new FileOutputStream(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String readEncrypted() {
        try {
            File file = new File("Encrypted.txt");
            // return IOUtils.toByteArray(new FileInputStream(file));
            return IOUtils.toString(new FileInputStream(file));
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return null;
    }

    /**
     * Testing the DES Encryption And Decryption Technique
     */
    public static void main(String args[]) throws Exception {
        DESEncryptionSample2 myEncryptor = new DESEncryptionSample2();

        String stringToEncrypt = "10.100.102.5";
        String encrypted = myEncryptor.encrypt(stringToEncrypt);
        System.out.println("Encrypted Value :" + encrypted);
        saveEncrypted(encrypted);

        System.out.println(readEncrypted());

        // String decrypted = myEncryptor.decrypt(encrypted);
        String decrypted = myEncryptor.decrypt(readEncrypted());

        System.out.println("String To Encrypt: " + stringToEncrypt);

        System.out.println("Decrypted Value :" + decrypted);

    }
}

March 24, 2014

Create join table with JPA annotations

Problem:

Need to create a join table in database using JPA annotations so the DATABASE design as follows:
 and it should be like this in JPA level:

Solution:

Default entities implementation:
@Entity
@Table(name="USER")
public class User implements Serializable {
//...

@ManyToOne
@JoinTable(name="USER_GROUP")
Group group;

@Entity
@Table(name="GROUP")
public class Group implements Serializable {
//...

@OneToMany(mappedBy="group")
Set<User> users;

Changes on User entity as follows:

@Entity
@Table(name="USER")
public class User implements Serializable {
//...
@ManyToOne @JoinTable(name="USER_GROUP",     joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "user_id"),     inverseJoinColumns = @JoinColumn(name = "group_id", referencedColumnName = "group_id")) Group group;

Primefaces + EJB + JPA Template Project

The best project template for Primefaces + EJB + JPA and Maven I worked with.



March 23, 2014

Add Microsoft SQL JDBC driver to Maven


1. Download the JDBC driver for Microsoft SQL Server
Visit the MSDN site for SQL Server and download the latest version of the JDBC driver for your operating system.
2. Unzip the package
3. Open a command prompt and switch into the expanded directory where the jar file is located.
4. Execute the following command. Be sure to modify the jar file name and version as necessary:

mvn install:install-file -Dfile=sqljdbc4.jar -Dpackaging=jar -DgroupId=com.microsoft.sqlserver -DartifactId=sqljdbc4 -Dversion=4.0

5. Modify your POM
Include the new dependency by modifying your project’s pom.xml. Add the following dependency:

<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>sqljdbc4</artifactId>
    <version>4.0</version>
</dependency>

March 2, 2014

replace special characters with HTML entities ONLINE

Great website for replace special characters with HTML entities ONLINE

http://www.htmlescape.net/htmlescape_tool.html

Arabic (UTF-8) Characters encoding Issue in JSF applications

Problem:

Some times when you develop a web application using JSF you face issue posting the Arabic characters to application server with different encoding.

Solution:
Create a filter for POST requests that add character encoding to the post request as follow:

@WebFilter("/*")
public class CharacterEncodingFilter implements Filter {

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException   {
     request.setCharacterEncoding("UTF-8");
     chain.doFilter(request, response);
  }

  @override
  public void destroy() {
  }

  @Override
  public void init(FilterConfig arg0) throws ServletException {
  }
}

And for the GET requests you need to update the application server's deployment descriptor.
In glass fish as example, create glassfish-web.xml file under WEB-INF folder and add the following line:


<parameter-encoding default-charset="UTF-8">

February 18, 2014

JSFUtils.java

I will keep updating this file

JSFUtils.java

Maven, EJB, JSF, Primefaces, JPA



How to build an Eclipse project contains:

EJB 3.1 and JSF 2.2 and Primefaces 4 and JPA 2.1

1. Run the following command to create a maven web project

mvn archetype:generate -DgroupId={project-packaging} -DartifactId={project-name} -DpackageName={package-name} -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false


2. Update the generated pom file as the following file:

pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.group.id</groupId>
    <artifactId>com.art.id</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>product name</name>
    <url>product url</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
 
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>6.0</version>
            <scope>provided</scope>
        </dependency>
 
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
 
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>org.eclipse.persistence.jpa</artifactId>
            <version>2.5.1</version>
        </dependency>
 
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.28</version>
        </dependency>
 
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>2.2.0</version>
        </dependency>
 
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>2.2.0</version>
        </dependency>
 
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>2.2.0</version>
        </dependency>
 
        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>4.0</version>
        </dependency>
 
    </dependencies>
 
    <build>
        <finalName>webapp-warfile</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <webResources>
                        <resource>
                            <directory>${basedir}/src/main/java</directory>
                            <targetPath>WEB-INF/classes</targetPath>
                            <includes>
                                <include>**/*.properties</include>
                                <include>**/*.xml</include>
                                <include>**/*.css</include>
                                <include>**/*.html</include>
                            </includes>
                        </resource>
                    </webResources>
                </configuration>
            </plugin>
 
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
 
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <wtpversion>2.0</wtpversion>
                    <jeeversion>6.0</jeeversion>
                    <additionalProjectFacets>
                        <jst.jsf>2.2</jst.jsf>
                        <jst.java>1.7</jst.java>
                        <jpt.jpa>2.1</jpt.jpa>
                        <jst.web>3.1</jst.web>
                    </additionalProjectFacets>
                </configuration>
            </plugin>
 
        </plugins>
    </build>
</project>


3. Then run mvn eclipse:eclipse

Done!

February 4, 2014

التفقيط بلغة جافا Translating Numbers to Arabic Words



I have been assigned to a task about Translating Numbers to Arabic Words in Arabic called "التفقيط".

The assignment was to build a simple Java class that contains the business logic.

I have finished it and hope it will be useful for all.

The Code:

package tafqeet;

public class TafqeetMain {

    public TafqeetMain() {
    }

    final private static String[] units = { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight",
            "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen",
            "Nineteen" };
    final private static String[] tens = { "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty",
            "Ninety" };

    private static String convert(Integer number) {
        if (number < 20) {
            return units[number];
        }
        if (number < 100) {
            return tens[number / 10] + ((number % 10 > 0) ? " " + convert(number % 10) : "");
        }
        if (number < 1000) {
            return units[number / 100] + " Hundred" + ((number % 100 > 0) ? " and " + convert(number % 100) : "");
        }
        if (number < 1000000) {
            return convert(number / 1000) + " Thousand " + ((number % 1000 > 0) ? " " + convert(number % 1000) : "");
        }
        return convert(number / 1000000) + " Million "
                + ((number % 1000000 > 0) ? " " + convert(number % 1000000) : "");
    }

    public static String convertNumberToEnglishWords(String number) throws NumberFormatException {
        Integer i = Integer.parseInt(number);
        return convert(i);

    }

    public static String convertNumberToArabicWords(String number) throws NumberFormatException {

        // check if the input string is number or not
        Double.parseDouble(number);

        // check if its floating point number or not
        if (number.contains(".")) { // yes
            // the number
            String theNumber = number.substring(0, number.indexOf('.'));
            // the floating point number
            String theFloat = number.substring(number.indexOf('.') + 1);
            // check how many digits in the number 1:x 2:xx 3:xxx 4:xxxx 5:xxxxx
            // 6:xxxxxx
            switch (theNumber.length()) {
            case 1:
                return convertOneDigits(theNumber) + " فاصلة " + convertTwoDigits(theFloat);
            case 2:
                return convertTwoDigits(theNumber) + " فاصلة " + convertTwoDigits(theFloat);
            case 3:
                return convertThreeDigits(theNumber) + " فاصلة " + convertTwoDigits(theFloat);
            case 4:
                return convertFourDigits(theNumber) + " فاصلة " + convertTwoDigits(theFloat);
            case 5:
                return convertFiveDigits(theNumber) + " فاصلة " + convertTwoDigits(theFloat);
            case 6:
                return convertSixDigits(theNumber) + " فاصلة " + convertTwoDigits(theFloat);
            default:
                return "";
            }
        }

        else {
            switch (number.length()) {
            case 1:
                return convertOneDigits(number);
            case 2:
                return convertTwoDigits(number);
            case 3:
                return convertThreeDigits(number);
            case 4:
                return convertFourDigits(number);
            case 5:
                return convertFiveDigits(number);
            case 6:
                return convertSixDigits(number);
            default:
                return "";
            }

        }
    }

    // -------------------------------------------

    private static String convertOneDigits(String oneDigit) {
        switch (Integer.parseInt(oneDigit)) {
        case 1:
            return "واحد";
        case 2:
            return "إثنان";
        case 3:
            return "ثلاثه";
        case 4:
            return "أربعه";
        case 5:
            return "خمسه";
        case 6:
            return "سته";
        case 7:
            return "سبعه";
        case 8:
            return "ثمانيه";
        case 9:
            return "تسعه";
        default:
            return "";
        }
    }

    private static String convertTwoDigits(String twoDigits) {
        String returnAlpha = "00";
        // check if the first digit is 0 like 0x
        if (twoDigits.charAt(0) == '0' && twoDigits.charAt(1) != '0') { // yes
            // convert two digits to one
            return convertOneDigits(String.valueOf(twoDigits.charAt(1)));
        } else { // no
            // check the first digit 1x 2x 3x 4x 5x 6x 7x 8x 9x
            switch (getIntVal(twoDigits.charAt(0))) {
            case 1: { // 1x
                if (getIntVal(twoDigits.charAt(1)) == 1) {
                    return "إحدى عشر";
                }
                if (getIntVal(twoDigits.charAt(1)) == 2) {
                    return "إثنى عشر";
                } else {
                    return convertOneDigits(String.valueOf(twoDigits.charAt(1))) + " " + "عشر";
                }
            }
            case 2: // 2x x:not 0
                returnAlpha = "عشرون";
                break;
            case 3: // 3x x:not 0
                returnAlpha = "ثلاثون";
                break;
            case 4: // 4x x:not 0
                returnAlpha = "أريعون";
                break;
            case 5: // 5x x:not 0
                returnAlpha = "خمسون";
                break;
            case 6: // 6x x:not 0
                returnAlpha = "ستون";
                break;
            case 7: // 7x x:not 0
                returnAlpha = "سبعون";
                break;
            case 8: // 8x x:not 0
                returnAlpha = "ثمانون";
                break;
            case 9: // 9x x:not 0
                returnAlpha = "تسعون";
                break;
            default:
                returnAlpha = "";
                break;
            }
        }

        // 20 - 99
        // x0 x:not 0,1
        if (convertOneDigits(String.valueOf(twoDigits.charAt(1))).length() == 0) {
            return returnAlpha;
        } else { // xx x:not 0
            return convertOneDigits(String.valueOf(twoDigits.charAt(1))) + " و " + returnAlpha;
        }
    }

    private static String convertThreeDigits(String threeDigits) {

        // check the first digit x00
        switch (getIntVal(threeDigits.charAt(0))) {

        case 1: { // 100 - 199
            if (getIntVal(threeDigits.charAt(1)) == 0) { // 10x
                if (getIntVal(threeDigits.charAt(2)) == 0) { // 100
                    return "مائه";
                } else { // 10x x: is not 0
                    return "مائه" + " و " + convertOneDigits(String.valueOf(threeDigits.charAt(2)));
                }
            } else {// 1xx x: is not 0
                return "مائه" + " و " + convertTwoDigits(threeDigits.substring(1, 3));
            }
        }
        case 2: { // 200 - 299
            if (getIntVal(threeDigits.charAt(1)) == 0) { // 20x
                if (getIntVal(threeDigits.charAt(2)) == 0) { // 200
                    return "مائتين";
                } else { // 20x x:not 0
                    return "مائتين" + " و " + convertOneDigits(String.valueOf(threeDigits.charAt(2)));
                }
            } else { // 2xx x:not 0
                return "مائتين" + " و " + convertTwoDigits(threeDigits.substring(1, 3));
            }
        }
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
        case 8:
        case 9: { // 300 - 999
            if (getIntVal(threeDigits.charAt(1)) == 0) { // x0x x:not 0
                if (getIntVal(threeDigits.charAt(2)) == 0) { // x00 x:not 0
                    return convertOneDigits(String.valueOf(threeDigits.charAt(1) + "مائه"));
                } else { // x0x x:not 0
                    return convertOneDigits(String.valueOf(threeDigits.charAt(0))) + "مائه" + " و "
                            + convertOneDigits(String.valueOf(threeDigits.charAt(2)));
                }
            } else { // xxx x:not 0
                return convertOneDigits(String.valueOf(threeDigits.charAt(0))) + "مائه" + " و "
                        + convertTwoDigits(threeDigits.substring(1, 3));
            }
        }

        case 0: { // 000 - 099
            if (threeDigits.charAt(1) == '0') { // 00x
                if (threeDigits.charAt(2) == '0') { // 000
                    return "";
                } else { // 00x x:not 0
                    return convertOneDigits(String.valueOf(threeDigits.charAt(2)));
                }
            } else { // 0xx x:not 0
                return convertTwoDigits(threeDigits.substring(1, 3));
            }
        }
        default:
            return "";
        }
    }

    private static String convertFourDigits(String fourDigits) {
        // xxxx
        switch (getIntVal(fourDigits.charAt(0))) {

        case 1: { // 1000 - 1999
            if (getIntVal(fourDigits.charAt(1)) == 0) { // 10xx x:not 0
                if (getIntVal(fourDigits.charAt(2)) == 0) { // 100x x:not 0
                    if (getIntVal(fourDigits.charAt(3)) == 0) { // 1000
                        return "ألف";
                    } else { // 100x x:not 0
                        return "ألف" + " و " + convertOneDigits(String.valueOf(fourDigits.charAt(3)));
                    }
                } else { // 10xx x:not 0
                    return "ألف" + " و " + convertTwoDigits(fourDigits.substring(2, 3));
                }
            } else { // 1xxx x:not 0
                return "ألف" + " و " + convertThreeDigits(fourDigits.substring(1, 4));
            }
        }
        case 2: { // 2000 - 2999
            if (getIntVal(fourDigits.charAt(1)) == 0) { // 20xx
                if (getIntVal(fourDigits.charAt(2)) == 0) { // 200x
                    if (getIntVal(fourDigits.charAt(3)) == 0) { // 2000
                        return "ألفين";
                    } else { // 200x x:not 0
                        return "ألفين" + " و " + convertOneDigits(String.valueOf(fourDigits.charAt(3)));
                    }
                } else { // 20xx x:not 0
                    return "ألفين" + " و " + convertTwoDigits(fourDigits.substring(2, 3));
                }
            } else { // 2xxx x:not 0
                return "ألفين" + " و " + convertThreeDigits(fourDigits.substring(1, 4));
            }
        }
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
        case 8:
        case 9: { // 3000 - 9999
            if (getIntVal(fourDigits.charAt(1)) == 0) { // x0xx x:not 0
                if (getIntVal(fourDigits.charAt(2)) == 0) { // x00x x:not 0
                    if (getIntVal(fourDigits.charAt(3)) == 0) { // x000 x:not 0
                        return convertOneDigits(String.valueOf(fourDigits.charAt(0))) + " ألاف";
                    } else { // x00x x:not 0
                        return convertOneDigits(String.valueOf(fourDigits.charAt(0))) + " ألاف" + " و "
                                + convertOneDigits(String.valueOf(fourDigits.charAt(3)));
                    }
                } else { // x0xx x:not 0
                    return convertOneDigits(String.valueOf(fourDigits.charAt(0))) + " ألاف" + " و "
                            + convertTwoDigits(fourDigits.substring(2, 3));
                }
            } else { // xxxx x:not 0
                return convertOneDigits(String.valueOf(fourDigits.charAt(0))) + " ألاف" + " و "
                        + convertThreeDigits(fourDigits.substring(1, 4));
            }
        }

        default:
            return "";
        }
    }

    private static String convertFiveDigits(String fiveDigits) {
        if (convertThreeDigits(fiveDigits.substring(2, 5)).length() == 0) { // xx000
                                                                            // x:not
                                                                            // 0
            return convertTwoDigits(fiveDigits.substring(0, 2)) + " ألف ";
        } else { // xxxxx x:not 0
            return convertTwoDigits(fiveDigits.substring(0, 2)) + " ألفا " + " و "
                    + convertThreeDigits(fiveDigits.substring(2, 5));
        }
    }

    private static String convertSixDigits(String sixDigits) {

        if (convertThreeDigits(sixDigits.substring(2, 5)).length() == 0) { // xxx000
                                                                           // x:not
                                                                           // 0
            return convertThreeDigits(sixDigits.substring(0, 3)) + " ألف ";
        } else { // xxxxxx x:not 0
            return convertThreeDigits(sixDigits.substring(0, 3)) + " ألفا " + " و "
                    + convertThreeDigits(sixDigits.substring(3, 6));
        }
    }

    private static int getIntVal(char c) {
        return Integer.parseInt(String.valueOf(c));
    }

    // ----------------------------------------------------------

    public static void main(String[] args) {
        System.out.println(TafqeetMain.convertNumberToEnglishWords("123456"));

        System.out.println(TafqeetMain.convertNumberToArabicWords("123412.11"));
    }
}