diff --git a/pom.xml b/pom.xml
index 668a54f..a29b7e5 100644
--- a/pom.xml
+++ b/pom.xml
@@ -43,7 +43,6 @@
* La excepción genérica en el API de SemanticWebBuilder.
*
- * Genera una instancia de esta excepción con un mensaje de detalle
- * especificado.
- *
+ * Genera una instancia de esta excepción con un mensaje de detalle
+ * especificado.
+ *
- * Genera una instancia de esta excepción con el mensaje de detalle y
- * causa especificados.
- *
+ * Genera una instancia de esta excepción con el mensaje de detalle y
+ * causa especificados.
+ *
@@ -162,7 +116,7 @@ public class SWBUtils { * La cadena que representa la ruta física de esta aplicación *
*/ - private static String applicationPath = "" + SWBUtils.class.getResource("/"); + private static String applicationPath = SWBUtils.class.getResource("/").toString(); static { if (applicationPath.endsWith("/")) { @@ -201,13 +155,13 @@ public class SWBUtils { */ public static final String LOCALE_SERVICES = "locale_services"; /** - * Stablishes the logger's output as the one used for {@link System.err} + * Stablishes the logger's output as the one used forSystem.err.
* * Establece la salida del generador de bitácoras, como el mismo que usa * {@code System.err} *
*/ - private static PrintWriter log2File = new PrintWriter(System.err); + private static PrintWriter fileLogWriter = new PrintWriter(System.err); /** * Contains the error elements to show in the administration site's error * viewer. @@ -216,7 +170,7 @@ public class SWBUtils { * administración. * */ - private static ArrayListInicializa las variables de clase necesarias para proveer los servicios de * este objeto.
*/ - /** - * Inits the. - */ private void init() { } @@ -283,7 +230,7 @@ private void init() { * serve */ public static String getApplicationPath() { - return SWBUtils.applicationPath; + return applicationPath; } /** @@ -300,7 +247,6 @@ public static String getApplicationPath() { * */ private static void initLogger() { - String logConf = "log4j.rootLogger=error, stdout" + "\n" + "log4j.appender.stdout=org.apache.log4j.ConsoleAppender" + "\n" + "log4j.appender.stdout.layout=org.apache.log4j.PatternLayout" + "\n" @@ -312,9 +258,9 @@ private static void initLogger() { proper.load(IO.getStreamFromString(logConf)); PropertyConfigurator.configure(proper); } catch (Exception e) { - e.printStackTrace(); + LOG.error("Error loading logging properties"); } - SWBUtils.initLogger = true; + initLogger = true; } /** @@ -331,29 +277,28 @@ private static void initLogger() { * */ private static void initFileLogger() { - try { String logConf = "log4j.rootLogger=info, stdout" + "\n" + "log4j.appender.stdout=org.apache.log4j.ConsoleAppender" + "\n" + "log4j.appender.stdout.layout=org.apache.log4j.PatternLayout" + "\n" + "log4j.appender.stdout.layout.ConversionPattern=%d %p - %m%n" + "\n" + "log4j.logger.org.semanticwb=trace"; - File file = new File(SWBUtils.applicationPath + "/WEB-INF/classes/logging.properties"); + + File file = new File(applicationPath + "/WEB-INF/classes/logging.properties"); if (!file.exists()) { - file = new File(SWBUtils.applicationPath + "/logging.properties"); + file = new File(applicationPath + "/logging.properties"); } - if (file.exists()) { - FileInputStream in = new FileInputStream(file); - logConf = IO.readInputStream(in); - } - logConf = SWBUtils.TEXT.replaceAll(logConf, "{apppath}", SWBUtils.applicationPath); + + FileInputStream in = new FileInputStream(file); + logConf = IO.getStringFromInputStream(in); + logConf = TEXT.replaceAll(logConf, "{apppath}", applicationPath); Properties proper = new Properties(); proper.load(IO.getStreamFromString(logConf)); PropertyConfigurator.configure(proper); } catch (Exception e) { - SWBUtils.log.error("Error: logging.properties not found...", e); + LOG.error("Error: logging.properties not found...", e); } - SWBUtils.initLogger = true; + initLogger = true; } /** @@ -368,12 +313,38 @@ private static void initFileLogger() { * @return a logger related to the class specified */ public static Logger getLogger(Class cls) { - if (!SWBUtils.initLogger) { + if (!initLogger) { initLogger(); } return new Logger4jImpl(cls); } + /** + * Carga los atributos del archivo de manifiesto del JAR asociado a la clase proporcionada. + * + * @return Objeto {@link Attributes} con la información del manifiesto o null si ocurre algún problema + * al cargar el archivo. + */ + public static Attributes loadJarManifestAttributes(Class clazz) { + Attributes attributes = new Attributes(); + if (null != clazz) { + URL resource = clazz.getResource(clazz.getSimpleName() + ".class"); + if (null != resource) { + String classPath = resource.toString(); + if (classPath.startsWith("jar")) { + String manifestPath = classPath.substring(0, classPath.lastIndexOf('!') + 1) + "/META-INF/MANIFEST.MF"; + try (InputStream manifestStream = new URL(manifestPath).openStream()) { + Manifest manifest = new Manifest(manifestStream); + attributes = manifest.getMainAttributes(); + } catch (IOException ignored) { + //Ignored + } + } + } + } + return attributes; + } + /** * Manages the element errors that are shown in the error viewer. *@@ -383,18 +354,18 @@ public static Logger getLogger(Class cls) { public static class ERROR { private ERROR () { } - + /** - * Adds an element to the class variable {@link SWBUtils.errorElement}. If the - * quantity of elements exceeds the {@link SWBUtils.errorElementSize}'s value, - * the last element of {@code SWBUtils.errorElement} is removed. Every element - * is added at the beggining of {@code SWBUtils.errorElement}. + * Adds an element to the class variable {@link #errorElement} If the + * quantity of elements exceeds the {@link #errorElementSize}'s value, + * the last element of {@link #errorElement} is removed. Every element + * is added at the beginning of {@link #errorElement}. *
- * Agrega un elemento a la variable de clase {@code SWBUtils.errorElement}. Si + * Agrega un elemento a la variable de clase {@link #errorElement}. Si * la cantidad de elementos excede el valor de - * {@code SWBUtils.errorElementSize}, el último elemento de - * {@code SWBUtils.errorElement} es eliminado. Cada elemento se agrega al inicio - * de {@code SWBUtils.errorElement}. + * {@link #errorElementSize}, el último elemento de + * {@link #errorElement} es eliminado. Cada elemento se agrega al inicio + * de {@link #errorElement}. *
* * @param msg @@ -407,24 +378,23 @@ private ERROR () { } * a string representing the error element's level */ public static void addError(String msg, Throwable e, Class cls, String level) { - // MAPS74 try removed, shoudn't be an error here - SWBUtils.errorElement.add(0, new ErrorElement(e, msg, cls, level)); - if (SWBUtils.errorElement.size() > SWBUtils.errorElementSize) { - SWBUtils.errorElement.remove(SWBUtils.errorElementSize); + errorElement.add(0, new ErrorElement(e, msg, cls, level)); + if (errorElement.size() > errorElementSize) { + errorElement.remove(errorElementSize); } } /** - * Retrieves the {@code SWBUtils.errorElement}'s iterator, whose size is defined - * by the class member {@code SWBUtils.errorElementSize}. + * Retrieves the {@link #errorElement}'s iterator, whose size is defined + * by the class member {@link #errorElementSize}. *
- * Regresa el iterador de {@code SWBUtils.errorElement}, cuyo tamaño está
- * definido por la variable de clase {@code SWBUtils.errorElementSize}.
+ * Regresa el iterador de {@link #errorElement}, cuyo tamaño está
+ * definido por la variable de clase {@link #errorElementSize}.
*
* @return the error elements
*/
public static Iterator
* Especifica el valor para el código de caracteres ISO8859-1. *
*/ + //TODO: Remove this harcoded charset name public static final String CHARSET_ISO8859_1 = "ISO8859_1"; /** * Specifies the value for the charset UTF-8 @@ -481,6 +452,7 @@ private TEXT() {} * Especifica el valor para el código de caracteres UTF-8. * */ + //TODO: Remove this harcoded charset name public static final String CHARSET_UTF8 = "UTF8"; /** * Stores the name of the character encoding used by default. @@ -489,13 +461,22 @@ private TEXT() {} * */ private static String defencoding = null; + /** + * a string that contains all characters in the english alphabet and the 10 + * digits. + *+ * una string que contiene todos los caracteres del alfabeto inglés y los + * 10 dígitos del sistema decimal. + *
+ * Used to generate strings with characters selected randomly. + */ + private final static String ALPHABETH = "ABCDEFGHiJKLMNPQRSTUVWXYZ123456789+=?"; - private static SimpleDateFormatTS formatter = new SimpleDateFormatTS("MMMM"); - private static SimpleDateFormatTS iso8601dateFormat1 = new SimpleDateFormatTS("yyyy-MM-dd'T'HH:mm:ss'.'SSS"); - private static SimpleDateFormatTS iso8601dateFormat2 = new SimpleDateFormatTS("yyyy-MM-dd'T'HH:mm:ss"); - private static SimpleDateFormatTS iso8601dateFormat3 = new SimpleDateFormatTS("yyyy-MM-dd"); - public static final SimpleDateFormatTS iso8601dateFormat4 = new SimpleDateFormatTS("yyyy-MM"); - public static final SimpleDateFormatTS iso8601dateFormat5 = new SimpleDateFormatTS("yyyy"); + //TODO: Refactor SimpleDateFormatTS attributes to use Java DateTimeFormatter class + public static final SimpleDateFormatTS formatter = new SimpleDateFormatTS("MMMM"); + public static final SimpleDateFormatTS iso8601Full = new SimpleDateFormatTS("yyyy-MM-dd'T'HH:mm:ss'.'SSS"); + public static final SimpleDateFormatTS iso8601Long = new SimpleDateFormatTS("yyyy-MM-dd'T'HH:mm:ss"); + public static final SimpleDateFormatTS iso8601Short = new SimpleDateFormatTS("yyyy-MM-dd"); /** * Given a string specifying a charset, returns the value of @@ -529,69 +510,108 @@ private TEXT() {} * {@value #CHARSET_ISO8859_1} * */ + //TODO: Check why this method is necessary in Distributor.java public static String getHomCharSet(String charset) { - - String ret = SWBUtils.TEXT.CHARSET_ISO8859_1; + String ret = TEXT.CHARSET_ISO8859_1; if (charset.toUpperCase().indexOf("UTF") > -1) { - ret = SWBUtils.TEXT.CHARSET_UTF8; + ret = TEXT.CHARSET_UTF8; } return ret; } /** + * @deprecated This method was only used in Banner.java to encode a query string. + * Use {@link URLEncoder} instead. + * * Encode URLChars 4 Cross Site Scripting - * - * @param txt - * @return + * @param urlString the URL to sanitize. + * @return Sanitized URL string. */ - public static String encodeURLChars4CSS(String txt) { - String ret = txt; - ret = ret.replace("\"", "%22"); - ret = ret.replace("'", "%27"); - ret = ret.replace(">", "%3E"); - ret = ret.replace("<", "%3C"); - return ret; + @Deprecated + public static String encodeURLChars4CSS(String urlString) { + if (null != urlString) { + return urlString.replace("\"", "%22") + .replace("'", "%27") + .replace(">", "%3E") + .replace("<", "%3C"); + } + return null; } /** - * Gets the plural. - * - * @param name - * the name - * @return the plural + * Pluralizes an english word using naive rules. + * @param name Word to pluralize. + * @return Pluralized form o word. */ public static String getPlural(String name) { String nname = name; - - if (nname.endsWith("y") && !(nname.endsWith("ay") || nname.endsWith("ey") || nname.endsWith("iy") - || nname.endsWith("oy") || nname.endsWith("uy"))) { - nname = nname.substring(0, nname.length() - 1); - nname += "ies"; - } else if (nname.endsWith("s") || nname.endsWith("z") || nname.endsWith("x") || nname.endsWith("ch") - || nname.endsWith("sh")) { - nname += "es"; - } else if (nname.endsWith("is")) { - nname = nname.substring(0, nname.length() - 2); - nname += "es"; - } else if (nname.endsWith("fe")) { - nname = nname.substring(0, nname.length() - 2); - nname += "ves"; - } else { - nname += "s"; + + if (null != name) { + if (nname.endsWith("y") && !(nname.endsWith("ay") || nname.endsWith("ey") || nname.endsWith("iy") + || nname.endsWith("oy") || nname.endsWith("uy"))) { + nname = nname.substring(0, nname.length() - 1); + nname += "ies"; + } else if (nname.endsWith("s") || nname.endsWith("z") || nname.endsWith("x") || nname.endsWith("ch") + || nname.endsWith("sh")) { + nname += "es"; + } else if (nname.endsWith("is")) { + nname = nname.substring(0, nname.length() - 2); + nname += "es"; + } else if (nname.endsWith("fe")) { + nname = nname.substring(0, nname.length() - 2); + nname += "ves"; + } else { + nname += "s"; + } + return nname; } - return nname; + return null; } /** + * Generates a string of {@code size} characters selected in a random basis. + *+ * Genera una string con {@code size} caracteres seleccionados en orden + * aleatorio. + *
+ * + * @param size the number of characters the resulting string will contain + * @return a string with {@code size} characters selected in a random basis. If + * {@code size} equals zero the returning string will be empty, and if + * {@code size} is less than zero an exception will be thrown. + * @throws NegativeArraySizeException if the {@code size} argument is less than zero. + */ + public static String getRandomString(int size) { + StringBuilder sb = new StringBuilder(size); + for (int i = 0; i < size; i++) { + sb.append(ALPHABETH.charAt((int) (Math.random() * ALPHABETH.length()))); + } + return sb.toString(); + } + + /** + * @deprecated Use {@link #capitalize(String)}. * To upper case. * * @param data * the data * @return the string */ + @Deprecated public static String toUpperCase(String data) { - String letter = data.substring(0, 1); - return letter.toUpperCase() + data.substring(1); + return capitalize(data); + } + + /** + * Capitalizes a String. + * @param data String to capitalize. + * @return Capitalized string. + */ + public static String capitalize(String data) { + if (null != data) { + return data.substring(0, 1).toUpperCase() + data.substring(1); + } + return null; } /** @@ -624,7 +644,7 @@ public static int monthToInt(String month, String language) { try { loc = new Locale(language); } catch (Exception e) { - loc = SWBUtils.locale; + loc = locale; } GregorianCalendar gc = new GregorianCalendar(loc); @@ -650,12 +670,11 @@ public static int monthToInt(String month, String language) { * */ public static String getDafaultEncoding() { - - if (SWBUtils.TEXT.defencoding == null) { + if (defencoding == null) { OutputStreamWriter out = new OutputStreamWriter(new ByteArrayOutputStream()); - SWBUtils.TEXT.defencoding = out.getEncoding(); + defencoding = out.getEncoding(); } - return SWBUtils.TEXT.defencoding; + return defencoding; } /** @@ -679,7 +698,7 @@ public static String getDafaultEncoding() { */ public static String replaceAll(String str, String match, String replace) { String replaceString = (null != replace ? replace : ""); - + if (match == null || match.length() == 0) { return str; } @@ -687,6 +706,7 @@ public static String replaceAll(String str, String match, String replace) { if (match.equals(replaceString)) { return str; } + StringBuilder ret = new StringBuilder(); int i = str.indexOf(match); int y = 0; @@ -722,13 +742,13 @@ public static String replaceAll(String str, String match, String replace) { */ public static String replaceAllIgnoreCase(String str, String match, String replace) { String replaceString = (null != replace ? replace : ""); - + if (match == null || match.length() == 0) { return str; } int i = str.toLowerCase().indexOf(match.toLowerCase()); - int y = 0; + int y; while (i >= 0) { str = str.substring(0, i) + replaceString + str.substring(i + match.length()); y = i + replaceString.length(); @@ -759,7 +779,7 @@ public static String replaceAllIgnoreCase(String str, String match, String repla */ public static String replaceFirstIgnoreCase(String str, String match, String replace) { String replaceString = (null != replace ? replace : ""); - + if (match == null || match.length() == 0) { return str; } @@ -772,6 +792,7 @@ public static String replaceFirstIgnoreCase(String str, String match, String rep } /** + * @deprecated Use format method of {@link #iso8601Full} static attribute * Converts a date into a string with the format * {@literal yyyy-MM-dd'T'HH:mm:ss'.'SSS}. *@@ -786,11 +807,13 @@ public static String replaceFirstIgnoreCase(String str, String match, String rep * representa al date recibido, con el formato * {@literal yyyy-MM-dd'T'HH:mm:ss'.'SSS}. */ + @Deprecated public static String iso8601DateFormat(Date date) { - return iso8601dateFormat1.format(date); + return iso8601Full.format(date); } /** + * @deprecated @deprecated Use parse method of {@link #iso8601Full} static attribute * Converts a string representing a date with the format * {@literal yyyy-MM-dd'T'HH:mm:ss'.'SSS} into a date. *
@@ -811,20 +834,22 @@ public static String iso8601DateFormat(Date date) { * objeto date. *
*/ + @Deprecated public static Date iso8601DateParse(String date) throws ParseException { - SimpleDateFormatTS iso8601dateFormat = null; + //TODO: Remove this method, logic is naive and error prone + SimpleDateFormatTS iso8601dateFormat; if (date.length() > 19) { - iso8601dateFormat = iso8601dateFormat1;// "yyyy-MM-dd'T'HH:mm:ss'.'SSS" - } - if (date.length() > 10) { - iso8601dateFormat = iso8601dateFormat2;// "yyyy-MM-dd'T'HH:mm:ss" + iso8601dateFormat = iso8601Full;// "yyyy-MM-dd'T'HH:mm:ss'.'SSS" + } else if (date.length() > 10) { + iso8601dateFormat = iso8601Long;// "yyyy-MM-dd'T'HH:mm:ss" } else { - iso8601dateFormat = iso8601dateFormat3;// "yyyy-MM-dd" + iso8601dateFormat = iso8601Short;// "yyyy-MM-dd" } return iso8601dateFormat.parse(date); } /** + * @deprecated Method is used only in Distributor.java and code can be written using parseInt directly. * Converts a string in an integer value; if this is not possible, it returns * the integer received. *
@@ -842,10 +867,8 @@ public static Date iso8601DateParse(String date) throws ParseException {
* {@code val}, o {@code defa}, si la conversión no es posible o
* si {@code val} es {@code null}.
*/
+ @Deprecated
public static int getInt(String val, int defa) {
- if (val == null) {
- return defa;
- }
try {
return Integer.parseInt(val);
} catch (Exception e) {
@@ -883,9 +906,7 @@ public static int getInt(String val, int defa) {
* @throws IOException
* Signals that an I/O exception has occurred.
*/
- public static String encode(String data, String enc)
- throws java.io.IOException {
-
+ public static String encode(String data, String enc) throws java.io.IOException {
ByteArrayOutputStream sw = new java.io.ByteArrayOutputStream();
OutputStreamWriter out = new OutputStreamWriter(sw, enc);
out.write(data);
@@ -923,17 +944,14 @@ public static String encode(String data, String enc)
* @throws IOException
* Signals that an I/O exception has occurred.
*/
- public static String decode(String data, String enc)
- throws java.io.IOException {
-
+ public static String decode(String data, String enc) throws java.io.IOException {
ByteArrayInputStream sw = new ByteArrayInputStream(data.getBytes());
InputStreamReader in = new InputStreamReader(sw, enc);
-
StringBuilder ret = new StringBuilder(data.length());
- char[] bfile = new char[SWBUtils.bufferSize];
+ char[] bfile = new char[bufferSize];
int x;
- while ((x = in.read(bfile, 0, SWBUtils.bufferSize)) > -1) {
+ while ((x = in.read(bfile, 0, bufferSize)) > -1) {
ret.append(new String(bfile, 0, x));
}
in.close();
@@ -1009,38 +1027,14 @@ public static String toUpperCaseFL(String str) {
}
/**
- * Replaces accented characters and blank spaces in the string given. Makes the
- * changes in a case sensitive manner, the following are some examples of the
- * changes this method makes:
- *
- * @param txt
- * a string in which the characters are going to be replaced
- * @param replaceSpaces
- * a {@code boolean} indicating if blank spaces are going to be
- * replaced or not
- * @return a string similar to {@code txt} but with neither accented or special
- * characters nor symbols in it. un objeto string similar a {@code txt}
- * pero sin caracteres acentuados o especiales y sin símbolos
- * {@literal Á} is replaced by {@literal A}
- * {@literal Ê} is replaced by {@literal E}
- * {@literal Ï} is replaced by {@literal I}
- * {@literal â} is replaced by {@literal a}
- * {@literal ç} is replaced by {@literal c}
- * {@literal ñ} is replaced by {@literal n}
- * and blank spaces are replaced by underscore characters, any symbol in
- * {@code txt} other than underscore is eliminated including the
- * periods.
- *
- * Reemplaza caracteres acentuados y espacios en blanco en {@code txt}. - * Realiza los cambios respetando caracteres en mayúsculas o - * minúsculas los caracteres en blanco son reemplazados por - * guiones bajos, cualquier símbolo diferente a guión bajo - * es eliminado. - *
+ * Replaces accented charcacters from a String. + * @param in Input string. + * @param replaceSpaces Whether to replace blank spaces. + * @return */ - public static String replaceSpecialCharacters(String txt, boolean replaceSpaces) { - StringBuilder ret = new StringBuilder(); - String aux = txt; + private static String replaceAccentedCharacters(String in, boolean replaceSpaces) { + String aux = in; + aux = aux.replace('Á', 'A'); aux = aux.replace('Ä', 'A'); aux = aux.replace('Å', 'A'); @@ -1111,7 +1105,45 @@ public static String replaceSpecialCharacters(String txt, boolean replaceSpaces) if (replaceSpaces) { aux = aux.replace(' ', '_'); } + + return aux; + } + + /** + * Replaces accented characters and blank spaces in the string given. Makes the + * changes in a case sensitive manner, the following are some examples of the + * changes this method makes:+ * Reemplaza caracteres acentuados y espacios en blanco en {@code txt}. + * Realiza los cambios respetando caracteres en mayúsculas o + * minúsculas los caracteres en blanco son reemplazados por + * guiones bajos, cualquier símbolo diferente a guión bajo + * es eliminado. + *
+ */ + public static String replaceSpecialCharacters(String txt, boolean replaceSpaces) { + StringBuilder ret = new StringBuilder(); + String aux = replaceAccentedCharacters(txt, replaceSpaces); int l = aux.length(); + for (int x = 0; x < l; x++) { char ch = aux.charAt(x); if ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '_' @@ -1123,82 +1155,27 @@ public static String replaceSpecialCharacters(String txt, boolean replaceSpaces) return aux; } - public static String replaceSpecialCharactersForFile(String txt, char ch, boolean replaceSpaces) { - return replaceSpecialCharactersForFile(txt, ch, replaceSpaces, '_'); + /** + * Replaces special characters for a file name, replacing spaces using underscore character. + * @param fileName File name. + * @param ch + * @param replaceSpaces whether to replace blank spaces using underscore. + * @return File name without special characters. + */ + public static String replaceSpecialCharactersForFile(String fileName, char ch, boolean replaceSpaces) { + return replaceSpecialCharactersForFile(fileName, ch, replaceSpaces, '_'); } - public static String replaceSpecialCharactersForFile(String txt, char ch, boolean replaceSpaces, - char wordSeparator) { - String aux = txt; - aux = aux.replace('Á', 'A'); - aux = aux.replace('Ä', 'A'); - aux = aux.replace('Å', 'A'); - aux = aux.replace('Â', 'A'); - aux = aux.replace('À', 'A'); - aux = aux.replace('Ã', 'A'); - - aux = aux.replace('É', 'E'); - aux = aux.replace('Ê', 'E'); - aux = aux.replace('È', 'E'); - aux = aux.replace('Ë', 'E'); - - aux = aux.replace('Í', 'I'); - aux = aux.replace('Î', 'I'); - aux = aux.replace('Ï', 'I'); - aux = aux.replace('Ì', 'I'); - - aux = aux.replace('Ó', 'O'); - aux = aux.replace('Ö', 'O'); - aux = aux.replace('Ô', 'O'); - aux = aux.replace('Ò', 'O'); - aux = aux.replace('Õ', 'O'); - - aux = aux.replace('Ú', 'U'); - aux = aux.replace('Ü', 'U'); - aux = aux.replace('Û', 'U'); - aux = aux.replace('Ù', 'U'); - - aux = aux.replace('Ñ', 'N'); - - aux = aux.replace('Ç', 'C'); - aux = aux.replace('Ý', 'Y'); - - aux = aux.replace('á', 'a'); - aux = aux.replace('à', 'a'); - aux = aux.replace('ã', 'a'); - aux = aux.replace('â', 'a'); - aux = aux.replace('ä', 'a'); - aux = aux.replace('å', 'a'); - - aux = aux.replace('é', 'e'); - aux = aux.replace('è', 'e'); - aux = aux.replace('ê', 'e'); - aux = aux.replace('ë', 'e'); - - aux = aux.replace('í', 'i'); - aux = aux.replace('ì', 'i'); - aux = aux.replace('î', 'i'); - aux = aux.replace('ï', 'i'); - - aux = aux.replace('ó', 'o'); - aux = aux.replace('ò', 'o'); - aux = aux.replace('ô', 'o'); - aux = aux.replace('ö', 'o'); - aux = aux.replace('õ', 'o'); - - aux = aux.replace('ú', 'u'); - aux = aux.replace('ù', 'u'); - aux = aux.replace('ü', 'u'); - aux = aux.replace('û', 'u'); - - aux = aux.replace('ñ', 'n'); - - aux = aux.replace('ç', 'c'); - aux = aux.replace('ÿ', 'y'); - aux = aux.replace('ý', 'y'); - + /** + * Replaces special characters for a file name, replacing spaces using specified word separator. + * @param fileName File name. + * @param ch + * @param replaceSpaces whether to replace blank spaces using underscore. + * @return File name without special characters. + */ + public static String replaceSpecialCharactersForFile(String fileName, char ch, boolean replaceSpaces, char wordSeparator) { + String aux = replaceAccentedCharacters(fileName, replaceSpaces); if (replaceSpaces) { - aux = aux.replace(' ', wordSeparator); } return aux; @@ -1258,11 +1235,8 @@ public static String replaceSpecialCharacters(String txt, char ch, boolean repla * @return the string */ public static String scape4Script(String txt) { - String aux = txt; - aux = aux.replace("'", "\\'"); - aux = aux.replace("\"", """); - - return aux; + return txt.replace("'", "\\'") + .replace("\"", """); } /** @@ -1290,7 +1264,7 @@ public static String cropText(String txt, int size) { * {@code locale} utilizado por defecto. * * - * @param Bundle + * @param bundle * a string specifying the bundle that contains the data to retrieve * @param key * a string indicating the key name whose value is required @@ -1299,7 +1273,7 @@ public static String cropText(String txt, int size) { * {@code key} especificado almacenado en {@code Bundle}. */ public static String getLocaleString(String bundle, String key) { - return getLocaleString(bundle, key, SWBUtils.locale); + return getLocaleString(bundle, key, locale); } /** @@ -1310,7 +1284,7 @@ public static String getLocaleString(String bundle, String key) { * {@code locale} indicado. * * - * @param Bundle + * @param bundle * a string specifying the bundle that contains the data to retrieve * @param key * a string indicating the key name whose value is required @@ -1333,7 +1307,7 @@ public static String getLocaleString(String bundle, String key, Locale locale) { * {@code locale} y {@code loader} indicados. * * - * @param Bundle + * @param bundle * a string specifying the bundle that contains the data to retrieve * @param key * a string indicating the key name whose value is required @@ -1347,7 +1321,6 @@ public static String getLocaleString(String bundle, String key, Locale locale) { * almacenado en {@code Bundle}. */ public static String getLocaleString(String bundle, String key, Locale locale, ClassLoader loader) { - String cad = ""; try { if (loader == null) { @@ -1356,8 +1329,7 @@ public static String getLocaleString(String bundle, String key, Locale locale, C cad = java.util.ResourceBundle.getBundle(bundle, locale, loader).getString(key); } } catch (Exception e) { - SWBUtils.log.error("Error while looking for properties key:" + key + " in " + bundle); - return ""; + LOG.error("Error while looking for properties key:" + key + " in " + bundle); } return cad; } @@ -1375,7 +1347,7 @@ public static String getLocaleString(String bundle, String key, Locale locale, C * @return the locale */ public static Locale getLocale() { - return SWBUtils.locale; + return locale; } /** @@ -1441,7 +1413,7 @@ public static ArrayList+ * Encuentra una subcadena en {@code str} cuya posición debe ser + * posterior a {@code index} y es delimitada por las cadenas {@code pre} y + * {@code pos}. La subcadena encontrada se almacena en {@code arr}. + *
+ * + * @param str + * a string from which a substring is going to be extracted + * @param pre + * a string that precedes the substring to extract from {@code str} + * @param pos + * a string that goes immediatly after the substring to extract from + * {@code str} + * @param index + * the position in {@code str} from which {@code pre} is looked for + * @param arr + * the object in which the substring extracted is going to be stored + * @return the index in {@code str} immediatly after {@code pos}, or -1 if + * {@code pre} is not found in {@code str}. El índice en + * {@code str} inmediatamente después de {@code pos}, o -1 si + * {@code pre} no es encontrado en {@code str}. + * + */ + private static int findInterStr(String str, String pre, String pos, int index, List- * Convierte un entero en un objeto string y le agrega un cero a la izquierda si - * ese entero está formado por un solo dígito. - *
- * - * @param num - * an integer to convert to a string - * @return a string representing the integer received, with a zero preceding the - * integer if it is formed by only one digit. un objeto string que - * representa el entero recibido, con un cero precediendo al valor - * entero si éste está formado solo por un dígito. - */ - private static String dateCeroComp(int num) { - String ret = Integer.toString(num); - if (ret.length() == 1) { - ret = "0" + ret; - } - return ret; - } - /** * Finds in {@code path} the query string contained and extracts all the * parameters and their corrresponding values. Every parameter has associated an @@ -1923,6 +1906,7 @@ public static Map
@@ -1940,13 +1924,36 @@ public static Map
+ * Crea un objeto properties a partir de un archivo cuyo nombre sea el mismo que + * el valor del parámetro {@code name}. + *
+ * + * @param name + * a string representing the name of the file from which the object + * properties is going to be created. + * @return a properties object whose name equals the value of the parameter + * {@code name}. + *+ * un objeto properties cuyo nombre es el mismo que el valor del + * parámetro {@code name}. + *
+ */ + public static Properties getPropertiesFile(String name) { Properties p = new SWBProperties(); try (InputStream in = SWBUtils.class.getResourceAsStream(name)) { - SWBUtils.log.info("-->Loading Property File:" + name); + LOG.info("-->Loading Property File:" + name); p.load(in); } catch (Exception ex) { - SWBUtils.log.error("Error loading property file:" + name, ex); + LOG.error("Error loading property file:" + name, ex); } return p; @@ -2030,13 +2037,13 @@ public static String decodeExtendedCharacters(String str) { /** * Extracts all the text in a HTML document. *- * Extrae todo el texto de un documento HTML. + * Extrae el texto de un documento HTML. *
* * @param txt * a string representing the content of a HTML document * @return a string representing all the text in the HTML document. un objeto - * string que representa todo el texto contenido en el documento HTML. + * string que representa el texto contenido en el documento HTML. * @throws java.io.IOException * if an I/O error occurs. *@@ -2053,7 +2060,6 @@ public static String decodeExtendedCharacters(String str) { * the interrupted exception */ public static String parseHTML(String txt) throws IOException { - String ret = null; if (txt != null) { HTMLParser parser = new HTMLParser(new StringReader(txt)); @@ -2063,12 +2069,14 @@ public static String parseHTML(String txt) throws IOException { } /** + * @deprecated Not intended to be used anymore. * Valida si txt es nulo regresa def de lo contrario regresa txt * * @param txt * @param def * @return */ + @Deprecated public static String nullValidate(String txt, String def) { if (txt == null) { return def; @@ -2077,12 +2085,14 @@ public static String nullValidate(String txt, String def) { } /** + * @deprecated Not intended to be used anymore. * Valida si obj es nulo regresa def de lo contrario regresa txt * * @param txt * @param def * @return */ + @Deprecated public static String nullValidate(Object obj, String txt, String def) { if (obj == null) { return def; @@ -2091,6 +2101,7 @@ public static String nullValidate(Object obj, String txt, String def) { } /** + * @deprecated Use join method of {@link String} class. * Une los elementos del arreglo arr de Strings con el valor * concat * @@ -2100,6 +2111,7 @@ public static String nullValidate(Object obj, String txt, String def) { * valores a concatenar con el valor del parametro concat * @return */ + @Deprecated public static String join(String concat, String[] arr) { StringBuilder ret = new StringBuilder(); for (int x = 0; x < arr.length; x++) { @@ -2110,7 +2122,6 @@ public static String join(String concat, String[] arr) { } return ret.toString(); } - } /** @@ -2122,7 +2133,7 @@ public static String join(String concat, String[] arr) { *
*/ public static class IO { - + private IO () {} /** @@ -2135,7 +2146,7 @@ private IO () {} * */ public static int getBufferSize() { - return SWBUtils.bufferSize; + return bufferSize; } /** @@ -2177,7 +2188,7 @@ public static InputStream getStreamFromString(String str) { * */ public static void copyStream(InputStream in, OutputStream out) throws IOException { - copyStream(in, out, SWBUtils.bufferSize); + copyStream(in, out, bufferSize); } /** @@ -2203,11 +2214,12 @@ public static void copyStream(InputStream in, OutputStream out) throws IOExcepti */ public static void copyStream(InputStream in, OutputStream out, int bufferSize) throws IOException { if (in == null) { - throw new IOException("Input Stream null"); + throw new IOException("Null Input Stream"); } if (out == null) { - throw new IOException("Ouput Stream null"); + throw new IOException("Null Ouput Stream"); } + byte[] bfile = new byte[bufferSize]; int x; while ((x = in.read(bfile, 0, bufferSize)) > -1) { @@ -2219,6 +2231,8 @@ public static void copyStream(InputStream in, OutputStream out, int bufferSize) } /** + * @deprecated Use {@link #getStringFromInputStream(InputStream)}. + * * Reads an input stream and creates a string with that content. ** Lee un objeto inputStream y crea un objeto string con el contenido @@ -2236,7 +2250,30 @@ public static void copyStream(InputStream in, OutputStream out, int bufferSize) * Si el objeto inputStream recibido tiene un valor {@code null}. *
*/ + @Deprecated public static String readInputStream(InputStream in) throws IOException { + return getStringFromInputStream(in); + } + + /** + * Reads an input stream and creates a string with that content. + *+ * Lee un objeto inputStream y crea un objeto string con el contenido + * leído. + *
+ * + * @param in + * an input stream to read its content + * @return a string whose content is the same as for the input stream read. un + * objeto string cuyo contenido es el mismo que el del objeto + * inputStream leído. + * @throws IOException + * if the input stream received is {@code null}. + *+ * Si el objeto inputStream recibido tiene un valor {@code null}. + *
+ */ + public static String getStringFromInputStream(InputStream in) throws IOException { if (in == null) { throw new IOException("Input Stream null"); } @@ -2252,6 +2289,7 @@ public static String readInputStream(InputStream in) throws IOException { } /** + * @deprecated Use {@link #getStringFromReader(Reader)}. * Reads a reader and creates a string with that content. ** Lee un objeto Reader y crea un objeto string con el contenido leído. @@ -2268,7 +2306,29 @@ public static String readInputStream(InputStream in) throws IOException { * Si el objeto inputStream recibido tiene un valor {@code null}. *
*/ + @Deprecated public static String readReader(Reader in) throws IOException { + return getStringFromReader(in); + } + + /** + * Reads a reader and creates a string with that content. + *+ * Lee un objeto Reader y crea un objeto string con el contenido leído. + *
+ * + * @param in + * an input stream to read its content + * @return a string whose content is the same as for the input stream read. un + * objeto string cuyo contenido es el mismo que el del objeto + * inputStream leído. + * @throws IOException + * if the input stream received is {@code null}. + *+ * Si el objeto inputStream recibido tiene un valor {@code null}. + *
+ */ + public static String getStringFromReader(Reader in) throws IOException { if (in == null) { throw new IOException("Input Stream null"); } @@ -2284,6 +2344,7 @@ public static String readReader(Reader in) throws IOException { } /** + * @deprecated Use {@link #getStringFromInputStream(InputStream, String)} * Reads an input stream and creates a string with the content read using the * charset especified by name through {@code enc}. *@@ -2291,7 +2352,7 @@ public static String readReader(Reader in) throws IOException { * utilizando el conjunto de caracteres especificado por nombre a través * de * - * @param inp + * @param in * the input stream to read * @param enc * the charset's name to use for representing the input stream's @@ -2314,26 +2375,51 @@ public static String readReader(Reader in) throws IOException { * @throws IOException * Signals that an I/O exception has occurred. {@code enc}. */ - public static String readInputStream(InputStream inp, String enc) - throws java.io.IOException { + @Deprecated + public static String readInputStream(InputStream in, String enc) throws java.io.IOException { + return getStringFromInputStream(in, enc); + } - if (inp == null) { - throw new IOException("Input Stream null"); + /** + * Reads an input stream and creates a string with the content read using the + * charset especified by name through {@code enc}. + *
+ * Lee un objeto inputStream y crea una cadena con el contenido leído + * utilizando el conjunto de caracteres especificado por nombre a través + * de + * + * @param in + * the input stream to read + * @param enc + * the charset's name to use for representing the input stream's + * content + * @return a string representing the input stream's content with the charset + * specified. un objeto string que representa el contenido del objeto + * inputStream con el conjunto de caracteres especificado. + * @throws java.io.UnsupportedEncodingException + * if {@code enc} is {@code null}. + *
+ * si el valor de {@code enc} es {@code null}. + *
+ * @throws java.io.IOException + * if {@code inp} is {@code null}. + *+ * si el valor de {@code inp} es {@code null}. + *
+ * @throws UnsupportedEncodingException + * the unsupported encoding exception + * @throws IOException + * Signals that an I/O exception has occurred. {@code enc}. + */ + public static String getStringFromInputStream(InputStream in, String enc) throws java.io.IOException { + if (in == null) { + throw new IOException("Null Input Stream"); } if (enc == null) { - throw new UnsupportedEncodingException("Encoding null"); - } - InputStreamReader in = new InputStreamReader(inp, enc); - - StringBuilder ret = new StringBuilder(); - - char[] bfile = new char[SWBUtils.bufferSize]; - int x; - while ((x = in.read(bfile, 0, SWBUtils.bufferSize)) > -1) { - ret.append(new String(bfile, 0, x)); + throw new UnsupportedEncodingException("Null Encoding"); } - in.close(); - return ret.toString(); + InputStreamReader reader = new InputStreamReader(in, enc); + return getStringFromReader(reader); } /** @@ -2360,7 +2446,6 @@ public static String readInputStream(InputStream inp, String enc) * anteriormente. */ public static String normalizePath(String path) { - if (path == null) { return null; } @@ -2368,12 +2453,15 @@ public static String normalizePath(String path) { if (normalized.equals("/.")) { return "/"; } + if (normalized.indexOf('\\') >= 0) { normalized = normalized.replace('\\', '/'); } + if (!normalized.startsWith("/") && normalized.indexOf(':') < 0) { normalized = "/" + normalized; } + do { int index = normalized.indexOf("//"); if (index < 0) { @@ -2417,34 +2505,34 @@ public static String normalizePath(String path) { * */ public static boolean removeDirectory(String path) { - log.trace("removeDirectory:" + path); try { File dir = new File(path); if (dir.exists() && dir.isDirectory()) { File[] listado = dir.listFiles(); - for (int i = 0; i < listado.length; i++) { - if (listado[i].isFile()) { - listado[i].delete(); - } - if (listado[i].isDirectory()) { - String lpath = listado[i].getPath(); - boolean flag = removeDirectory(lpath); - if (flag) { - listado[i].delete(); + if (null != listado) { + for (File fi : listado) { + if (fi.isFile()) { + Files.delete(fi.toPath()); + } else if (fi.isDirectory()) { + String lpath = fi.getPath(); + if (removeDirectory(lpath)) { + Files.delete(fi.toPath()); + } } } } - } - if (dir.isDirectory() && dir.delete()) { + Files.delete(dir.toPath()); return true; } } catch (Exception e) { - log.error("Can't recursively delete " + path, e); + LOG.error("Can't recursively delete " + path, e); } return false; } /** + * @deprecated Use {@link #readFile(String)} + * * Reads the file corresponding to the {@code path} specified. ** Lee el archivo correspondiente a la ruta especificada por {@code path}. @@ -2455,17 +2543,32 @@ public static boolean removeDirectory(String path) { * @return a string with the file's content read, null if the file don't exist * */ + @Deprecated public static String getFileFromPath(String path) { + return readFile(path); + } + + /** + * Reads the file corresponding to the {@code path} specified. + *
+ * Lee el archivo correspondiente a la ruta especificada por {@code path}. + *
+ * + * @param path + * a string representing the path of the file to read. + * @return a string with the file's content read, null if the file don't exist + * + */ + public static String readFile(String path) { String ret = null; - ByteArrayOutputStream out = new ByteArrayOutputStream(); File f = new File(path); if (f.exists()) { - try { - FileInputStream in = new FileInputStream(f); + try (FileInputStream in = new FileInputStream(f)) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); copyStream(in, out); ret = out.toString(); } catch (Exception e) { - log.error("Can't retreive file:" + path, e); + LOG.error("Can't read file:" + path, e); } } return ret; @@ -2526,10 +2629,11 @@ public static long getFileSize(File file) { if (file.isFile()) { ret = file.length(); } else if (file.isDirectory()) { - File []files = file.listFiles(); - for (int x = 0; x < files.length; x++) { - File ch = files[x]; - ret += getFileSize(ch); + File [] files = file.listFiles(); + if (null != files) { + for (File fi : files) { + ret += getFileSize(fi); + } } } return ret; @@ -2550,20 +2654,20 @@ public static long getFileSize(File file) { * */ public static boolean createDirectory(String path) { - boolean ret = false; try { File f = new File(path); if (!f.exists()) { f.mkdirs(); } - ret = true; + return true; } catch (Exception e) { - SWBUtils.log.error(e); + LOG.error(e); } - return ret; + return false; } /** + * @deprecated Use {@link #copyDirectory(String, String)} * Creates a copy of the given pathname's file system substructure. The origen * pathname ({@code source}) must represent a directory's path in the file * system. @@ -2582,15 +2686,74 @@ public static boolean createDirectory(String path) { * succefully or not. * */ + @Deprecated public static boolean copyStructure(String source, String target) { - boolean ret = false; + return copyDirectory(source, target); + } + + /** + * Creates a copy of the given pathname's file system substructure. The origen + * pathname ({@code source}) must represent a directory's path in the file + * system. + *+ * Crea una copia de la subestructura del sistema de archivos de la ruta dada. + * La ruta de origen ({@code source}) debe representar la ruta de un directorio + * en el sistema de archivos. + *
+ * + * @param source + * pathname of the directory to copy. Must not be null. + * @param target + * pathname of the new directory where file system's substructure + * will be copied. Must not be null. + * @return a {@code boolean} indicating if the source directory was copied + * succefully or not. + * + */ + public static boolean copyDirectory(String source, String target) { try { - copyStructure(source, target, false, "", ""); - ret = true; + copyDirectory(source, target, false, "", ""); + return true; } catch (Exception e) { - SWBUtils.log.error(e); + LOG.error(e); } - return ret; + return false; + } + + /** + * @deprecated Use {@link #copyDirectory(String, String, boolean, String, String)} + * Creates a copy of the given pathname's file system substructure and replaces + * a specified path located within the files of that substructure. The origen + * pathname ({@code source}) must represent a directory's path in the file + * system. + *+ * Crea una copia de la subestructura del sistema de archivos de la ruta dada y + * reemplaza una ruta especificada por {@code sourcePath} en el contenido de los + * archivos a copiar. La ruta de origen ({@code source}) debe representar la + * ruta de un directorio en el sistema de archivos. + *
+ * + * @param source + * pathname of the directory to copy. Must not be null. + * @param target + * pathname of the new directory where file system's substructure + * will be copied. Must not be null. + * @param changePath + * a {@code boolean} that indicates if the files' content will be + * parsed. Must not be null. + * @param sourcePath + * a pathname string located in the source files to be replaced by + * {@code targetPath}. Must not be null. + * @param targetPath + * the pathname string to write in the target files in replacement of + * {@code sourcePath} + * @return a {@code boolean} indicating if the source directory was copied + * succefully or not. + * + */ + @Deprecated + public static boolean copyStructure(String source, String target, boolean changePath, String sourcePath, String targetPath) { + return copyDirectory(source, target, changePath, sourcePath, targetPath); } /** @@ -2610,7 +2773,7 @@ public static boolean copyStructure(String source, String target) { * @param target * pathname of the new directory where file system's substructure * will be copied. Must not be null. - * @param ChangePath + * @param changePath * a {@code boolean} that indicates if the files' content will be * parsed. Must not be null. * @param sourcePath @@ -2623,22 +2786,21 @@ public static boolean copyStructure(String source, String target) { * succefully or not. * */ - public static boolean copyStructure(String source, String target, boolean changePath, String sourcePath, - String targetPath) { + public static boolean copyDirectory(String source, String target, boolean changePath, String sourcePath, String targetPath) { try { File ftarget = new File(target); if (!ftarget.exists()) { ftarget.mkdirs(); } File dir = new File(source); - if (dir != null && dir.exists() && dir.isDirectory()) { + if (dir.exists() && dir.isDirectory()) { File[] listado = dir.listFiles(); for (int i = 0; i < listado.length; i++) { try { if (listado[i].isFile()) { File targetFile = new File(target + listado[i].getName()); if (targetFile.length() == 0) { - copy(source + listado[i].getName(), target + listado[i].getName(), changePath, + copyFile(source + listado[i].getName(), target + listado[i].getName(), changePath, sourcePath, targetPath); } } @@ -2646,25 +2808,63 @@ public static boolean copyStructure(String source, String target, boolean change String newpath = listado[i].getPath(); File f = new File(target + listado[i].getName()); f.mkdirs(); - boolean flag = copyStructure(newpath + "/", target + listado[i].getName() + "/", + boolean flag = copyDirectory(newpath + "/", target + listado[i].getName() + "/", changePath, sourcePath, targetPath); if (flag) { listado[i].delete(); } } } catch (Exception e) { - SWBUtils.log.error(e); + LOG.error(e); return false; } } } } catch (Exception e) { - SWBUtils.log.error(e); + LOG.error(e); return false; } return true; } + /** + * @deprecated Use {@link #copyFile(String, String, boolean, String, String)} + * Copies a file to another directory, modifying a path in its content. If + * indicated through {@code ChangePath} the string represented by + * + * @param sourceName + * pathname of the file to copy. Must not be null. + * @param destName + * pathname of the new location of the file to copy. Must not be + * null. + * @param changePath + * a {@code boolean} indicating if the file will be parsed to modify + * its content + * @param sourcePath + * a pathname string in the source file to be replaced + * @param targetPath + * a pathname string that will replace {@code sourcePath} + * @throws IOException + * Signals that an I/O exception has occurred. {@code sourcePath} is + * looked for in the file's content and replaced by + * {@code targetPath}, only if the file to copy has an extension + * like: {@literal html}, {@literal html}, {@literal htm.orig} or + * {@literal html.orig}. + *+ * Copia un archivo a otro directorio, modificando una ruta en su + * contenido. Si se indica a través de {@code ChangePath} el + * objeto string representado en {@code sourcePath} se busca en el + * contenido del archivo y se reemplaza por el representado en + * {@code targetPath}, solo si el archivo a copiar tiene por + * extensión: {@literal html}, {@literal html}, + * {@literal htm.orig} o {@literal html.orig}. + *
+ */ + @Deprecated + public static void copy(String sourceName, String destName, boolean changePath, String sourcePath, String targetPath) throws IOException { + copyFile(sourceName, destName, changePath, sourcePath, targetPath); + } + /** * Copies a file to another directory, modifying a path in its content. If * indicated through {@code ChangePath} the string represented by @@ -2697,29 +2897,23 @@ public static boolean copyStructure(String source, String target, boolean change * {@literal htm.orig} o {@literal html.orig}. * */ - public static void copy(String sourceName, String destName, boolean changePath, String sourcePath, - String targetPath) throws IOException { - + public static void copyFile(String sourceName, String destName, boolean changePath, String sourcePath, String targetPath) throws IOException { File sourceFile = new File(sourceName); File destinationFile = new File(destName); - java.io.FileOutputStream destination = null; - - try (FileInputStream source = new FileInputStream(sourceFile)) { - destination = new FileOutputStream(destinationFile); - if (changePath && (sourceFile.getName().endsWith(".htm") || sourceFile.getName().endsWith(".html") - || sourceFile.getName().endsWith(".html.orig") - || sourceFile.getName().endsWith(".htm.orig"))) { - String content = readInputStream(source); - content = content.replaceAll(sourcePath, targetPath); - copyStream(getStreamFromString(content), destination); - } else { - copyStream(source, destination); - } - - destination.close(); - } catch (Exception e) { - SWBUtils.log.error(e); + FileOutputStream destination; + FileInputStream source = new FileInputStream(sourceFile); + + destination = new FileOutputStream(destinationFile); + if (changePath && (sourceFile.getName().endsWith(".htm") || sourceFile.getName().endsWith(".html") + || sourceFile.getName().endsWith(".html.orig") + || sourceFile.getName().endsWith(".htm.orig"))) { + String content = getStringFromInputStream(source); + content = content.replaceAll(sourcePath, targetPath); + copyStream(getStreamFromString(content), destination); + } else { + copyStream(source, destination); } + destination.close(); } /** @@ -2750,7 +2944,7 @@ public static Object decodeObject(String txt) throws IOException, ClassNotFoundE byte []arr = new byte[txt.length() / 2]; for (int x = 0; x < txt.length(); x += 2) { String val = txt.substring(x, x + 2); - int v = Integer.decode("0x" + val).intValue(); + int v = Integer.decode("0x" + val); if (v > 127) { v = v - 256; } @@ -2787,7 +2981,7 @@ public static String encodeObject(Object obj) throws IOException { s.flush(); s.close(); byte []arr = f.toByteArray(); - String hex = ""; + StringBuilder hex = new StringBuilder(); for (int x = 0; x < arr.length; x++) { int v = arr[x]; if (v < 0) { @@ -2797,49 +2991,36 @@ public static String encodeObject(Object obj) throws IOException { if (val.length() == 1) { val = "0" + val; } - hex += val; + hex.append(val); } - return hex; + return hex.toString(); } - /* + /** * Reads a file and stores the content in an array of bytes.Lee un archivo y * almacena el contenido en un arreglo de bytes
- * + * * @param file the {@code file} to read. Must not be {@code null} - * + * * @return an array of bytes that stores the content of the file specified. *un arreglo de bytes que almecena el contenido del archivo * especificado.
- * + * * @throws java.io.FileNotFoundException if the specified file does not exists. *si el archivo especificado no existe.
- * + * * @throws java.io.IOException if an I/O error occurs while reading the file's * content.si un error de E/S ocurre durante la lectura del contenido del * archivo.
*/ - /** - * Read file. - * - * @param file - * the file - * @return the byte[] - * @throws FileNotFoundException - * the file not found exception - * @throws IOException - * Signals that an I/O exception has occurred. - */ public static byte[] readFile(File file) throws IOException { if (!file.exists()) { - throw new FileNotFoundException("File Not Found..."); + throw new FileNotFoundException(); } - + try (FileInputStream in = new FileInputStream(file)) { - // EHSP2017 - Removed dead code - int len = (int) file.length(); - + byte[] bfile = new byte[len]; int x = 0; int y = 0; @@ -2863,36 +3044,37 @@ public static byte[] readFile(File file) throws IOException { * * @param request * an HTTP request that contains the files to store. - * @param path2Save + * @param destPath * the string representing the pathname where the files are to be * stored * @return an iterator containing the file items detected in the HTTP request. * un objeto iterador que contiene los archivos detectados en la * petición HTTP. */ - public static Iterator* Agrega los archivos recibidos al archivo comprimido especificado. @@ -3047,7 +3228,31 @@ public static boolean isUTF8(File file) throws IOException { * Signals that an I/O exception has occurred. * @author Jorge Jiménez */ + @Deprecated public static void addFilesToExistingZip(File zipFile, File[] files) throws IOException { + addFilesToZip(zipFile, files); + } + + /** + * Adds the files received to the specified zip file. + *
+ * Agrega los archivos recibidos al archivo comprimido especificado. + *
+ * + * @param zipFile + * a compressed file to include some files at + * @param files + * an array of files that will be added to {@code zipFile} + * @throws java.io.IOException + * if some I/O error occurs during data reading or writing. + *+ * si algún error de E/S ocurre durante la lectura o + * escritura de información. + *
+ * @throws IOException + * Signals that an I/O exception has occurred. + */ + public static void addFilesToZip(File zipFile, File[] files) throws IOException { // get a temp file // MAPS74 En Solaris no se vale renombrar un archivo hacia /var/tmp File tempFile = File.createTempFile(zipFile.getName(), null, zipFile.getParentFile()); @@ -3114,7 +3319,7 @@ public static void addFilesToExistingZip(File zipFile, File[] files) throws IOEx * * @param zip * a zipped file - * @param extractTo + * @param destPath * a file that denotes a directory path * @throws java.io.IOException * if an I/O error occurs during reading or writing data. @@ -3126,8 +3331,8 @@ public static void addFilesToExistingZip(File zipFile, File[] files) throws IOEx * Signals that an I/O exception has occurred. * @author Jorge Jiménez */ - public static final void unzip(File zip, File extractTo) throws IOException { - unzip(zip, extractTo, new ArrayList@@ -3359,8 +3558,8 @@ public static void setSMTPSsl(boolean ssl) { * dirección IP del servidor SMTP. *
*/ - public static void setSMTPServer(String smtpserver) { - SWBUtils.EMAIL.smtpserver = smtpserver; + public static void setSMTPServer(String val) { + smtpserver = val; } /** @@ -3370,7 +3569,7 @@ public static void setSMTPServer(String smtpserver) { * the new sMTP port */ public static void setSMTPPort(int port) { - SWBUtils.EMAIL.smtpport = port; + smtpport = port; } /** @@ -3380,7 +3579,7 @@ public static void setSMTPPort(int port) { * the new sMTP tls */ public static void setSMTPTls(boolean tls) { - SWBUtils.EMAIL.smtptls = tls; + smtptls = tls; } /** @@ -3395,7 +3594,7 @@ public static void setSMTPTls(boolean tls) { * la dirección IP del servidor SMTP en uso. */ public static String getSMTPServer() { - return SWBUtils.EMAIL.smtpserver; + return smtpserver; } /** @@ -3404,23 +3603,24 @@ public static String getSMTPServer() { * Fija una cuenta de correo para generar mensajes de correo electrónico. * * - * @param adminEmail + * @param val * a string representing a valid e-mail account. ** un objeto string que representa una cuenta de correo * electrónico válida. *
*/ - public static void setAdminEmail(String adminEmail) { - SWBUtils.EMAIL.adminEmail = adminEmail; + public static void setAdminEmail(String val) { + adminEmail = val; } public static String getAdminEmail() { - return SWBUtils.EMAIL.adminEmail; + return adminEmail; } /** - * Sends an e-mail with the information supplied. The e-mail body can be + * @deprecated Use {@link #sendMail(SWBMail)} + * Sends an e-mail with the information supplied. The e-mail body can be * formatted as HTML or plain text. ** Envía un correo electrónico con la información @@ -3428,22 +3628,22 @@ public static String getAdminEmail() { * texto plano. *
* - * @param fromEmail + * @param senderEmail * a string representing the sender's e-mail account. Must be a valid * e-mail account, otherwise the mail will not be sent. - * @param fromName + * @param senderName * a string representing the sender's name - * @param address + * @param recipients * a collection of the recipients' e-mail accounts. Every element in * the collection is expected to be a valid - * {@link java.mail.internet.InternetAddress}. Must not be null, + * {@link InternetAddress}. Must not be null, * otherwise the mail will not be sent. - * @param ccEmail + * @param ccRecipients * a collection of e-mail accounts to send the email as a copy. Every * element in the collection is expected to be a valid * {@literal java.mail.internet.InternetAddress}. If it is * {@code null}, the mail won't be sent as a carbon copy to anyone. - * @param bccEmail + * @param bccRecipients * a collection of e-mail accounts to send the email as a blind * carbon copy. Every element in the collection is expected to be a * valid {@literal java.mail.internet.InternetAddress}. If it is @@ -3455,7 +3655,7 @@ public static String getAdminEmail() { * a string indicating the content type of the mail. {@literal HTML} * indicates the body has an HTML format, otherwise it will be send * in text plain format. Must not be {@code null}. - * @param data + * @param body * a string containing the e-mail body's text * @param login * a string representing a login name for SMTP server authentication. @@ -3467,68 +3667,27 @@ public static String getAdminEmail() { * a list containing all the attachments for the e-mail. Every * element in the collection is expected to be of type * {@literal org.apache.commons.mail.EmailAttachment}. - * @return a string that at the moment of writing this documentation is equal to - * {@code null}. un objeto string que al momento de escribir esta - * documentación es igual a {@code null}. + * @return the message id of the underlying MimeMessage. See {@link HtmlEmail#send()} */ - public static String sendMail(String fromEmail, String fromName, Collection* Envía un correo electrónico en segundo plano con la * información proporcionada. *
* - * @param fromEmail + * @param senderEmail * a string representing the sender's e-mail account. Must be a valid * e-mail account, if it is equal to {@code null}, the value of * {@code EMAIL.adminEmail} will be used. - * @param fromName + * @param senderName * a string representing the sender's name - * @param address + * @param recipients * a collection of the recipients' e-mail accounts. Every element in * the collection is expected to be a valid - * {@link java.mail.internet.InternetAddress}. Must not be null, + * {@link InternetAddress}. Must not be null, * otherwise the mail will not be sent. - * @param ccEmail + * @param ccRecipients * a collection of e-mail accounts to send the email as a copy. Every * element in the collection is expected to be a valid * {@literal java.mail.internet.InternetAddress}. If it is * {@code null}, the mail won't be sent as a carbon copy to anyone. - * @param bccEmail + * @param bccRecipients * a collection of e-mail accounts to send the email as a blind * carbon copy. Every element in the collection is expected to be a * valid {@literal java.mail.internet.InternetAddress}. If it is @@ -3734,7 +3880,7 @@ public static void sendBGEmail(String toEmail, String subject, String body) thro * a string indicating the content type of the mail. {@literal HTML} * indicates the body has an HTML format, otherwise it will be send * in text plain format. Must not be {@code null}. - * @param data + * @param body * a string containing the e-mail body's text * @param login * a string representing a login name for SMTP server authentication. @@ -3753,64 +3899,98 @@ public static void sendBGEmail(String toEmail, String subject, String body) thro * si ocurre un error durante la creación del nuevo thread * para trabajar en segundo plano. * - * @throws SocketException - * the socket exception */ - public static void sendBGEmail(String fromEmail, String fromName, Collection* Provee varias operaciones comunes que involucran documentos DOM y su @@ -3896,6 +4068,7 @@ public static boolean isValidEmailAddress(String emailAddress) { *
*/ public static class XML { + //TODO: Review class code because several NPE are not cached /** * The only one instance of this object for the entire application. @@ -3915,10 +4088,6 @@ public DocumentBuilderFactory initialValue() { } }; - // /** - // * A DOM object tree producer. - // *Un generador de árboles de objetos DOM.
- // */ /** * Creator of objects of type {@link javax.xml.transform.Transformer} and * {@link javax.xml.transform.Templates}. @@ -4032,13 +4201,13 @@ private XML() { xpathObj = xpathFactory.newXPath(); } catch (Exception e) { - log.error("Error getting DocumentBuilderFactory...", e); + LOG.error("Error getting DocumentBuilderFactory...", e); } try { mTFactory = TransformerFactory.newInstance(); } catch (Exception e) { - log.error("Error getting TransformerFactory...", e); + LOG.error("Error getting TransformerFactory...", e); } } @@ -4084,7 +4253,7 @@ public static String domToXml(Document dom, String encode, boolean indent) { transformer.transform(new DOMSource(dom), streamResult); res = sw.toString(); } catch (Exception e) { - SWBUtils.log.error(e); + LOG.error(e); } return res; } @@ -4145,10 +4314,8 @@ public static String nodeToString(Node node) { Transformer transformer = factory.newTransformer(); transformer.transform(source, result); return stringWriter.getBuffer().toString(); - } catch (TransformerConfigurationException e) { - e.printStackTrace(); } catch (TransformerException e) { - e.printStackTrace(); + LOG.error(e); } return null; } @@ -4170,8 +4337,7 @@ public static String nodeToString(Node node) { * si una circunstancia excepcional ocurre mientras se ejecutan * operaciones DOM. * - * @throws SWBException - * the sWB exception + * */ public static Document copyDom(Document dom) { Document n = getNewDocument(); @@ -4202,7 +4368,7 @@ public static Document xmlToDom(String xml) { ByteArrayInputStream sr = new java.io.ByteArrayInputStream(xml.getBytes()); dom = xmlToDom(sr); } catch (Exception e) { - SWBUtils.log.error(e); + LOG.error(e); } return dom; } @@ -4224,7 +4390,7 @@ public static Document xmlToDom(InputStream xml) { try { dom = xmlToDom(new InputSource(xml)); } catch (Exception e) { - SWBUtils.log.error(e); + LOG.error(e); } return dom; } @@ -4242,9 +4408,10 @@ public static Document xmlToDom(InputStream xml) { * por la fuente de entrada recibida. */ public static Document xmlToDom(InputSource xml) { - DocumentBuilderFactory dbf = null; - DocumentBuilder db = null; + DocumentBuilderFactory dbf; + DocumentBuilder db; Document dom = null; + try { dbf = getDocumentBuilderFactory(); synchronized (dbf) { @@ -4256,7 +4423,7 @@ public static Document xmlToDom(InputSource xml) { dom = copyDom(dom); } } catch (Exception e) { - SWBUtils.log.error(e); + LOG.error(e); } return dom; } @@ -4272,7 +4439,7 @@ public static Document xmlToDom(InputSource xml) { */ public static Document getNewDocument() { DocumentBuilderFactory dbf = getDocumentBuilderFactory(); - DocumentBuilder db = null; + DocumentBuilder db; Document dom = null; try { synchronized (dbf) { @@ -4280,7 +4447,7 @@ public static Document getNewDocument() { } dom = db.newDocument(); } catch (Exception e) { - SWBUtils.log.error(e); + LOG.error(e); } return dom; } @@ -4394,9 +4561,9 @@ public static boolean xmlVerifier(String idschema, org.xml.sax.InputSource schem boolean bOk = false; if (schema == null || xml == null) { if (schema == null) { - SWBUtils.log.error("Error SWBUtils.XMLVerifier(): Schema source is null."); + LOG.error("Error SWBUtils.XMLVerifier(): Schema source is null."); } else { - SWBUtils.log.event("Error SWBUtils.XMLVerifier(): The input document source is null."); + LOG.event("Error SWBUtils.XMLVerifier(): The input document source is null."); } return bOk; } @@ -4458,9 +4625,9 @@ public static boolean xmlVerifier(String idschema, InputStream schema, InputStre boolean bOk = false; if (schema == null || xml == null) { if (schema == null) { - SWBUtils.log.error("Error SWBUtils.XMLVerifier(): Schema stream is null."); + LOG.error("Error SWBUtils.XMLVerifier(): Schema stream is null."); } else { - SWBUtils.log.error("Error SWBUtils.XMLVerifier(): The input document stream is null."); + LOG.error("Error SWBUtils.XMLVerifier(): The input document stream is null."); } return bOk; } @@ -4493,13 +4660,13 @@ public static boolean xmlVerifier(String idschema, InputStream schema, InputStre * {@code java.lang.String}. */ private static boolean xmlVerifierImpl(String sysid, Object objschema, Object objxml) { - + //TODO: Remove this method and dependencies because is not used anywhere. Move code to WBAdmResourceUtils class and migrate to pure java code. boolean bOk = false; if (objschema == null || objxml == null) { if (objschema == null) { - SWBUtils.log.error("Error SWBUtils.XMLVerifier(): Schema is null."); + LOG.error("Error SWBUtils.XMLVerifier(): Schema is null."); } else { - SWBUtils.log.error("Error SWBUtils.XMLVerifier(): The input document is null."); + LOG.error("Error SWBUtils.XMLVerifier(): The input document is null."); } return bOk; } @@ -4533,12 +4700,12 @@ private static boolean xmlVerifierImpl(String sysid, Object objschema, Object ob bOk = verifier.verify((String) objxml); } } catch (org.iso_relax.verifier.VerifierConfigurationException e) { - SWBUtils.log.error("Error SWBUtils.XMLVerifier(): Unable to create a new verifier.", e); + LOG.error("Error SWBUtils.XMLVerifier(): Unable to create a new verifier.", e); } catch (org.xml.sax.SAXException e) { - SWBUtils.log.event("Error SWBUtils.XMLVerifier(): Input document is not wellformed.", e); + LOG.event("Error SWBUtils.XMLVerifier(): Input document is not wellformed.", e); } } catch (Exception e) { - SWBUtils.log.event("Error SWBUtils.XMLVerifier(): Unable to parse schema file.", e); + LOG.event("Error SWBUtils.XMLVerifier(): Unable to parse schema file.", e); } return bOk; } @@ -4597,13 +4764,6 @@ public static boolean xmlVerifierByURL(String sysid, String schema, String xml) * a node to convert * @return a document containing the node's content. * - * @throws SWBException - * if an exceptional situation occurs during creation of the new - * document. - *- * si una situación excepcional ocurre durante la - * creación del nuevo documento. - *
*/ public static Document node2Document(Node node) { // ensures xerces dom @@ -4676,7 +4836,7 @@ public static void domToFile(Document dom, String file, String encode) { osw.flush(); osw.close(); } catch (Exception e) { - SWBUtils.log.error(e); + LOG.error(e); } } @@ -4687,33 +4847,18 @@ public static void domToFile(Document dom, String file, String encode) { * alguno. * */ + //TODO: Check whether a mute error handler is needed or if its a good practice to do this. private static final org.xml.sax.ErrorHandler silentErrorHandler = new org.xml.sax.ErrorHandler() { - - /** - * Method with an empty body. - *- * Método con cuerpo vacío. - *
- */ public void fatalError(org.xml.sax.SAXParseException e) { + } - /** - * Method with an empty body. - *- * Método con cuerpo vacío. - *
- */ public void error(org.xml.sax.SAXParseException e) { + } - /** - * Method with an empty body. - *- * Método con cuerpo vacío. - *
- */ public void warning(org.xml.sax.SAXParseException e) { + } }; @@ -4745,31 +4890,16 @@ public static String replaceXMLChars(String str) { // split tokens StringTokenizer tokenizer = new StringTokenizer(str, " \t@%^&()-+=|\\{}[].;\"<>", true); while (tokenizer.hasMoreTokens()) { - // next token String token = tokenizer.nextToken(); - // replace '\t' by the content of "tabulation" if (token.startsWith("\t")) { ret.append(" "); - continue; - } - - // replace '<' by '<' - if (token.startsWith("<")) { + } else if (token.startsWith("<")) { ret.append("<"); - continue; - } - - // replace '>' by '>' - if (token.startsWith(">")) { + } else if (token.startsWith(">")) { ret.append(">"); - continue; - } - - // replace '&' by '&' - if (token.startsWith("&")) { + } else if (token.startsWith("&")) { ret.append("&"); - continue; } ret.append(token); } @@ -4797,10 +4927,10 @@ public static String replaceXMLChars(String str) { * */ public static String replaceXMLTags(String txt) { - if (txt == null) { return null; } + StringBuilder str = new StringBuilder(txt); for (int x = 0; x < str.length(); x++) { char ch = str.charAt(x); @@ -5113,10 +5243,10 @@ private DB () {} * objeto. */ private static DBConnectionManager getConnectionManager() { - if (SWBUtils.DB.manager == null) { - SWBUtils.DB.manager = new DBConnectionManager(); + if (manager == null) { + manager = new DBConnectionManager(); } - return SWBUtils.DB.manager; + return manager; } /** @@ -5164,7 +5294,7 @@ public static DBConnectionPool getPool(String name) { * datos cuyo nombre concuerda con {@code SWBUtils.DB.defaultPoolName}. */ public static DBConnectionPool getDefaultPool() { - return (DBConnectionPool) getConnectionManager().getPools().get(SWBUtils.DB.defaultPoolName); + return (DBConnectionPool) getConnectionManager().getPools().get(defaultPoolName); } /** @@ -5178,7 +5308,7 @@ public static DBConnectionPool getDefaultPool() { * conexiones a base de datos por defecto. */ public static String getDefaultPoolName() { - return SWBUtils.DB.defaultPoolName; + return defaultPoolName; } /** @@ -5192,7 +5322,7 @@ public static String getDefaultPoolName() { * connection pool. Must not be {@code null}. */ public static void setDefaultPool(String poolName) { - SWBUtils.DB.defaultPoolName = poolName; + defaultPoolName = poolName; } /** @@ -5228,7 +5358,7 @@ public static Connection getNoPoolConnection(String poolName) { * @return Connection from DBPool. */ public static Connection getDefaultConnection(String description) { - return getConnection(SWBUtils.DB.defaultPoolName, description); + return getConnection(defaultPoolName, description); } /** @@ -5243,7 +5373,7 @@ public static Connection getDefaultConnection(String description) { * conexión a base de datos del pool de conexiones por defecto. */ public static Connection getDefaultConnection() { - return getConnection(SWBUtils.DB.defaultPoolName); + return getConnection(defaultPoolName); } /** @@ -5297,7 +5427,7 @@ public static Connection getConnection(String name) { * defecto. */ public static String getDatabaseName() { - return getDatabaseName(SWBUtils.DB.defaultPoolName); + return getDatabaseName(defaultPoolName); } /** @@ -5324,7 +5454,7 @@ public static String getDatabaseName(String poolName) { con.close(); } } catch (Exception e) { - SWBUtils.log.error("Not Database Found...", e); + LOG.error("Not Database Found...", e); } return ret; } @@ -5354,7 +5484,7 @@ public static String getDatabaseName(String poolName) { * */ public static String getDatabaseType() { - return getDatabaseType(SWBUtils.DB.defaultPoolName); + return getDatabaseType(defaultPoolName); } /** @@ -5384,20 +5514,22 @@ public static String getDatabaseType() { * */ public static String getDatabaseType(String poolName) { - String ret = getDatabaseName(poolName); - if (ret.toLowerCase().indexOf("hsql") > -1) { - ret = SWBUtils.DB.DBTYPE_HSQLDB; - } else if (ret.toLowerCase().indexOf("mysql") > -1) { - ret = SWBUtils.DB.DBTYPE_MySQL; - } else if (ret.toLowerCase().indexOf("mssql") > -1) { - ret = SWBUtils.DB.DBTYPE_MsSQL; - } else if (ret.toLowerCase().indexOf("oracle") > -1) { - ret = SWBUtils.DB.DBTYPE_Oracle; - } else if (ret.toLowerCase().indexOf("postgresql") > -1) { - ret = SWBUtils.DB.DBTYPE_PostgreSQL; - } else if (ret.toLowerCase().indexOf("derby") > -1) { - ret = SWBUtils.DB.DBTYPE_Derby; + + if (null != ret) { + if (ret.toLowerCase().contains("hsql")) { + ret = SWBUtils.DB.DBTYPE_HSQLDB; + } else if (ret.toLowerCase().contains("mysql")) { + ret = SWBUtils.DB.DBTYPE_MySQL; + } else if (ret.toLowerCase().contains("mssql")) { + ret = SWBUtils.DB.DBTYPE_MsSQL; + } else if (ret.toLowerCase().contains("oracle")) { + ret = SWBUtils.DB.DBTYPE_Oracle; + } else if (ret.toLowerCase().contains("postgresql")) { + ret = SWBUtils.DB.DBTYPE_PostgreSQL; + } else if (ret.toLowerCase().contains("derby")) { + ret = SWBUtils.DB.DBTYPE_Derby; + } } return ret; } @@ -5465,14 +5597,14 @@ public static PoolConnectionTimeLock getTimeLock() { */ public static class CryptoWrapper { private static SecureRandom sr = null; - + private CryptoWrapper () {} static { try { sr = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException nsae) { - log.error("Instantiating the secure Random generator", nsae); + LOG.error("Instantiating the secure Random generator", nsae); } } @@ -5547,7 +5679,7 @@ public static String passwordDigest(String toEncode) * si no hay una implementación del algoritmo SHA-512 * disponible en el ambiente. * - * @throws GeneralSecurityException + * @throws NoSuchAlgorithmException * If something fails when comparing passwords */ public static String comparablePassword(String toEncode) throws NoSuchAlgorithmException { @@ -5578,11 +5710,8 @@ public static String comparablePassword(String toEncode) throws NoSuchAlgorithmE * si no hay una implementación del algoritmo especificado * disponible en el ambiente. * - * @throws GeneralSecurityException - * If something fails when comparing passwords */ - public static String comparablePassword(String toEncode, String digestAlgorithm) - throws NoSuchAlgorithmException { + public static String comparablePassword(String toEncode, String digestAlgorithm) throws NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest.getInstance(digestAlgorithm); byte[] bits = null; try { @@ -5618,15 +5747,7 @@ public static String comparablePassword(String toEncode, String digestAlgorithm) * */ public static byte[] PBEAES128Cipher(String passPhrase, byte[] data) throws GeneralSecurityException { - - byte[] key = new byte[16]; - byte[] tmp = passPhrase.getBytes(); - int pos = 0; - while (pos < 16) { - System.arraycopy(tmp, 0, key, pos, Math.min(16 - pos, tmp.length)); - pos += tmp.length; - } - SecretKey secretKey = new SecretKeySpec(key, "AES"); + SecretKey secretKey = getSecretKey(passPhrase, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); return cipher.doFinal(data); @@ -5659,7 +5780,19 @@ public static byte[] PBEAES128Cipher(String passPhrase, byte[] data) throws Gene * */ public static byte[] PBEAES128Decipher(String passPhrase, byte[] data) throws GeneralSecurityException { + SecretKey secretKey = getSecretKey(passPhrase, "AES"); + Cipher cipher = Cipher.getInstance("AES"); + cipher.init(Cipher.DECRYPT_MODE, secretKey); + return cipher.doFinal(data); + } + /** + * Gets a {@link SecretKey} object from a String passphrase. + * @param passPhrase Passphrase. + * @param algorithm Algorithm. + * @return SecretKey + */ + private static SecretKey getSecretKey(String passPhrase, String algorithm) { byte[] key = new byte[16]; byte[] tmp = passPhrase.getBytes(); int pos = 0; @@ -5667,10 +5800,7 @@ public static byte[] PBEAES128Decipher(String passPhrase, byte[] data) throws Ge System.arraycopy(tmp, 0, key, pos, Math.min(16 - pos, tmp.length)); pos += tmp.length; } - SecretKey secretKey = new SecretKeySpec(key, "AES"); - Cipher cipher = Cipher.getInstance("AES"); - cipher.init(Cipher.DECRYPT_MODE, secretKey); - return cipher.doFinal(data); + return new SecretKeySpec(key, algorithm); } /** @@ -5696,7 +5826,7 @@ public static KeyPair genDH512KeyPair() { keyGen.initialize(dhSpec, new SecureRandom(seed.getBytes())); return keyGen.generateKeyPair(); } catch (Exception e) { - e.printStackTrace(); + LOG.error(e); assert (false); } return null; @@ -5713,7 +5843,7 @@ public static KeyPair genRSAKeyPair() { keyGen.initialize(1024); return keyGen.genKeyPair(); } catch (Exception e) { - e.printStackTrace(); + LOG.error(e); assert (false); } return null; @@ -5772,8 +5902,7 @@ public static String byteArrayToHexString(byte[] arr) { * @param password * @return */ - public static String decryptPassword(String password, java.security.KeyPair RSA512key) - throws GeneralSecurityException { + public static String decryptPassword(String password, java.security.KeyPair RSA512key) throws GeneralSecurityException { Cipher c = Cipher.getInstance("RSA"); c.init(Cipher.DECRYPT_MODE, RSA512key.getPrivate()); return new String(c.doFinal(hexStringToByteArray(password))); @@ -5798,7 +5927,7 @@ public static String genCryptoToken() { * */ public static class Collections { - + private Collections () {} /** @@ -5814,7 +5943,7 @@ private Collections () {} * {@code list} formado por los mismos elementos que tiene {@code it}. */ public static List copyIterator(Iterator it) { - ArrayList ret = new ArrayList(); + List ret = new ArrayList(); while (it.hasNext()) { Object ref = it.next(); ret.add(ref); @@ -5844,35 +5973,5 @@ public static long sizeOf(Iterator it) { } return size; } - - /** - * Filtra iterador por medio de la interface FilterRule, la cual hay que - * implementar cuando se utilice - * - * @param it - * @param rule - * @return - */ - public static List filterIterator(Iterator it, FilterRule rule) { - List ret = new ArrayList(); - while (it.hasNext()) { - Object object = it.next(); - if (!rule.filter(object)) { - ret.add(object); - } - } - return ret; - } - - public static List filterIterator(Iterator it, GenericFilterRule rule) { - List ret = new ArrayList(); - while (it.hasNext()) { - Object object = it.next(); - if (!rule.filter(object)) { - ret.add(object); - } - } - return ret; - } } } diff --git a/src/main/java/org/semanticwb/base/SWBAppObject.java b/src/main/java/org/semanticwb/base/SWBAppObject.java index 5ed7f17..a26d7ed 100644 --- a/src/main/java/org/semanticwb/base/SWBAppObject.java +++ b/src/main/java/org/semanticwb/base/SWBAppObject.java @@ -23,7 +23,7 @@ package org.semanticwb.base; /** - * Application object that need to perform some operations constantly in time or + * Interface for an Application object that needs to perform some operations constantly in time or * by events that are very common in the entire application, hence will remain * alive while the application is running. *@@ -56,7 +56,7 @@ public interface SWBAppObject { * de la aplicación para dejar de interactuar con este objeto. *
*/ - public void destroy(); + void destroy(); /** * Updates the state of this object. @@ -64,5 +64,5 @@ public interface SWBAppObject { * Actualiza el estado de este objeto. * */ - public void refresh(); + void refresh(); } diff --git a/src/main/java/org/semanticwb/base/SWBObserver.java b/src/main/java/org/semanticwb/base/SWBObserver.java index d30f6c1..f2e4199 100644 --- a/src/main/java/org/semanticwb/base/SWBObserver.java +++ b/src/main/java/org/semanticwb/base/SWBObserver.java @@ -23,20 +23,15 @@ package org.semanticwb.base; /** - * objeto: indica que el objeto puede recibir notificaciones de otro objeto. - * + * Interface for observer objects allowed to send notifications. * @author Javier Solis Gonzalez * @version 1.1 */ public interface SWBObserver { - /** - * Avisa al observador de un cambio. - * - * @param s - * the s - * @param obj - * the obj + * Notifies of changes. + * @param message notification message. + * @param reference reference object. */ - public void sendDBNotify(String s, Object obj); + void sendDBNotify(String message, Object reference); } diff --git a/src/main/java/org/semanticwb/base/db/AutoConnection.java b/src/main/java/org/semanticwb/base/db/AutoConnection.java index 340615b..84418f4 100644 --- a/src/main/java/org/semanticwb/base/db/AutoConnection.java +++ b/src/main/java/org/semanticwb/base/db/AutoConnection.java @@ -22,61 +22,31 @@ */ package org.semanticwb.base.db; -import java.sql.Array; -import java.sql.Blob; -import java.sql.CallableStatement; -import java.sql.Clob; -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.NClob; -import java.sql.PreparedStatement; -import java.sql.SQLClientInfoException; -import java.sql.SQLException; -import java.sql.SQLWarning; -import java.sql.SQLXML; -import java.sql.Statement; -import java.sql.Struct; -import java.util.Properties; -import java.util.concurrent.Executor; - import org.semanticwb.Logger; import org.semanticwb.SWBUtils; +import java.sql.*; +import java.util.Properties; +import java.util.concurrent.Executor; + /** - * The Class AutoConnection. - * + * Wrapper class for a {@link Connection} object with methods to perform SWB specific actions + * on a {@link DBConnectionPool}. + * * @author javier.solis */ public class AutoConnection implements Connection { - - /** The log. */ private static final Logger log = SWBUtils.getLogger(AutoConnection.class); - - /** The con. */ - private java.sql.Connection con = null; - - /** The pool. */ + private java.sql.Connection con; private DBConnectionPool pool; - - /** The description. */ private String description = ""; - - /** The id. */ private long id = 0; - - /** The isclosed. */ - private boolean isclosed = false; - - /** The debug. */ - private boolean debug = false; + private boolean isClosed = false; /** - * Instantiates a new auto connection. - * - * @param con - * the con - * @param pool - * the pool + * Creates a new {@link AutoConnection} instance. + * @param con {@link Connection} object to wrap. + * @param pool {@link DBConnectionPool} object responsible for managing the connections. */ public AutoConnection(Connection con, DBConnectionPool pool) { this.con = con; @@ -85,25 +55,20 @@ public AutoConnection(Connection con, DBConnectionPool pool) { } /** - * Check connection. - * - * @return true, if successful + * Checks the connection. + * @return true, if connection is open. */ public boolean checkConnection() { - if (debug) { - log.debug("checkConnection"); - } boolean ret = false; - if (!isclosed) { + if (!isClosed) { if (con != null) { try { - boolean closed = con.isClosed(); - if (closed) { + if (con.isClosed()) { changeConnection(); ret = true; } } catch (SQLException e) { - log.error("SQLException:" + e.getMessage()); + log.error("AutoConnection: Error accessing database.", e); changeConnection(); ret = true; } @@ -115,418 +80,313 @@ public boolean checkConnection() { } /** - * Change connection. + * Creates a new {@link Connection} object managed by the {@link AutoConnection}. */ public void changeConnection() { - if (debug) { - log.debug("changeConnection"); - } - log.error("Error checking connection, Auto Reconnect..."); con = pool.newNoPoolConnection(); } /** - * Getter for property id. - * - * @return Value of property id. - * + * Gets the id property. + * @return ID for this object. */ public long getId() { return id; } /** - * Setter for property id. - * - * @param id - * New value of property id. - * + * Sets the id property. + * @param id Identifier for this object. */ public void setId(long id) { this.id = id; } /** - * Gets the native connection. - * - * @return the native connection - * @return + * Gets the wrapped {@link Connection} object. + * @return {@link Connection} object wrapped by this class. */ public java.sql.Connection getNativeConnection() { return con; } /** - * Getter for property pool. - * - * @return Value of property pool. - * + * Gets the {@link DBConnectionPool} associated to this object. + * @return {@link DBConnectionPool} object. */ public DBConnectionPool getPool() { return pool; } /** - * Getter for property description. - * - * @return Value of property description. - * + * Gets the description of this object. + * @return description of this object. */ - public java.lang.String getDescription() { + public String getDescription() { return description; } /** - * Setter for property description. - * - * @param description - * New value of property description. - * + * Sets the description of this object. + * @param description object description. */ - public void setDescription(java.lang.String description) { + public void setDescription(String description) { this.description = description; } /** - * Cierra la conexión con la base de datos en vez de esperar. Una conexión puede - * ser cerrada automáticamente cuando es garbage collected. También ciertos - * errores fatales puden cerrar la conexión. - * - * @throws SQLException - * the sQL exception - * @exception java.sql.SQLException - * Si un error de acceso a kla base de datos ocurre. + * Closes connection without waiting. A connection can be automatically closed when + * garbage collected or by certain errors. + * @throws SQLException when a database error occurs closing the connection. */ public void close() throws SQLException { - if (debug) { - log.debug("close"); - } - isclosed = true; + isClosed = true; con.close(); log.trace("close:(" + getId() + "," + pool.getName() + "):" + pool.checkedOut); } - /** - * Configura el modo auto-commit de la conexión en el estado determinado. Si una - * conexión está en auto-commit, entonces cada sentencia SQL será procesada y el - * commit se ejecutará por cada una como una transacción individual. De lo - * contrario, sus sentencias SQL se agrupan en una transacción que finalizará - * por una llamada al métodocommit o al método
- * rollback. Por default un nuevo objeto PoolConnection está en
- * modo auto-commit.
- *
- * @param param
- * the new auto commit
- * @throws SQLException
- * the sQL exception
- * @exception java.sql.SQLException
- * Si un error de acceso a kla base de datos ocurre.
- * @see getAutoCommit()
- */
- public void setAutoCommit(boolean param) throws SQLException {
- if (debug) {
- log.debug("setAutoCommit");
- }
- checkConnection();
- con.setAutoCommit(param);
- }
-
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#getWarnings()
*/
public SQLWarning getWarnings() throws SQLException {
- if (debug) {
- log.debug("getWarnings");
- }
checkConnection();
return con.getWarnings();
}
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#getCatalog()
*/
public String getCatalog() throws SQLException {
- if (debug) {
- log.debug("getCatalog");
- }
checkConnection();
return con.getCatalog();
}
/*
* (non-Javadoc)
- *
- * @see java.sql.Connection#setTypeMap(java.util.Map)
+ *
+ * @see java.sql.Connection#setCatalog(java.lang.String)
*/
- public void setTypeMap(java.util.Map map) throws SQLException {
- if (debug) {
- log.debug("setTypeMap");
- }
+ public void setCatalog(String catalog) throws SQLException {
checkConnection();
- con.setTypeMap(map);
+ con.setCatalog(catalog);
}
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#getTypeMap()
*/
public java.util.Map getTypeMap() throws SQLException {
- if (debug) {
- log.debug("getTypeMap");
- }
checkConnection();
return con.getTypeMap();
}
/*
* (non-Javadoc)
- *
- * @see java.sql.Connection#getTransactionIsolation()
+ *
+ * @see java.sql.Connection#setTypeMap(java.util.Map)
*/
- public int getTransactionIsolation() throws SQLException {
- if (debug) {
- log.debug("getTransactionIsolation");
- }
+ public void setTypeMap(java.util.Map map) throws SQLException {
checkConnection();
- return con.getTransactionIsolation();
+ con.setTypeMap(map);
}
/*
* (non-Javadoc)
- *
- * @see java.sql.Connection#isReadOnly()
+ *
+ * @see java.sql.Connection#getTransactionIsolation()
*/
- public boolean isReadOnly() throws SQLException {
- if (debug) {
- log.debug("isReadOnly");
- }
+ public int getTransactionIsolation() throws SQLException {
checkConnection();
- return con.isReadOnly();
+ return con.getTransactionIsolation();
}
/*
* (non-Javadoc)
- *
- * @see java.sql.Connection#getMetaData()
+ *
+ * @see java.sql.Connection#setTransactionIsolation(int)
*/
- public DatabaseMetaData getMetaData() throws SQLException {
- if (debug) {
- log.debug("getMetaData");
- }
+ public void setTransactionIsolation(int level) throws SQLException {
checkConnection();
- return con.getMetaData();
+ con.setTransactionIsolation(level);
}
/*
* (non-Javadoc)
- *
- * @see java.sql.Connection#clearWarnings()
+ *
+ * @see java.sql.Connection#isReadOnly()
*/
- public void clearWarnings() throws SQLException {
- if (debug) {
- log.debug("clearWarnings");
- }
+ public boolean isReadOnly() throws SQLException {
checkConnection();
- con.clearWarnings();
+ return con.isReadOnly();
}
/*
* (non-Javadoc)
- *
- * @see java.sql.Connection#nativeSQL(java.lang.String)
+ *
+ * @see java.sql.Connection#setReadOnly(boolean)
*/
- public String nativeSQL(String str) throws SQLException {
- if (debug) {
- log.debug("nativeSQL");
- }
+ public void setReadOnly(boolean readOnly) throws SQLException {
checkConnection();
- return con.nativeSQL(str);
+ con.setReadOnly(readOnly);
}
/*
* (non-Javadoc)
- *
- * @see java.sql.Connection#prepareStatement(java.lang.String, int, int)
+ *
+ * @see java.sql.Connection#getMetaData()
*/
- public PreparedStatement prepareStatement(String str, int param, int param2) throws SQLException {
- if (debug) {
- log.debug("prepareStatement");
- }
+ public DatabaseMetaData getMetaData() throws SQLException {
checkConnection();
- return con.prepareStatement(str, param, param2);
+ return con.getMetaData();
}
/*
* (non-Javadoc)
- *
- * @see java.sql.Connection#setTransactionIsolation(int)
+ *
+ * @see java.sql.Connection#clearWarnings()
*/
- public void setTransactionIsolation(int param) throws SQLException {
- if (debug) {
- log.debug("setTransactionIsolation");
- }
+ public void clearWarnings() throws SQLException {
checkConnection();
- con.setTransactionIsolation(param);
+ con.clearWarnings();
}
/*
* (non-Javadoc)
- *
- * @see java.sql.Connection#setReadOnly(boolean)
+ *
+ * @see java.sql.Connection#nativeSQL(java.lang.String)
*/
- public void setReadOnly(boolean param) throws SQLException {
- if (debug) {
- log.debug("setReadOnly");
- }
+ public String nativeSQL(String sql) throws SQLException {
checkConnection();
- con.setReadOnly(param);
+ return con.nativeSQL(sql);
}
/*
* (non-Javadoc)
- *
- * @see java.sql.Connection#setCatalog(java.lang.String)
+ *
+ * @see java.sql.Connection#prepareStatement(java.lang.String, int, int)
*/
- public void setCatalog(String str) throws SQLException {
- if (debug) {
- log.debug("setCatalog");
- }
+ public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
checkConnection();
- con.setCatalog(str);
+ return con.prepareStatement(sql, resultSetType, resultSetConcurrency);
}
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#isClosed()
*/
public boolean isClosed() throws SQLException {
- if (debug) {
- log.debug("isClosed");
- }
checkConnection();
return con.isClosed();
}
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#createStatement()
*/
public Statement createStatement() throws SQLException {
- if (debug) {
- log.debug("createStatement");
- }
checkConnection();
return new AutoStatement(this);
}
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#createStatement(int, int)
*/
public Statement createStatement(int param, int param1) throws SQLException {
- if (debug) {
- log.debug("createStatement");
- }
checkConnection();
return new AutoStatement(this, param, param1);
}
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#prepareStatement(java.lang.String)
*/
public PreparedStatement prepareStatement(String str) throws SQLException {
- if (debug) {
- log.debug("prepareStatement");
- }
checkConnection();
return new AutoPreparedStatement(this, str);
}
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#getAutoCommit()
*/
public boolean getAutoCommit() throws SQLException {
- if (debug) {
- log.debug("getAutoCommit");
- }
checkConnection();
return con.getAutoCommit();
}
+ /**
+ * Sets connection auto-commit mode. On auto-commit enabled connections, each SQL
+ * sentence will be processed and committed as a separate transaction. When connection
+ * is not in auto-commit mode, all SQL sentences are grouped in a single transaction
+ * that will be committed using commit or rollback methods.
+ * New instances of {@link PoolConnection} class are auto-commit enabled by default.
+ *
+ * @param enable boolean value to set auto-commit. TRUE for enable, FALSE for disable.
+ * @throws SQLException if value setting fails.
+ */
+ public void setAutoCommit(boolean enable) throws SQLException {
+ checkConnection();
+ con.setAutoCommit(enable);
+ }
+
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#prepareCall(java.lang.String)
*/
- public CallableStatement prepareCall(String str) throws SQLException {
- if (debug) {
- log.debug("prepareCall");
- }
+ public CallableStatement prepareCall(String sql) throws SQLException {
checkConnection();
- return con.prepareCall(str);
+ return con.prepareCall(sql);
}
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#commit()
*/
public void commit() throws SQLException {
- if (debug) {
- log.debug("commit");
- }
checkConnection();
con.commit();
}
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#prepareCall(java.lang.String, int, int)
*/
- public CallableStatement prepareCall(String str, int param, int param2) throws SQLException {
- if (debug) {
- log.debug("prepareCall");
- }
+ public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
checkConnection();
- return con.prepareCall(str, param, param2);
+ return con.prepareCall(sql, resultSetType, resultSetConcurrency);
}
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#rollback()
*/
public void rollback() throws SQLException {
- if (debug) {
- log.debug("rollback");
- }
checkConnection();
con.rollback();
}
/*
* (non-Javadoc)
- *
+ *
* @see java.lang.Object#finalize()
*/
@Override
protected void finalize() throws Throwable {
- if (debug) {
- log.debug("finalize");
- }
log.warn("finalize()..., connection was not closed, " + description);
}
@@ -534,161 +394,121 @@ protected void finalize() throws Throwable {
// *****************************************************************
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#setSavepoint()
*/
- public java.sql.Savepoint setSavepoint() throws java.sql.SQLException {
- if (debug) {
- log.debug("setSavepoint");
- }
+ public Savepoint setSavepoint() throws SQLException {
checkConnection();
return con.setSavepoint();
}
/*
* (non-Javadoc)
- *
- * @see java.sql.Connection#setHoldability(int)
+ *
+ * @see java.sql.Connection#prepareStatement(java.lang.String, int)
*/
- public void setHoldability(int param) throws java.sql.SQLException {
- if (debug) {
- log.debug("setHoldability");
- }
+ public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
checkConnection();
- con.setHoldability(param);
+ return con.prepareStatement(sql, autoGeneratedKeys);
}
/*
* (non-Javadoc)
- *
- * @see java.sql.Connection#prepareStatement(java.lang.String, int)
+ *
+ * @see java.sql.Connection#prepareStatement(java.lang.String, int, int, int)
*/
- public java.sql.PreparedStatement prepareStatement(java.lang.String str, int param) throws java.sql.SQLException {
- if (debug) {
- log.debug("prepareStatement");
- }
+ public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
checkConnection();
- return con.prepareStatement(str, param);
+ return con.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
}
/*
* (non-Javadoc)
- *
- * @see java.sql.Connection#prepareStatement(java.lang.String, int, int, int)
+ *
+ * @see java.sql.Connection#prepareStatement(java.lang.String, int[])
*/
- public java.sql.PreparedStatement prepareStatement(java.lang.String str, int param, int param2, int param3)
- throws java.sql.SQLException {
- if (debug) {
- log.debug("prepareStatement");
- }
+ public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
checkConnection();
- return con.prepareStatement(str, param, param2, param3);
+ return con.prepareStatement(sql, columnIndexes);
}
/*
* (non-Javadoc)
- *
- * @see java.sql.Connection#prepareStatement(java.lang.String, int[])
+ *
+ * @see java.sql.Connection#getHoldability()
*/
- public java.sql.PreparedStatement prepareStatement(java.lang.String str, int[] values)
- throws java.sql.SQLException {
- if (debug) {
- log.debug("prepareStatement");
- }
+ public int getHoldability() throws SQLException {
checkConnection();
- return con.prepareStatement(str, values);
+ return con.getHoldability();
}
/*
* (non-Javadoc)
- *
- * @see java.sql.Connection#getHoldability()
+ *
+ * @see java.sql.Connection#setHoldability(int)
*/
- public int getHoldability() throws java.sql.SQLException {
- if (debug) {
- log.debug("getHoldability");
- }
+ public void setHoldability(int holdability) throws SQLException {
checkConnection();
- return con.getHoldability();
+ con.setHoldability(holdability);
}
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#setSavepoint(java.lang.String)
*/
- public java.sql.Savepoint setSavepoint(java.lang.String str) throws java.sql.SQLException {
- if (debug) {
- log.debug("setSavepoint");
- }
+ public Savepoint setSavepoint(java.lang.String str) throws SQLException {
checkConnection();
return con.setSavepoint(str);
}
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#createStatement(int, int, int)
*/
- public java.sql.Statement createStatement(int param, int param1, int param2) throws java.sql.SQLException {
- if (debug) {
- log.debug("createStatement");
- }
+ public java.sql.Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
checkConnection();
- return con.createStatement(param, param1, param2);
+ return con.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability);
}
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#prepareCall(java.lang.String, int, int, int)
*/
- public java.sql.CallableStatement prepareCall(java.lang.String str, int param, int param2, int param3)
- throws java.sql.SQLException {
- if (debug) {
- log.debug("prepareCall");
- }
+ public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
checkConnection();
- return con.prepareCall(str, param, param2, param3);
+ return con.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
}
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#releaseSavepoint(java.sql.Savepoint)
*/
- public void releaseSavepoint(java.sql.Savepoint savepoint) throws java.sql.SQLException {
- if (debug) {
- log.debug("releaseSavepoint");
- }
+ public void releaseSavepoint(Savepoint savepoint) throws SQLException {
checkConnection();
con.releaseSavepoint(savepoint);
}
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#prepareStatement(java.lang.String,
* java.lang.String[])
*/
- public java.sql.PreparedStatement prepareStatement(java.lang.String str, java.lang.String[] str1)
- throws java.sql.SQLException {
- if (debug) {
- log.debug("prepareStatement");
- }
+ public java.sql.PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
checkConnection();
- return con.prepareStatement(str, str1);
+ return con.prepareStatement(sql, columnNames);
}
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#rollback(java.sql.Savepoint)
*/
- public void rollback(java.sql.Savepoint savepoint) throws java.sql.SQLException {
- if (debug) {
- log.debug("rollback");
- }
+ public void rollback(java.sql.Savepoint savepoint) throws SQLException {
checkConnection();
con.rollback(savepoint);
}
@@ -724,11 +544,6 @@ public void setClientInfo(String name, String value) throws SQLClientInfoExcepti
con.setClientInfo(name, value);
}
- public void setClientInfo(Properties properties) throws SQLClientInfoException {
- checkConnection();
- con.setClientInfo(properties);
- }
-
public String getClientInfo(String name) throws SQLException {
checkConnection();
return con.getClientInfo(name);
@@ -739,6 +554,11 @@ public Properties getClientInfo() throws SQLException {
return con.getClientInfo();
}
+ public void setClientInfo(Properties properties) throws SQLClientInfoException {
+ checkConnection();
+ con.setClientInfo(properties);
+ }
+
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
checkConnection();
return con.createArrayOf(typeName, elements);
@@ -759,15 +579,15 @@ public boolean isWrapperFor(Class> iface) throws SQLException {
return con.isWrapperFor(iface);
}
- /* MAPS74 - JSE 7 Wrapper */
@Override
- public void setSchema(String schema) throws SQLException {
- con.setSchema(schema);
+ public String getSchema() throws SQLException {
+ return con.getSchema();
}
+ /* MAPS74 - JSE 7 Wrapper */
@Override
- public String getSchema() throws SQLException {
- return con.getSchema();
+ public void setSchema(String schema) throws SQLException {
+ con.setSchema(schema);
}
@Override
diff --git a/src/main/java/org/semanticwb/base/db/AutoPreparedStatement.java b/src/main/java/org/semanticwb/base/db/AutoPreparedStatement.java
index fbe858d..e6f29f3 100644
--- a/src/main/java/org/semanticwb/base/db/AutoPreparedStatement.java
+++ b/src/main/java/org/semanticwb/base/db/AutoPreparedStatement.java
@@ -22,77 +22,39 @@
*/
package org.semanticwb.base.db;
+import org.semanticwb.Logger;
+import org.semanticwb.SWBUtils;
+
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
-import java.sql.Array;
-import java.sql.Blob;
-import java.sql.Clob;
-import java.sql.Connection;
-import java.sql.Date;
-import java.sql.NClob;
-import java.sql.ParameterMetaData;
-import java.sql.PreparedStatement;
-import java.sql.Ref;
-import java.sql.ResultSet;
-import java.sql.ResultSetMetaData;
-import java.sql.RowId;
-import java.sql.SQLException;
-import java.sql.SQLXML;
-import java.sql.Time;
-import java.sql.Timestamp;
+import java.sql.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
-import org.semanticwb.Logger;
-import org.semanticwb.SWBUtils;
-
/**
- * Objeto que sobrescribe la clase Statement para poder tener control la misma
- * desde el Pool de conexiones.
- *
+ * Wrapper class for a {@link java.sql.Statement} for use in a {@link DBConnectionPool}.
+ *
* @author Javier Solis Gonzalez (jsolis@infotec.com.mx)
*/
public class AutoPreparedStatement implements java.sql.PreparedStatement {
-
private static final Logger LOG = SWBUtils.getLogger(AutoPreparedStatement.class);
-
- /** The st. */
private PreparedStatement st;
-
- /** The closed. */
private boolean closed = false;
-
- /** The query. */
- private String query = null;
-
- /** The args. */
- private String args = "";
-
- /** The debug. */
- private boolean debug = false;
-
- /** The aconn. */
+ private String query;
private AutoConnection aconn;
-
- /** The conn. */
private Connection conn;
-
- /** The batchs. */
private ArrayListtime milliseconds
+ * while attempting to connect to a database.
*
- * @param name the name
- * @param time the time
- * @return Connection La conexión o nulo.
+ * @param name pool name.
+ * @param time timeout in milliseconds.
+ * @return connection or null.
*/
- public Connection getConnection(String name, long time)
- {
+ public Connection getConnection(String name, long time) {
Connection ret = null;
- if (!isJNDI)
- {
+ if (!isJNDI) {
DBConnectionPool pool = (DBConnectionPool) pools.get(name);
- if (pool != null)
- {
+ if (pool != null) {
ret = pool.getConnection(time);
}
- } else
- {
+ } else {
DataSource ds = (DataSource) pools.get(name);
- if (ds == null)
- {
- try
- {
- ds = (DataSource) initCtx.lookup(JNDIPatern + name);
+ if (ds == null) {
+ try {
+ ds = (DataSource) initCtx.lookup(jndiPattern + name);
pools.put(name, ds);
log.info("Initialized JNDI Pool [" + name + "]");
- } catch (Exception ex)
- {
+ } catch (Exception ex) {
log.error("Error to get DataSource of Context...", ex);
}
- }
- try
- {
- ds.setLoginTimeout((int) (time / 1000));
- ret = ds.getConnection();
- } catch (SQLException ex)
- {
- log.error("Error to get JNDI Pool Connection...", ex);
+ } else {
+ try {
+ ds.setLoginTimeout((int) (time / 1000));
+ ret = ds.getConnection();
+ } catch (SQLException ex) {
+ log.error("Error to get JNDI Pool Connection...", ex);
+ }
}
}
return ret;
}
/**
- * Cierra todas las conexiones abiertas.
+ * Closes all connections.
*/
- public void closeAllConnection()
- {
+ public void closeAllConnection() {
Enumeration allPools = pools.elements();
- if (!isJNDI)
- {
- while (allPools.hasMoreElements())
- {
+ if (!isJNDI) {
+ while (allPools.hasMoreElements()) {
DBConnectionPool pool = (DBConnectionPool) allPools.nextElement();
pool.release();
}
@@ -328,29 +251,25 @@ public void closeAllConnection()
}
/**
- * Crea instancias del DBConnectionPool basandose en el archivo de propiedades.
- * Un DBConnectionPool puede ser definido con las siguientes propiedades:
+ * Creates {@link DBConnectionPool} instances with parameters from a {@link Properties} object.
+ * Properties must match values defined in db.properties file.
*
- * <poolname>.url El URL JDBC de la base de datos.
- * <poolname>.user Un usuario de la base de datos (opcional)
- * <poolname>.password El password del usuario de la base de datos. (Si el usuario se especifica)
- * <poolname>.maxconn El número máximo de conexiones (opcional)
+ * <poolname>.url JDBC URL connection String.
+ * <poolname>.user Database user (optional)
+ * <poolname>.password Database password (required if user is defined)
+ * <poolname>.maxconn Maximum number of connections managed by the pool (optional)
*
*
- * @param props the props
+ * @param props properties object.
*/
- private void createPools(Properties props)
- {
+ private void createPools(Properties props) {
Enumeration propNames = props.propertyNames();
- while (propNames.hasMoreElements())
- {
+ while (propNames.hasMoreElements()) {
String name = (String) propNames.nextElement();
- if (name.endsWith(".url"))
- {
+ if (name.endsWith(".url")) {
String poolName = name.substring(0, name.lastIndexOf('.'));
String url = props.getProperty(poolName + ".url");
- if (url == null)
- {
+ if (url == null) {
log.error("No URL specified for " + poolName);
continue;
}
@@ -358,32 +277,27 @@ private void createPools(Properties props)
String password = props.getProperty(poolName + ".password");
String maxconn = props.getProperty(poolName + ".maxconn", "0");
String sidleTime = props.getProperty(poolName + ".idle_time", "0");
- if (user != null)
- {
+ if (user != null) {
user = user.trim();
}
- if (password != null)
- {
+ if (password != null) {
password = password.trim();
}
- int max;
- try
- {
+
+ int max = 0;
+ try {
max = Integer.parseInt(maxconn.trim());
- } catch (NumberFormatException e)
- {
+ } catch (NumberFormatException e) {
log.warn("Invalid maxconn value " + maxconn + " for " + poolName);
- max = 0;
}
+
long idleTime = 0;
- try
- {
- idleTime = Long.parseLong(sidleTime.trim());
- } catch (NumberFormatException e)
- {
+ try {
+ idleTime = Long.parseLong(sidleTime.trim());
+ } catch (NumberFormatException e) {
log.warn("Invalid idle_time value " + sidleTime + " for " + poolName);
- idleTime = 0;
}
+
DBConnectionPool pool =
new DBConnectionPool(this, poolName, url, user, password, max, idleTime);
pools.put(poolName, pool);
@@ -393,98 +307,78 @@ private void createPools(Properties props)
}
/**
- * Carga las propiedades e inicializa la instancia con sus valores.
+ * Initializes {@link DBConnectionManager} with parameters from db.properties file.
*/
- private void init()
- {
+ private void init() {
+ //TODO: Desacoplar dependencia con archivo db.properties
InputStream is = getClass().getResourceAsStream("/db.properties");
Properties dbProps = new SWBProperties();
- try
- {
- if (is != null)
- {
+ try {
+ if (is != null) {
dbProps.load(is);
- } else
- {
+ } else {
throw new FileNotFoundException();
}
is.close();
- } catch (Exception e)
- {
+ } catch (Exception e) {
log.error("Can't read the properties file. Make sure db.properties is in the CLASSPATH", e);
return;
}
String jndi = dbProps.getProperty("jndi_pool", "false");
- if (jndi.equals("true"))
- {
+ if (jndi.equals("true")) {
log.info("JDNI Pool found...");
isJNDI = true;
- JNDIPatern = dbProps.getProperty("jndi_patern", "java:comp/env/jdbc/");
- try
- {
+ jndiPattern = dbProps.getProperty("jndi_patern", "java:comp/env/jdbc/");
+ try {
initCtx = new InitialContext();
- } catch (javax.naming.NamingException ex)
- {
+ } catch (javax.naming.NamingException ex) {
log.error("Error to initialize JNDI Context", ex);
}
}
- if (!isJNDI)
- {
+ if (!isJNDI) {
loadDrivers(dbProps);
createPools(dbProps);
}
}
/**
- * Carga y registra todos los drivers JDBC. Esto lo realiza el DBConnectionManager, en comparación
- * con el DBConnectionPool, puesto que muchos pools pueden compartir el mismo driver.
- *
- * @param props the props
+ * Loads and registers shared JDBC drivers with parameters from a {@link Properties} object.
+ * @param props properties object.
*/
- private void loadDrivers(Properties props)
- {
+ private void loadDrivers(Properties props) {
String driverClasses = props.getProperty("drivers");
StringTokenizer st = new StringTokenizer(driverClasses);
- while (st.hasMoreElements())
- {
+ while (st.hasMoreElements()) {
String driverClassName = st.nextToken().trim();
- try
- {
+ try {
Driver driver = (Driver) Class.forName(driverClassName).newInstance();
DriverManager.registerDriver(driver);
drivers.add(driver);
log.info("Registered JDBC driver " + driverClassName);
- } catch (Exception e)
- {
+ } catch (Exception e) {
log.error("Can't register JDBC driver: " + driverClassName + ", Exception: " + e);
}
}
}
- /** Getter for property timeLock.
+ /** Gets the time lock value.
* @return Value of property timeLock.
- *
*/
- public PoolConnectionTimeLock getTimeLock()
- {
+ public PoolConnectionTimeLock getTimeLock() {
return timeLock;
}
- /** Getter for property pools.
- * @return Value of property pools.
- *
+ /** Gets the Pool objects.
+ * @return Hashtable of Pool objects.
*/
- public Hashtable getPools()
- {
+ public Hashtable getPools() {
Hashtable map = new Hashtable();
Enumeration en = pools.keys();
- while (en.hasMoreElements())
- {
+ while (en.hasMoreElements()) {
String key = (String) en.nextElement();
Object obj = pools.get(key);
- if (obj instanceof DBConnectionPool)
- {
+ if (obj instanceof DBConnectionPool) {
map.put(key, obj);
}
}
@@ -492,19 +386,15 @@ public Hashtable getPools()
}
/**
- * Gets the hits.
- *
- * @return Regresa las total de solicitudes de conexiones
+ * Gets the total count of requests made to all Pools.
+ * @return count of requests on all pools.
*/
- public long getHits()
- {
+ public long getHits() {
long hits = 0;
Enumeration en = pools.elements();
- while (en.hasMoreElements())
- {
+ while (en.hasMoreElements()) {
Object obj = en.nextElement();
- if (obj instanceof DBConnectionPool)
- {
+ if (obj instanceof DBConnectionPool) {
hits += ((DBConnectionPool) obj).getHits();
}
}
diff --git a/src/main/java/org/semanticwb/base/db/DBConnectionPool.java b/src/main/java/org/semanticwb/base/db/DBConnectionPool.java
index 44b1396..4f2e59c 100644
--- a/src/main/java/org/semanticwb/base/db/DBConnectionPool.java
+++ b/src/main/java/org/semanticwb/base/db/DBConnectionPool.java
@@ -22,102 +22,67 @@
*/
package org.semanticwb.base.db;
-import java.sql.*;
-import java.util.concurrent.ConcurrentLinkedQueue;
import org.semanticwb.Logger;
import org.semanticwb.SWBUtils;
import org.semanticwb.base.util.SFBase64;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.concurrent.ConcurrentLinkedQueue;
+
/**
- * Esta clase interna representa un connection pool. Crea nuevas conexiones con
- * base en la demanda, hasta un numero máximo si esta especificado. Tambien se
- * cerciora de que una conexión todavia esté abierta antes de que se regrese a
- * un cliente.
- *
+ * Connection Pool implementation. Creates connections on demand up to a defined limit if specified.
+ * This implementation checks if the connection is open before returning it to clients.
+ *
* @author Javier Solis Gonzalez (jsolis@infotec.com.mx)
*/
public class DBConnectionPool {
- /** The log. */
+ private static final String KEY = "akdhfyehe38";
private static Logger log = SWBUtils.getLogger(DBConnectionPool.class);
-
- /** The checked out. */
protected int checkedOut;
-
- /** The free connections. */
protected ConcurrentLinkedQueue freeConnections = new ConcurrentLinkedQueue();
-
- /** The max conn. */
private int maxConn;
-
- /** The name. */
private String name;
-
- /** The password. */
private String password = "";
-
- /** The URL. */
private String url;
-
- /** The user. */
private String user;
-
- /** The idle_time. */
- private long idle_time = 0;
-
- /** The manager. */
+ private long idleTime = 0;
private DBConnectionManager manager;
-
- /** The hits. */
private long hits = 0;
-
- /** The hits time. */
private long hitsTime = 0;
- private static final String KEY = "akdhfyehe38";
-
/**
- * Crea un nuevo objeto connection pool.
- *
- * @param manager
- * the manager
- * @param name
- * El nombre del pool
- * @param theURL
- * El URL JDBC de la base de datos.
- * @param user
- * Un usuario de la base de datos o nulo.
- * @param password
- * El password del usuario de la base de datos o nulo.
- * @param maxConn
- * El número máximo de conexiones o 0 para definir que no tenga
- * límite.
- * @param idle_time
- * the idle_time
+ * Creates a new instance of a {@link DBConnectionPool}.
+ * @param manager {@link DBConnectionManager} object responsible for managing pools.
+ * @param name Pool name.
+ * @param jdbcURL URL connection String for the pool.
+ * @param user User for the connection. Can be null.
+ * @param password Password for the connection. Can be null.
+ * @param maxConn Maximum number of connections. A value of 0 means no limit.
+ * @param idleTime Connection idle time in seconds.
*/
- public DBConnectionPool(DBConnectionManager manager, String name, String theURL, String user, String password,
- int maxConn, long idle_time) {
+ public DBConnectionPool(DBConnectionManager manager, String name, String jdbcURL, String user, String password, int maxConn, long idleTime) {
this.manager = manager;
this.name = name;
- setURL(theURL);
+ setURL(jdbcURL);
this.user = user;
setPassword(password);
this.maxConn = maxConn;
- this.idle_time = idle_time * 1000;
+ this.idleTime = idleTime * 1000;
}
/**
- * Libera una conexión del pool. Notifica a otros Threads que pudieran estar
- * esperando una conexión.
- *
- * @param con
- * La conexión a liberar.
+ * Disposes a connection from the pool. Notifies threads waiting for connections.
+ * @param con {@link Connection} to dispose.
*/
public void freeConnection(Connection con) {
boolean add = true;
// Put the connection at the end of the Vector
try {
- if (idle_time > 0 && (System.currentTimeMillis() - ((PoolConnection) con).getIdleTime()) > idle_time) {
+ if (idleTime > 0 && (System.currentTimeMillis() - ((PoolConnection) con).getIdleTime()) > idleTime) {
((PoolConnection) con).destroyConnection();
add = false;
}
@@ -129,18 +94,15 @@ public void freeConnection(Connection con) {
freeConnections.add(con);
}
} catch (Exception e) {
- log.warn("To return connection to pool", e);
+ log.warn("Exception when returning connection to pool", e);
}
}
/**
- * Obtiene una conexión del pool. Si ninguna conexión esté disponible, una nueva
- * conexión es creada al menos que el número máximo de conexiones haya sido
- * alcanzado. Si una conexión libre ha sido cerrada por la base de datos, se
- * elimina del pool y este método es llamado otra vez recursivamente.
- *
- * @return the connection
- * @return
+ * Gets a {@link Connection} from the {@link DBConnectionPool}. If no connections are
+ * available, a new one is created.
+ *
+ * @return new {@link Connection} object.
*/
public Connection getConnection() {
// Escoje la primera conexión en el vector o utiliza round-robin.
@@ -148,7 +110,7 @@ public Connection getConnection() {
if (con != null) {
try {
- if (idle_time > 0 && (System.currentTimeMillis() - con.getIdleTime()) > idle_time) {
+ if (idleTime > 0 && (System.currentTimeMillis() - con.getIdleTime()) > idleTime) {
log.warn("Removed bad connection " + con.getId() + " (idle_time) from " + name + ", "
+ con.getDescription());
con.destroyConnection();
@@ -192,18 +154,11 @@ public Connection getConnection() {
}
/**
- * Obtiene una conexión del pool. Si ninguna conexión está disponible, una nueva
- * conexión es creada al menos que el número máximo de conexiones haya sido
- * alcanzado. Si una conexión libre ha sido cerrada por la base de datos, se
- * elimina del pool y este métdo es llamado otra vez recursivamente.
- *
- * Si ninguna conexión está disponible y el número máximo ha sido alcanzado,
- * este método espera por una conexión liberada el tiempo especificado.
- *
- * @param timeout
- * El valor del timeout en milisegundos.
- * @return the connection
- * @return
+ * Gets a {@link Connection} from the {@link DBConnectionPool}. This method returns null
+ * after timeout milliseconds if no connection can be established.
+ *
+ * @param timeout timeout in milliseconds.
+ * @return new connection or null after timeout.
*/
public Connection getConnection(long timeout) {
long startTime = System.currentTimeMillis();
@@ -218,10 +173,10 @@ public Connection getConnection(long timeout) {
}
/**
- * Cierra todas las conexiones disponibles.
+ * Closes all available connections.
*/
public void release() {
- PoolConnection con = null;
+ PoolConnection con;
while ((con = (PoolConnection) freeConnections.poll()) != null) {
try {
con.destroyConnection();
@@ -233,19 +188,16 @@ public void release() {
}
/**
- * Crea una nueva conexión usando un identificador de usuario y passsword si son
- * especificados.
- *
- * @return the connection
- * @return
+ * Creates a new {@link Connection} with instance parameters.
+ * @return new Database connection or null.
*/
- public Connection newNoPoolConnection() {
- Connection con = null;
+ private Connection createConnection() {
+ Connection con;
try {
if (user == null) {
con = DriverManager.getConnection(url);
} else {
- con = DriverManager.getConnection(url, user, getDescriptedPassword());
+ con = DriverManager.getConnection(url, user, getDecryptedPassword());
}
log.debug("Created a new connection in pool " + name);
} catch (SQLException e) {
@@ -256,24 +208,20 @@ public Connection newNoPoolConnection() {
}
/**
- * Crea una nueva conexión que se auto conecta si se piede la conexion.
- *
- * @return the connection
- * @return
+ * Creates a new {@link Connection}.
+ * @return Database connection or null.
+ */
+ public Connection newNoPoolConnection() {
+ return createConnection();
+ }
+
+ /**
+ * Creates a new {@link AutoConnection}.
+ * @return Database autoconnection or null.
*/
public Connection newAutoConnection() {
- Connection con = null;
- try {
- if (user == null) {
- con = DriverManager.getConnection(url);
- } else {
- con = DriverManager.getConnection(url, user, getDescriptedPassword());
- }
- log.debug("Created a new connection in pool " + name);
- } catch (SQLException e) {
- log.error("Can't create a new connection for " + url, e);
- return null;
- }
+ Connection con = createConnection();
+
if (con != null) {
return new AutoConnection(con, this);
} else {
@@ -282,24 +230,11 @@ public Connection newAutoConnection() {
}
/**
- * Crea una nueva conexión usando un identificador de usuario y passsword si son
- * especificados.
- *
- * @return the connection
+ * Creates a new {@link PoolConnection}.
+ * @return the pool connection or null.
*/
private Connection newConnection() {
- Connection con = null;
- try {
- if (user == null) {
- con = DriverManager.getConnection(url);
- } else {
- con = DriverManager.getConnection(url, user, getDescriptedPassword());
- }
- log.debug("Created a new connection in pool " + name);
- } catch (SQLException e) {
- log.error("Can't create a new connection for " + url, e);
- return null;
- }
+ Connection con = createConnection();
if (con != null) {
return new PoolConnection(con, this);
} else {
@@ -308,28 +243,20 @@ private Connection newConnection() {
}
/**
- * Getter for property name.
- *
- * @return Value of property name.
+ * Gets the Pool name
+ * @return pool name.
*
*/
- public java.lang.String getName() {
+ public String getName() {
return name;
}
- public void setPassword(String password) {
- if (password != null) {
- this.password = password;
- }
- }
-
/**
- * Getter for property name.
- *
- * @return Value of property name.
+ * Gets the Pool password.
+ * @return pool password.
*
*/
- public java.lang.String getPassword() {
+ public String getPassword() {
if (password.startsWith("{") && password.endsWith("}")) {
return password;
} else {
@@ -343,7 +270,21 @@ public java.lang.String getPassword() {
}
}
- private String getDescriptedPassword() {
+ /**
+ * Sets the Pool password.
+ * @param password password string.
+ */
+ public void setPassword(String password) {
+ if (password != null) {
+ this.password = password;
+ }
+ }
+
+ /**
+ * Gets decrypted password string.
+ * @return plain string for password.
+ */
+ private String getDecryptedPassword() {
if (password.startsWith("{") && password.endsWith("}")) {
String pwd = password.substring(1, password.length() - 1);
try {
@@ -358,9 +299,8 @@ private String getDescriptedPassword() {
}
/**
- * Getter for property maxConn.
- *
- * @return Value of property maxConn.
+ * Gets maximum number of connections allowed.
+ * @return maximum connection number.
*
*/
public int getMaxConn() {
@@ -368,62 +308,51 @@ public int getMaxConn() {
}
/**
- * Setter for property maxConn.
- *
- * @param maxConn
- * New value of property maxConn.
- *
+ * Sets maximum number of connections allowed.
+ * @param maxConn connections allowed.
*/
public void setMaxConn(int maxConn) {
this.maxConn = maxConn;
}
/**
- * Getter for property URL.
- *
- * @return Value of property URL.
+ * Gets the URL connection String for this pool.
+ * @return URL connection String.
*
*/
- public java.lang.String getURL() {
+ public String getURL() {
return url;
}
/**
- * Setter for property URL.
- *
- * @param url
- * New value of property URL.
- *
+ * Sets the URL connection String for this pool. Special tag apppath is replaced
+ * by application path.
+ * @param url URL connection String.
*/
- public void setURL(java.lang.String url) {
+ public void setURL(String url) {
this.url = SWBUtils.TEXT.replaceAll(url, "{apppath}", SWBUtils.getApplicationPath());
}
/**
- * Getter for property user.
- *
- * @return Value of property user.
+ * Gets the connection user.
+ * @return connection user.
*
*/
- public java.lang.String getUser() {
+ public String getUser() {
return user;
}
/**
- * Setter for property user.
- *
- * @param user
- * New value of property user.
- *
+ * Sets the connection user.
+ * @param user user.
*/
- public void setUser(java.lang.String user) {
+ public void setUser(String user) {
this.user = user;
}
/**
- * Gets the hits.
- *
- * @return Regresa las total de solicitudes de conexiones
+ * Gets total count of connection requests.
+ * @return connection request count.
*/
public long getHits() {
return hits;
@@ -431,18 +360,15 @@ public long getHits() {
/**
* Gets the hits time.
- *
- * @return Regresa las total de solicitudes de conexiones
+ * @return hits time.
*/
public long getHitsTime() {
return hitsTime / 100;
}
/**
- * Adds the hit.
- *
- * @param time
- * the time
+ * Adds a hit.
+ * @param time hit time.
*/
public void addHit(long time) {
long ttime = time * 100;
@@ -451,17 +377,18 @@ public void addHit(long time) {
}
/**
- * Gets the connection manager.
- *
- * @return the connection manager
- * @return
+ * Gets the {@link DBConnectionManager} object managed by the Pool.
+ * @return the connection manager.
*/
public DBConnectionManager getConnectionManager() {
return manager;
}
+ /**
+ * Gets the Pool idle time.
+ * @return idle time.
+ */
public long getIdleTime() {
- return idle_time;
+ return idleTime;
}
-
}
diff --git a/src/main/java/org/semanticwb/base/db/PoolConnection.java b/src/main/java/org/semanticwb/base/db/PoolConnection.java
index 73e6971..b3f4559 100644
--- a/src/main/java/org/semanticwb/base/db/PoolConnection.java
+++ b/src/main/java/org/semanticwb/base/db/PoolConnection.java
@@ -22,89 +22,47 @@
*/
package org.semanticwb.base.db;
+import org.semanticwb.Logger;
+import org.semanticwb.SWBUtils;
+
import java.io.PrintStream;
-import java.sql.Array;
-import java.sql.Blob;
-import java.sql.CallableStatement;
-import java.sql.Clob;
-import java.sql.Connection;
-import java.sql.DatabaseMetaData;
-import java.sql.NClob;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLClientInfoException;
-import java.sql.SQLException;
-import java.sql.SQLWarning;
-import java.sql.SQLXML;
-import java.sql.Statement;
-import java.sql.Struct;
+import java.sql.*;
import java.util.ArrayList;
import java.util.Properties;
import java.util.concurrent.Executor;
-import org.semanticwb.Logger;
-import org.semanticwb.SWBUtils;
-
/**
- * Una conexión (sesión) con una base de datos. Sentencias SQL son ejecutadas y
- * los resultados se obtienen dentro del contexto de la conexión.
- *
- * Un objeto PoolConnection con una base de datos puede proporcionar la
- * información que describe sus tablas, soporta la gramática SQL, los
- * procedimientos almacenados, las capacidades de esta conexión, etc. Esta
- * información se obtiene con el método getMetaData().}
- *
+ * Custom implementation of a Database connection.
* @author Javier Solis Gonzalez (jsolis@infotec.com.mx)
*
* @see java.sql.Connection
*/
public class PoolConnection implements java.sql.Connection {
-
- /** The log. */
private static Logger log = SWBUtils.getLogger(PoolConnection.class);
-
- /** The con. */
- private java.sql.Connection con = null;
-
- /** The vec. */
- private ArrayList