com.viettel.util.StringUtils.java Source code

Java tutorial

Introduction

Here is the source code for com.viettel.util.StringUtils.java

Source

 /*
  * Copyright (C) 2012 Viettel Telecom. All rights reserved.
  * VIETTEL PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  */
 package com.viettel.util;

 import java.text.Normalizer;
 import java.text.ParseException;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.regex.Pattern;

 import org.apache.commons.collections.CollectionUtils;
 import org.apache.log4j.Logger;
 import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;

 import com.viettel.util.DateTimeUtils;
 import com.viettel.util.DateUtil;
 import com.viettel.util.ParamUtils;
 import com.viettel.util.security.EncryptionUtil;

 /**
  * @author binhnt22@viettel.com.vn
  * @since May 2012
  * @version 1.1
  */
 public final class StringUtils {
     private static Logger LOGGER = Logger.getLogger(StringUtils.class);
     /**
      * alphabeUpCaseNumber.
      */
     private static String alphabeUpCaseNumber = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
     private static String mask = "0123456789_aA?bBcCdD?eE?fFgGhHiI?IHjJkKlLmMnNoO????pPqQrRsStTuUvVwWxXyY?zZ";
     private static String maskEN = "0123456789_aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ";

     // source array, order ascending UTF-8 code
public static char[] SOURCE_CHARACTERS = { '', '?', '', '', '', '', '', '', '?', '', '', '', '', '',
      '', '?', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '?',
      '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
      '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
      '?', '', '', '', '', '', '', '', '', '', '', '', '?', '', '?', '?', '', '', '', '', '',
      '', '', '', '', '', '', '', '?', '', '', '', '', '', '', '', '', '', '', '', '', '',
      '', '', '', '', '', '', '', '', '', '', '', '', '', '', '' };

     public static char[] DESTINATION_CHARACTERS = { 'A', 'A', 'A', 'A', 'E', 'E', 'E', 'I', 'I', 'O', 'O', 'O', 'O',
             'U', 'U', 'Y', 'a', 'a', 'a', 'a', 'e', 'e', 'e', 'i', 'i', 'o', 'o', 'o', 'o', 'u', 'u', 'y', 'A', 'a',
             'D', 'd', 'I', 'i', 'U', 'u', 'O', 'o', 'U', 'u', 'A', 'a', 'A', 'a', 'A', 'a', 'A', 'a', 'A', 'a', 'A',
             'a', 'A', 'a', 'A', 'a', 'A', 'a', 'A', 'a', 'A', 'a', 'A', 'a', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e',
             'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'I', 'i', 'I', 'i', 'O', 'o', 'O', 'o', 'O', 'o', 'O', 'o', 'O',
             'o', 'O', 'o', 'O', 'o', 'O', 'o', 'O', 'o', 'O', 'o', 'O', 'o', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U',
             'u', 'U', 'u', 'O', 'U', 'u', 'U', 'u', 'Y', 'y', 'Y', 'y', 'Y', 'y', 'Y', 'y' };

     /**
      * ZERO.
      */
     private static final String c[] = { "<", ">" };
     private static final String expansion[] = { "&lt;", "&gt;" };

     public static char removeVietMarksFast(char ch) {
         char result = ch;
         int index = java.util.Arrays.binarySearch(SOURCE_CHARACTERS, result);
         if (index >= 0) {
             result = DESTINATION_CHARACTERS[index];
         }
         return result;
     }

     public static String removeVietMarksFast(String text) {
         StringBuilder sb = new StringBuilder(text);
         for (int i = 0; i < sb.length(); i++) {
             sb.setCharAt(i, removeVietMarksFast(sb.charAt(i)));
         }
         return sb.toString();
     }

     public static String HTMLEncode(String s) {
         for (int j = 0; j < c.length; j++) {
             s = s.replace(c[j], expansion[j]);
         }
         return s;
     }

     public static String HTMLDecode(String s) {
         String mine = s;
         for (int i = 0; i < c.length; i++) {
             mine.replaceAll(expansion[i], (c[i] + ""));
         }
         return mine;
     }

     /**
      * method compare two string
      *
      * @param str1
      *            String
      * @param str2
      *            String
      * @return boolean
      */
     public static boolean compareString(String str1, String str2) {
         if (str1 == null) {
             str1 = "";
         }
         if (str2 == null) {
             str2 = "";
         }

         if (str1.equals(str2)) {
             return true;
         }
         return false;
     }

     /**
      * method convert long to string
      *
      * @param lng
      *            Long
      * @return String
      * @throws abc
      *             Exception
      */
     public static String convertFromLongToString(Long lng) throws Exception {
         return Long.toString(lng);
     }

     /*
      * @todo: convert from Long array to String array
      */
     public static String[] convertFromLongToString(Long[] arrLong) throws Exception {
         String[] arrResult = new String[arrLong.length];
         for (int i = 0; i < arrLong.length; i++) {
             arrResult[i] = convertFromLongToString(arrLong[i]);
         }
         return arrResult;
     }

     /*
      * @todo: convert from String array to Long array
      */
     public static long[] convertFromStringToLong(String[] arrStr) throws Exception {
         long[] arrResult = new long[arrStr.length];
         for (int i = 0; i < arrStr.length; i++) {
             arrResult[i] = Long.parseLong(arrStr[i]);
         }
         return arrResult;
     }

     /*
      * @todo: convert from String value to Long value
      */
     public static long convertFromStringToLong(String value) throws Exception {
         return Long.parseLong(value);
     }

     /*
      * Check String that containt only AlphabeUpCase and Number Return True if
      * String was valid, false if String was not valid
      */
     public static boolean checkAlphabeUpCaseNumber(String value) {
         boolean result = true;
         for (int i = 0; i < value.length(); i++) {
             String temp = value.substring(i, i + 1);
             if (alphabeUpCaseNumber.indexOf(temp) == -1) {
                 result = false;
                 return result;
             }
         }
         return result;
     }

     public static boolean validString(Object temp) {
         if (temp == null || temp.toString().trim().equals("")) {
             return false;
         }
         return true;
     }

     public static boolean maskVN(String str) {
         for (int i = 0; i < str.length(); i++) {
             if (mask.indexOf(str.charAt(i)) < 0) {
                 return false;
             }
         }
         return true;
     }

     public static boolean maskEN(String str) {
         for (int i = 0; i < str.length(); i++) {
             if (maskEN.indexOf(str.charAt(i)) < 0) {
                 return false;
             }
         }
         if (str.toLowerCase().charAt(0) < 'a' || str.toLowerCase().charAt(0) > 'z') {
             return false;
         }
         return true;
     }

     public static boolean isInteger(String str) {
         if (str == null || !str.matches("[0-9]+$")) {
             return false;
         }
         return true;
     }

     public static String formatString(String str) {
         return " '" + str.trim().toLowerCase() + "'";
     }

     public static String formatLike(String str) {
         return "%" + str.trim().toLowerCase().replaceAll("_", "\\\\_") + "%";
     }

     public static String formatOrder(String str, String direction) {
         return " NLSSORT(" + str + ",'NLS_SORT=vietnamese') " + direction;
     }

     public static String formatDate(Date date) {
         // return " to_date('" + DateTimeUtils.convertDateToString(date,
         // ParamUtils.ddMMyyyy) + "', '" + ParamUtils.ddMMyyyy + "')";
         return DateTimeUtils.convertDateToString(date, ParamUtils.ddMMyyyy);
     }

     public static String removeNumbering(String str) {
         if (CommonUtil.isEmpty(str))
             return str;
         str = str.trim();
         if (str.startsWith("0") || str.startsWith("1") || str.startsWith("2") || str.startsWith("3")
                 || str.startsWith("4") || str.startsWith("5") || str.startsWith("6") || str.startsWith("7")
                 || str.startsWith("8") || str.startsWith("9"))
             return str.replaceFirst("(\\d\\.(\\d.)*)+", "").trim();
         else
             return str;
     }

     public static String formatFunction(String function, String str) {
         return " " + function + "(" + str + ") ";
     }

     public static String formatConstant(String str) {
         String str1 = "";
         int index = 0;
         String alphabe = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
         for (int i = 1; i < str.length(); i++) {
             if (alphabe.indexOf(str.charAt(i)) > 0) {
                 str1 = str1 + str.substring(index, i).toUpperCase() + "_";
                 index = i;
             }
         }
         str1 = str1 + str.substring(index, str.length()).toUpperCase() + "_";
         return str1;
     }

     public static void main(String[] args) {
         System.out.println(formatConstant("raHivePartition"));
     }

     public static boolean isLong(String str) {
         try {
             Long.valueOf(str);
             return true;
         } catch (Exception ex) {
             return false;
         }
     }

     @SuppressWarnings({ "unchecked", "rawtypes" })
     public static boolean containSpecialCharacteristic(String str) {
         if (str == null) {
             return false;
         }
         List lstSpecialCharacteristic = new ArrayList<String>();
         lstSpecialCharacteristic.add("!");
         lstSpecialCharacteristic.add("@");
         lstSpecialCharacteristic.add("#");
         lstSpecialCharacteristic.add("%");
         lstSpecialCharacteristic.add("^");
         lstSpecialCharacteristic.add("&");
         lstSpecialCharacteristic.add("*");
         lstSpecialCharacteristic.add("(");
         lstSpecialCharacteristic.add(")");
         lstSpecialCharacteristic.add(" ");
         for (int i = 0; i < lstSpecialCharacteristic.size(); i++) {
             if (str.contains(lstSpecialCharacteristic.get(i).toString())) {
                 return true;
             }
         }
         return false;
     }

     public static String upperFirstChar(String input) {
         if (isNullOrEmpty(input)) {
             return input;
         }
         return input.substring(0, 1).toUpperCase() + input.substring(1);
     }

     public static boolean isNullOrEmpty(String obj1) {
         return (obj1 == null || "".equals(obj1.trim()));
     }

     public static boolean isLongNullOrEmpty(Long obj1) {
         return (obj1 == null || "0L".equals(obj1));
     }

     public static boolean isDoubleNullOrEmpty(Double obj1) {
         return (obj1 == null || "0D".equals(obj1));
     }

     //
     public static boolean isStringNullOrEmpty(Object obj1) {
         return obj1 == null || obj1.toString().trim().equals("");
     }

     // Convert operator type
     public static String convertTypeOperator(String operator) {
         String opConvert = "";
         if (StringUtils.isNullOrEmpty(operator)) {
             return opConvert;
         }
         switch (operator) {
         case ParamUtils.NAME_EQUAL:
             opConvert = ParamUtils.OP_EQUAL;
             break;
         case ParamUtils.NAME_GREATER:
             opConvert = ParamUtils.OP_GREATER;
             break;
         case ParamUtils.NAME_GREATER_EQUAL:
             opConvert = ParamUtils.OP_GREATER_EQUAL;
             break;
         case ParamUtils.NAME_LESS:
             opConvert = ParamUtils.OP_LESS;
             break;
         case ParamUtils.NAME_LESS_EQUAL:
             opConvert = ParamUtils.OP_LESS_EQUAL;
             break;
         case ParamUtils.NAME_NOT_EQUAL:
             opConvert = ParamUtils.OP_NOT_EQUAL;
             break;
         case ParamUtils.NAME_LIKE:
             opConvert = ParamUtils.OP_LIKE;
             break;
         case ParamUtils.NAME_IN:
             opConvert = ParamUtils.OP_IN;
             break;
         }
         return opConvert;
     }

     public static String getStringDecript(String key) {
         StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
         encryptor.setAlgorithm("PBEWithMD5AndDES");
         encryptor.setPassword(System.getProperty("PASSWORD_ENV_VARIABLE"));
         // encryptor.setPassword(System.getenv("PASSWORD_ENV_VARIABLE"));

         String decrypt = encryptor.decrypt(key);
         return decrypt;
     }

     public static String IntegerToRoman(int n) {
         String roman = "";
         int repeat;
         int magnitude[] = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
         String symbol[] = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
         repeat = n / 1;
         for (int x = 0; n > 0; x++) {
             repeat = n / magnitude[x];
             for (int i = 1; i <= repeat; i++) {
                 roman = roman + symbol[x];
             }
             n = n % magnitude[x];
         }
         return roman;
     }

     public static int toExcelNumber(String name) {
         int number = 0;
         for (int i = 0; i < name.length(); i++) {
             number = number * 26 + (name.charAt(i) - ('A' - 1));
         }
         return number;
     }

     public static String toExcelName(int number) {
         StringBuilder sb = new StringBuilder();
         while (number-- > 0) {
             sb.append((char) ('A' + (number % 26)));
             number /= 26;
         }
         return sb.reverse().toString();
     }

     public static String encryptString(String str) {
         try {
             return EncryptionUtil.encryptToStringAES(str);
         } catch (Exception e) {
             LOGGER.info(e);
             return null;
         }
     }

     public static String unAccent(String s) {
         String temp = Normalizer.normalize(s, Normalizer.Form.NFD);
         Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");
         return pattern.matcher(temp).replaceAll("").replaceAll("?", "D").replaceAll("", "d");
     }

     public static void buidQuery(String name, HashMap<String, Object> searchParams, StringBuilder strQuery,
             Map<String, Object> params, String... prefix) {
         ArrayList<String> arrQuery = new ArrayList<String>();
         SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
         HashMap<String, Object> searchParamsCopy = new HashMap<>(searchParams);
         for (Map.Entry<String, Object> entry : searchParams.entrySet()) {
             String key = entry.getKey();
             Object value = entry.getValue();
             if (value == null || value.toString().equals("")) {
                 searchParamsCopy.remove(key);
             }
         }
         String pref = prefix != null && prefix.length > 0 ? prefix[0] + "." : "";
         for (Map.Entry<String, Object> entry : searchParamsCopy.entrySet()) {
             String key = entry.getKey();

             Object value = entry.getValue();
             /*
              * if (value == null || value.toString().equals("") || (value
              * instanceof Long && 0 >= (int) value)) { continue; }
              */
             if (arrQuery.size() > 0) {
                 arrQuery.add(" AND  ");
             }
             if (value instanceof Date || DateUtil.isValidDateWithFormat(value.toString(), "yyyy-MM-dd")) {
                 try {
                     if (key.startsWith("from")) {
                         String cl = key.replace("from", "");
                         if (searchParamsCopy.containsKey("to" + cl)) {
                             arrQuery.add(String.format("%1$s BETWEEN :%2$s", pref + cl, key));
                             params.put(key, formatter.parse(value.toString()));

                             Object objTo = searchParamsCopy.get("to" + cl);
                             if (objTo != null) {
                                 arrQuery.add(String.format(" AND :%s", "to" + cl));
                                 params.put("to" + cl, formatter.parse(objTo.toString()));
                             }
                         } else {
                             arrQuery.add(String.format("%1$s >= :%2$s", pref + cl, key));
                             params.put(key, formatter.parse(value.toString()));
                         }
                     } else if (key.startsWith("to")) {
                         String cl = key.replace("to", "");
                         if (!searchParamsCopy.containsKey("from" + cl)) {
                             arrQuery.add(String.format("%1$s <= :%2$s", pref + cl, key));
                             params.put(key, formatter.parse(value.toString()));
                         } else {
                             if (arrQuery.size() > 0) {
                                 arrQuery.remove(arrQuery.size() - 1);
                             }
                         }
                     } else {
                         arrQuery.add(String.format("DATE(%1$s) = DATE(:%2$s)", pref + key, key));
                         params.put(key, value + "%");
                     }
                 } catch (ParseException ex) {

                 }
             } else if (value instanceof Number) {
                 if (key.startsWith("and_")) {
                     if (searchParamsCopy.containsKey(key.replace("and_", ""))) {
                         if (!CollectionUtils.isEmpty(arrQuery)) {
                             arrQuery.remove(arrQuery.size() - 1);
                         }
                     }
                 } else if (searchParamsCopy.containsKey("and_" + key)) {
                     arrQuery.add(String.format("(%1$s = :%2$s", pref + key, key));
                     if (value instanceof Integer) {
                         params.put(key, Integer.parseInt(value.toString()));
                     } else if (value instanceof Long) {
                         params.put(key, Long.parseLong(value.toString()));
                     } else if (value instanceof Float) {
                         params.put(key, Float.parseFloat(value.toString()));
                     } else if (value instanceof Double) {
                         params.put(key, Double.parseDouble(value.toString()));
                     }

                     Object obj = searchParamsCopy.get("and_" + key);
                     if (obj != null) {
                         arrQuery.add(String.format(" OR %1$s = :%2$s)", pref + key, "and_" + key));
                         if (value instanceof Integer) {
                             params.put("and_" + key, Integer.parseInt(obj.toString()));
                         } else if (value instanceof Long) {
                             params.put("and_" + key, Long.parseLong(obj.toString()));
                         } else if (value instanceof Float) {
                             params.put("and_" + key, Float.parseFloat(obj.toString()));
                         } else if (value instanceof Double) {
                             params.put("and_" + key, Double.parseDouble(obj.toString()));
                         }
                     }
                 } else {
                     arrQuery.add(String.format("%1$s = :%2$s", pref + key, key));
                     if (value instanceof Integer) {
                         params.put(key, Integer.parseInt(value.toString()));
                     } else if (value instanceof Long) {
                         params.put(key, Long.parseLong(value.toString()));
                     } else if (value instanceof Float) {
                         params.put(key, Float.parseFloat(value.toString()));
                     } else if (value instanceof Double) {
                         params.put(key, Double.parseDouble(value.toString()));
                     }
                 }
             } else if (value instanceof String) {
                 if (key.startsWith("and_")) {
                     if (searchParamsCopy.containsKey(key.replace("and_", ""))) {
                         if (arrQuery.size() > 0) {
                             arrQuery.remove(arrQuery.size() - 1);
                         }
                     }
                 } else if (searchParamsCopy.containsKey("and_" + key)) {
                     arrQuery.add(String.format("(LOWER(%1$s) like LOWER(:%2$s)", pref + key, key));
                     params.put(key, "%" + value + "%");

                     Object obj = searchParamsCopy.get("and_" + key);
                     if (obj != null) {
                         arrQuery.add(String.format(" OR LOWER(%1$s) LIKE LOWER(:%2$s))", pref + key, "and_" + key));
                         params.put("and_" + key, "%" + obj + "%");
                     }
                 } else if (key.startsWith("in_cond_")) {
                     String cl = key.replace("in_cond_", "");
                     arrQuery.add(String.format("%1$s IN (%2$s)", pref + cl, value.toString()));
                     params.remove(key);
                 } else if (key.startsWith("not_in_cond_")) {
                     String cl = key.replace("not_in_cond_", "");
                     arrQuery.add(String.format("%1$s NOT IN (%2$s)", pref + cl, value.toString()));
                     params.remove(key);
                 } else {
                     arrQuery.add(String.format("LOWER(%1$s) LIKE LOWER(:%2$s)", pref + key, key));
                     params.put(key, "%" + value + "%");
                 }
             }
         }
         strQuery.append(String.join("", arrQuery));
     }
 }