PageRenderTime 52ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/src/classes/com/sapienter/jbilling/server/util/Util.java

https://github.com/bibulous/SkyrackJbill2.2
Java | 346 lines | 244 code | 39 blank | 63 comment | 55 complexity | 3f327c5c54021da115cce367286ed741 MD5 | raw file
  1. /*
  2. jBilling - The Enterprise Open Source Billing System
  3. Copyright (C) 2003-2009 Enterprise jBilling Software Ltd. and Emiliano Conde
  4. This file is part of jbilling.
  5. jbilling is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU Affero General Public License as published by
  7. the Free Software Foundation, either version 3 of the License, or
  8. (at your option) any later version.
  9. jbilling is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU Affero General Public License for more details.
  13. You should have received a copy of the GNU Affero General Public License
  14. along with jbilling. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. /*
  17. * Created on Aug 11, 2004
  18. */
  19. package com.sapienter.jbilling.server.util;
  20. import java.math.BigDecimal;
  21. import java.text.DecimalFormat;
  22. import java.text.NumberFormat;
  23. import java.text.ParseException;
  24. import java.text.SimpleDateFormat;
  25. import java.util.Date;
  26. import java.util.Iterator;
  27. import java.util.LinkedList;
  28. import java.util.List;
  29. import java.util.Locale;
  30. import java.util.ResourceBundle;
  31. import org.apache.log4j.Logger;
  32. import com.sapienter.jbilling.common.SessionInternalError;
  33. import com.sapienter.jbilling.server.item.CurrencyBL;
  34. import com.sapienter.jbilling.server.user.UserBL;
  35. import com.sapienter.jbilling.server.util.db.InternationalDescriptionDAS;
  36. import com.sapienter.jbilling.server.util.db.InternationalDescriptionDTO;
  37. import java.math.RoundingMode;
  38. /**
  39. * @author Emil
  40. */
  41. public class Util {
  42. public static final String[] hexLookupTable = {
  43. "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f",
  44. "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f",
  45. "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f",
  46. "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f",
  47. "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f",
  48. "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f",
  49. "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f",
  50. "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f",
  51. "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f",
  52. "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f",
  53. "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af",
  54. "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf",
  55. "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf",
  56. "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df",
  57. "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef",
  58. "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff"
  59. };
  60. public static String formatDate(Date date, Integer userId)
  61. throws SessionInternalError {
  62. Locale locale;
  63. try {
  64. UserBL user = new UserBL(userId);
  65. locale = user.getLocale();
  66. } catch (Exception e) {
  67. throw new SessionInternalError(e);
  68. }
  69. ResourceBundle bundle = ResourceBundle.getBundle("entityNotifications",
  70. locale);
  71. SimpleDateFormat df = new SimpleDateFormat(
  72. bundle.getString("format.date"));
  73. return df.format(date);
  74. }
  75. public static String formatMoney(BigDecimal number, Integer userId, Integer currencyId, boolean forEmail)
  76. throws SessionInternalError {
  77. try {
  78. // find first the right format for the number
  79. UserBL user = new UserBL(userId);
  80. Locale locale = user.getLocale();
  81. ResourceBundle bundle = ResourceBundle.getBundle("entityNotifications", locale);
  82. NumberFormat format = NumberFormat.getNumberInstance(locale);
  83. ((DecimalFormat) format).applyPattern(bundle.getString("format.float"));
  84. // now the symbol of the currency
  85. CurrencyBL currency = new CurrencyBL(currencyId);
  86. String symbol = currency.getEntity().getSymbol();
  87. if (symbol.length() >= 4 && symbol.charAt(0) == '&' &&
  88. symbol.charAt(1) == '#') {
  89. if (!forEmail) {
  90. // this is an html symbol
  91. // remove the first two digits
  92. symbol = symbol.substring(2);
  93. // remove the last digit (;)
  94. symbol = symbol.substring(0, symbol.length() - 1);
  95. // convert to a single char
  96. Character ch = (char) Integer.valueOf(symbol).intValue();
  97. symbol = ch.toString();
  98. } else {
  99. symbol = currency.getEntity().getCode();
  100. }
  101. }
  102. return symbol + " " + format.format(number.doubleValue());
  103. } catch (Exception e) {
  104. throw new SessionInternalError(e);
  105. }
  106. }
  107. public static String formatMoney(Float number, Integer userId,
  108. Integer currencyId, boolean forEmail)
  109. throws SessionInternalError {
  110. Locale locale;
  111. try {
  112. // find first the right format for the number
  113. UserBL user = new UserBL(userId);
  114. locale = user.getLocale();
  115. ResourceBundle bundle = ResourceBundle.getBundle("entityNotifications",
  116. locale);
  117. NumberFormat format = NumberFormat.getNumberInstance(locale);
  118. ((DecimalFormat) format).applyPattern(bundle.getString(
  119. "format.float"));
  120. // now the symbol of the currency
  121. CurrencyBL currency = new CurrencyBL(currencyId);
  122. String symbol = currency.getEntity().getSymbol();
  123. if (symbol.length() >= 4 && symbol.charAt(0) == '&' &&
  124. symbol.charAt(1) == '#') {
  125. if (!forEmail) {
  126. // this is an html symbol
  127. // remove the first two digits
  128. symbol = symbol.substring(2);
  129. // remove the last digit (;)
  130. symbol = symbol.substring(0, symbol.length() - 1);
  131. // convert to a single char
  132. Character ch = new Character((char)
  133. Integer.valueOf(symbol).intValue());
  134. symbol = ch.toString();
  135. } else {
  136. symbol = currency.getEntity().getCode();
  137. }
  138. }
  139. return symbol + " " + format.format(number.doubleValue());
  140. } catch (Exception e) {
  141. throw new SessionInternalError(e);
  142. }
  143. }
  144. public static String getPeriodUnitStr(Integer id, Integer language) {
  145. Logger log = Logger.getLogger(Util.class);
  146. InternationalDescriptionDTO inter = ((InternationalDescriptionDAS)
  147. Context.getBean(Context.Name.DESCRIPTION_DAS)).findIt(Constants.TABLE_PERIOD_UNIT, id,
  148. "description", language);
  149. if (inter == null) {
  150. log.debug("Description not set for period unit " + id + " language" +
  151. " " + language);
  152. return null;
  153. }
  154. return inter.getContent();
  155. }
  156. public static double round(double val, int places) {
  157. long factor = (long) Math.pow(10, places);
  158. // Shift the decimal the correct number of places
  159. // to the right.
  160. val = val * factor;
  161. // Round to the nearest integer.
  162. long tmp = Math.round(val);
  163. // Shift the decimal the correct number of places
  164. // back to the left.
  165. return (double) tmp / factor;
  166. }
  167. public static float round(float val, int places) {
  168. return (float) round((double) val, places);
  169. }
  170. public static String decimal2string(BigDecimal arg, Locale loc) {
  171. if (arg == null) return null;
  172. return NumberFormat.getInstance(loc).format(arg);
  173. }
  174. public static String float2string(Float arg, Locale loc) {
  175. if (arg == null) {
  176. return null;
  177. }
  178. NumberFormat nf = NumberFormat.getInstance(loc);
  179. return nf.format(arg);
  180. }
  181. public static String float2string(double arg, Locale loc) {
  182. return float2string(new Float(arg), loc);
  183. }
  184. public static Float string2float (String arg, Locale loc)
  185. throws ParseException {
  186. if (arg == null) {
  187. return null;
  188. }
  189. NumberFormat nf = NumberFormat.getInstance(loc);
  190. return new Float(nf.parse(arg).floatValue());
  191. }
  192. public static String binaryToString(byte[] string) {
  193. int readBytes = string.length;
  194. StringBuffer hexData = new StringBuffer();
  195. for (int i=0; i < readBytes; i++) {
  196. hexData.append(hexLookupTable[0xff & string[i]]);
  197. }
  198. return hexData.toString();
  199. }
  200. public static byte[] stringToBinary(String string) {
  201. byte retValue[] = new byte[string.length()/2];
  202. for (int i=0; i < retValue.length; i++) {
  203. String digit = string.substring(i * 2, (i *2) + 2);
  204. int hex = Integer.parseInt(digit, 16);
  205. byte by = (byte) hex;
  206. retValue[i] = by;
  207. }
  208. return retValue;
  209. }
  210. public static ResourceBundle getEntityNotificationsBundle(Integer userId)
  211. throws SessionInternalError {
  212. UserBL userBL;
  213. ResourceBundle bundle;
  214. try {
  215. userBL = new UserBL(userId);
  216. bundle = ResourceBundle.getBundle("entityNotifications",
  217. userBL.getLocale());
  218. } catch (Exception e) {
  219. throw new SessionInternalError("Error getting user info or resource bundle",
  220. Util.class, e);
  221. }
  222. return bundle;
  223. }
  224. /**
  225. * Basic CSV line splitting that takes quotes into account.
  226. * Doesn't do any error checking, e.g., mis-matched quotes.
  227. */
  228. public static String[] csvSplitLine(String line, char fieldSeparator) {
  229. LinkedList<String> fields = new LinkedList<String>();
  230. boolean inQuote = false; // whether inside a quotation
  231. String field = "";
  232. for (int i = 0; i < line.length(); i++) {
  233. if (line.charAt(i) == '\"') {
  234. if (inQuote && i + 1 != line.length() && line.charAt(i + 1) == '\"') {
  235. field += '\"';
  236. i++; // skip over quote escape
  237. } else {
  238. inQuote = !inQuote;
  239. }
  240. } else if (!inQuote && line.charAt(i) == fieldSeparator) {
  241. fields.add(field);
  242. field = "";
  243. } else {
  244. field += line.charAt(i);
  245. }
  246. }
  247. fields.add(field); // after last ','
  248. return fields.toArray(new String[0]);
  249. }
  250. /**
  251. * Joining by separator after each 'not last' value
  252. *
  253. * @param lst list for joining
  254. * @param separator separator string
  255. * @return joined string
  256. */
  257. public static String join(List<String> lst, String separator) {
  258. if (lst == null) return "";
  259. StringBuilder str = new StringBuilder();
  260. Iterator<String> iter = lst.iterator();
  261. while (iter.hasNext()) {
  262. str.append(iter.next());
  263. if (iter.hasNext()) {
  264. str.append(separator);
  265. }
  266. }
  267. return str.toString();
  268. }
  269. /**
  270. * Basic CSV line concatination with characters escaping
  271. *
  272. * @param values values for concatination
  273. * @param fieldSeparator character for fields separation
  274. * @return concatinated string
  275. */
  276. public static String concatCsvLine(List<String> values, String fieldSeparator) {
  277. if (values == null || values.isEmpty()) return null;
  278. StringBuilder builder = new StringBuilder(escapeStringForCsvFormat(values.get(0), fieldSeparator));
  279. for (int i = 1; i < values.size(); i++) {
  280. //add separator for 'not last' element
  281. builder.append(fieldSeparator);
  282. builder.append(escapeStringForCsvFormat(values.get(i), fieldSeparator));
  283. }
  284. return builder.toString();
  285. }
  286. private static String escapeStringForCsvFormat(String str, String fieldSeparator) {
  287. if (str == null) return "";
  288. //is escaping fieldSeparators and line separators by quotes needed
  289. boolean inQuotes = str.indexOf(fieldSeparator) != -1 || str.indexOf('\n') != -1;
  290. StringBuilder builder = new StringBuilder();
  291. if (inQuotes) builder.append('\"');
  292. for (int i = 0; i < str.length(); i++) {
  293. char ch = str.charAt(i);
  294. //escaping quote by duplicating it
  295. if (ch == '\"') {
  296. builder.append('\"');
  297. }
  298. builder.append(ch);
  299. }
  300. if (inQuotes) builder.append('\"');
  301. return builder.toString();
  302. }
  303. }