diff --git a/pom.xml b/pom.xml index 668a54f..a29b7e5 100644 --- a/pom.xml +++ b/pom.xml @@ -43,7 +43,6 @@ maven-source-plugin 3.0.1 - false true @@ -76,7 +75,7 @@ org.apache.commons commons-email - 1.4 + 1.5 commons-fileupload @@ -101,11 +100,6 @@ 7.0 provided - - com.sun.xml.bind.jaxb - isorelax - 20090621 - net.java.dev.msv msv-core diff --git a/src/main/java/org/semanticwb/Logger.java b/src/main/java/org/semanticwb/Logger.java index f7a4d13..9b0cc2f 100644 --- a/src/main/java/org/semanticwb/Logger.java +++ b/src/main/java/org/semanticwb/Logger.java @@ -51,7 +51,7 @@ public interface Logger { * @param t * a throwable object indicating an exceptional condition */ - public void trace(String txt, Throwable t); + void trace(String txt, Throwable t); /** * Registers a message to provide information about an exceptional condition in @@ -64,7 +64,7 @@ public interface Logger { * @param txt * a string representing the message to include in the app's log */ - public void trace(String txt); + void trace(String txt); /** * Registers the elements of the execution stack at the moment it is called to @@ -79,7 +79,7 @@ public interface Logger { * @param t * a throwable object indicating an exceptional condition */ - public void trace(Throwable t); + void trace(Throwable t); /* * Los 3 siguientes metodos son usados para debugueos sencillos @@ -98,7 +98,7 @@ public interface Logger { * @param t * a throwable object indicating an exceptional condition */ - public void debug(String txt, Throwable t); + void debug(String txt, Throwable t); /** * Registers a message to provide information about an exceptional condition. @@ -110,7 +110,7 @@ public interface Logger { * @param txt * a string representing the message to include in the app's log */ - public void debug(String txt); + void debug(String txt); /** * Registers an exceptional condition in the execution of the current thread. @@ -122,7 +122,7 @@ public interface Logger { * @param t * a throwable object indicating an exceptional condition */ - public void debug(Throwable t); + void debug(Throwable t); /* * Los 3 siguientes metodos son usados para Informacion del Sistema @@ -135,7 +135,7 @@ public interface Logger { * @param t * a throwable object indicating an exceptional condition */ - public void info(String txt, Throwable t); + void info(String txt, Throwable t); /** * Registers a message to provide detail on an exceptional condition. @@ -143,7 +143,7 @@ public interface Logger { * @param txt * a string representing the message to include in the app's log */ - public void info(String txt); + void info(String txt); /** * Registers an exceptional condition in an informative manner. @@ -151,7 +151,7 @@ public interface Logger { * @param t * a throwable object indicating an exceptional condition */ - public void info(Throwable t); + void info(Throwable t); /* * Los 3 siguientes metodos son usados para registrar advertencias @@ -168,7 +168,7 @@ public interface Logger { * @param t * a throwable object indicating an exceptional condition */ - public void warn(String txt, Throwable t); + void warn(String txt, Throwable t); /** * Registers a message as a warning on an exceptional condition generated. @@ -180,7 +180,7 @@ public interface Logger { * @param txt * a string representing the message to include in the app's log */ - public void warn(String txt); + void warn(String txt); /** * Registers data as a warning on an exceptional condition generated. @@ -192,7 +192,7 @@ public interface Logger { * @param t * a throwable object indicating an exceptional condition */ - public void warn(Throwable t); + void warn(Throwable t); /* * Los 3 siguientes metodos son usados para registrar errores @@ -208,7 +208,7 @@ public interface Logger { * @param t * a throwable object indicating an exceptional condition */ - public void error(String txt, Throwable t); + void error(String txt, Throwable t); /** * Registers a message to report an error in the application. @@ -219,7 +219,7 @@ public interface Logger { * @param txt * a string representing the message to include in the app's log */ - public void error(String txt); + void error(String txt); /** * Registers data to report an error in the application. @@ -230,7 +230,7 @@ public interface Logger { * @param t * a throwable object indicating an exceptional condition */ - public void error(Throwable t); + void error(Throwable t); /* * Los 3 siguientes metodos son usados para registrar excepciones en tiempo de @@ -248,7 +248,7 @@ public interface Logger { * @param t * a throwable object indicating an exceptional condition */ - public void fatal(String txt, Throwable t); + void fatal(String txt, Throwable t); /** * Registers a message about an exceptional condition generated at runtime. @@ -260,7 +260,7 @@ public interface Logger { * @param txt * a string representing the message to include in the app's log */ - public void fatal(String txt); + void fatal(String txt); /** * Registers data of an exceptional condition generated at runtime. @@ -272,7 +272,7 @@ public interface Logger { * @param t * a throwable object indicating an exceptional condition */ - public void fatal(Throwable t); + void fatal(Throwable t); /* * Los 3 siguientes metodos son usados para notificar eventos @@ -288,7 +288,7 @@ public interface Logger { * @param t * a throwable object indicating an exceptional condition */ - public void event(String txt, Throwable t); + void event(String txt, Throwable t); /** * Registers a message when certain event occurs. @@ -299,7 +299,7 @@ public interface Logger { * @param txt * a string representing the message to include in the app's log */ - public void event(String txt); + void event(String txt); /** * Registers data when certain event occurs. @@ -310,26 +310,26 @@ public interface Logger { * @param t * a throwable object indicating an exceptional condition */ - public void event(Throwable t); + void event(Throwable t); /** * Regresa true si el nivel de loggeo es debug * * @return */ - public boolean isDebugEnabled(); + boolean isDebugEnabled(); /** * Regresa true si el nivel de loggeo es trace * * @return */ - public boolean isTraceEnabled(); + boolean isTraceEnabled(); /** * Regresa true si el nivel de loggeo es info * * @return */ - public boolean isInfoEnabled(); + boolean isInfoEnabled(); } diff --git a/src/main/java/org/semanticwb/SWBException.java b/src/main/java/org/semanticwb/SWBException.java index 388c48b..2dd9e3e 100644 --- a/src/main/java/org/semanticwb/SWBException.java +++ b/src/main/java/org/semanticwb/SWBException.java @@ -27,46 +27,42 @@ *

* La excepción genérica en el API de SemanticWebBuilder. *

- * + * * @author Javier Solis Gonzalez * @version 1.1 */ public class SWBException extends java.lang.Exception { - /** - * Generates an instance of this exception with a specified detail message. - *

- * Genera una instancia de esta excepción con un mensaje de detalle - * especificado. - *

- * - * @param msg - * the detail message (which is saved for later retrieval by the - * {@link Throwable.getMessage() Throwable.getMessage()} method) - */ - public SWBException(String msg) { - super(msg); - } + /** + * Generates an instance of this exception with a specified detail message. + *

+ * Genera una instancia de esta excepción con un mensaje de detalle + * especificado. + *

+ * + * @param msg the detail message (which is saved for later retrieval by the {@link #getMessage()} method) + */ + public SWBException(String msg) { + super(msg); + } - /** - * Generates an instance of this exception with the specified detail message and - * cause. - *

- * Genera una instancia de esta excepción con el mensaje de detalle y - * causa especificados. - *

- * - * @param msg - * the detail message (which is saved for later retrieval by the - * Throwable.getMessage() method) - * @param e - * the cause (which is saved for later retrieval by the - * {@link Throwable.getCause() Throwable.getCause()} method). (A - * {@code null} value is permitted, and indicates that the cause is - * nonexistent or unknown.) - */ - public SWBException(String msg, Exception e) { - super(msg, e); - } + /** + * Generates an instance of this exception with the specified detail message and + * cause. + *

+ * Genera una instancia de esta excepción con el mensaje de detalle y + * causa especificados. + *

+ * + * @param msg the detail message (which is saved for later retrieval by the + * Throwable.getMessage() method) + * @param e the cause (which is saved for later retrieval by the + * {@link #getCause()} method). (A + * {@code null} value is permitted, and indicates that the cause is + * nonexistent or unknown.) + */ + public SWBException(String msg, Exception e) { + super(msg, e); + } } diff --git a/src/main/java/org/semanticwb/SWBMethodImplementationRequiredException.java b/src/main/java/org/semanticwb/SWBMethodImplementationRequiredException.java index ec11ea5..33fa08f 100644 --- a/src/main/java/org/semanticwb/SWBMethodImplementationRequiredException.java +++ b/src/main/java/org/semanticwb/SWBMethodImplementationRequiredException.java @@ -48,9 +48,7 @@ public SWBMethodImplementationRequiredException() { * especificado. *

* - * @param msg - * the detail message (which is saved for later retrieval by the - * {@link Throwable.getMessage() Throwable.getMessage()} method) + * @param msg the detail message (which is saved for later retrieval by the {@link #getMessage()} method) */ public SWBMethodImplementationRequiredException(String msg) { super(msg); @@ -69,7 +67,7 @@ public SWBMethodImplementationRequiredException(String msg) { * Throwable.getMessage() method) * @param e * the cause (which is saved for later retrieval by the - * {@link Throwable.getCause() Throwable.getCause()} method). (A + * {@link #getCause()} method). (A * {@code null} value is permitted, and indicates that the cause is * nonexistent or unknown.) */ diff --git a/src/main/java/org/semanticwb/SWBRuntimeException.java b/src/main/java/org/semanticwb/SWBRuntimeException.java index 1f9ced1..53691db 100644 --- a/src/main/java/org/semanticwb/SWBRuntimeException.java +++ b/src/main/java/org/semanticwb/SWBRuntimeException.java @@ -49,7 +49,7 @@ public SWBRuntimeException() { * * @param msg * the detail message (which is saved for later retrieval by the - * {@link Throwable.getMessage() Throwable.getMessage()} method) + * {@link #getMessage()} method) */ public SWBRuntimeException(String msg) { super(msg); @@ -68,7 +68,7 @@ public SWBRuntimeException(String msg) { * Throwable.getMessage() method) * @param e * the cause (which is saved for later retrieval by the - * {@link Throwable.getCause() Throwable.getCause()} method). (A + * {@link #getCause()} method). (A * {@code null} value is permitted, and indicates that the cause is * nonexistent or unknown.) */ diff --git a/src/main/java/org/semanticwb/SWBUtils.java b/src/main/java/org/semanticwb/SWBUtils.java index 61f824e..a0f7440 100644 --- a/src/main/java/org/semanticwb/SWBUtils.java +++ b/src/main/java/org/semanticwb/SWBUtils.java @@ -22,82 +22,6 @@ */ package org.semanticwb; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.ObjectOutput; -import java.io.ObjectOutputStream; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.Reader; -import java.io.StringReader; -import java.io.StringWriter; -import java.io.UnsupportedEncodingException; -import java.math.BigInteger; -import java.net.SocketException; -import java.security.GeneralSecurityException; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.sql.Connection; -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collection; -import java.util.Date; -import java.util.Enumeration; -import java.util.Formatter; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Properties; -import java.util.StringTokenizer; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; -import java.util.zip.ZipInputStream; -import java.util.zip.ZipOutputStream; - -import javax.crypto.Cipher; -import javax.crypto.SecretKey; -import javax.crypto.spec.DHParameterSpec; -import javax.crypto.spec.SecretKeySpec; -import javax.mail.internet.InternetAddress; -import javax.xml.namespace.QName; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Result; -import javax.xml.transform.Source; -import javax.xml.transform.Templates; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; -import javax.xml.transform.stream.StreamSource; -import javax.xml.xpath.XPath; -import javax.xml.xpath.XPathConstants; -import javax.xml.xpath.XPathExpressionException; -import javax.xml.xpath.XPathFactory; - import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; @@ -109,14 +33,7 @@ import org.semanticwb.base.db.DBConnectionManager; import org.semanticwb.base.db.DBConnectionPool; import org.semanticwb.base.db.PoolConnectionTimeLock; -import org.semanticwb.base.util.ErrorElement; -import org.semanticwb.base.util.FilterRule; -import org.semanticwb.base.util.GenericFilterRule; -import org.semanticwb.base.util.SFBase64; -import org.semanticwb.base.util.SWBMail; -import org.semanticwb.base.util.SWBMailSender; -import org.semanticwb.base.util.SWBProperties; -import org.semanticwb.base.util.SimpleDateFormatTS; +import org.semanticwb.base.util.*; import org.semanticwb.base.util.imp.Logger4jImpl; import org.semanticwb.base.util.parser.html.HTMLParser; import org.w3c.dom.Document; @@ -125,6 +42,43 @@ import org.w3c.dom.NodeList; import org.xml.sax.InputSource; +import javax.crypto.Cipher; +import javax.crypto.SecretKey; +import javax.crypto.spec.DHParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import javax.mail.internet.InternetAddress; +import javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.*; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; +import java.io.*; +import java.math.BigInteger; +import java.net.SocketException; +import java.net.URL; +import java.net.URLEncoder; +import java.nio.file.Files; +import java.security.*; +import java.sql.Connection; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.jar.Attributes; +import java.util.jar.Manifest; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; +import java.util.zip.ZipInputStream; +import java.util.zip.ZipOutputStream; + /** * Contains utilities for managing error logs, text, database, IO, Zip files, * emails, Xml, Xslt , Dom, Collections and encryption @@ -148,7 +102,7 @@ public class SWBUtils { * bitácoras. *

*/ - private static Logger log = getLogger(SWBUtils.class); + private static final Logger LOG = getLogger(SWBUtils.class); /** * Holds a reference to an object of this class. *

@@ -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 for System.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 ArrayList errorElement = new ArrayList<>(); + private static List errorElement = new ArrayList<>(); /** * Specifies the number of error elements to show in the administration site's * error viewer. @@ -227,17 +181,14 @@ public class SWBUtils { */ private static int errorElementSize = 200; - // private static java.security.KeyPair RSA512key = - // SWBUtils.CryptoWrapper.genRSA512KeyPair(); /** * Creates a new object of this class. */ private SWBUtils() { - - SWBUtils.log.event("Initializing SemanticWebBuilder Base..."); - SWBUtils.log.event("-->AppicationPath: " + SWBUtils.applicationPath); + LOG.event("Initializing SemanticWebBuilder Base..."); + LOG.event("-->AppicationPath: " + SWBUtils.applicationPath); init(); - SWBUtils.log.event("-->Default Encoding: " + TEXT.getDafaultEncoding()); + LOG.event("-->Default Encoding: " + TEXT.getDafaultEncoding()); } /** @@ -251,23 +202,19 @@ private SWBUtils() { * @return a reference to the only one existing object of this class */ public static synchronized SWBUtils createInstance(String applicationPath) { - SWBUtils.applicationPath = IO.normalizePath(applicationPath); - if (SWBUtils.instance == null) { + if (instance == null) { initFileLogger(); - SWBUtils.instance = new SWBUtils(); + instance = new SWBUtils(); } - return SWBUtils.instance; + return instance; } - /* + /** * Initializes the class variables needed to provide this object's services *

Inicializa 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 getErrorElements() { - return new ArrayList(SWBUtils.errorElement).iterator(); + return new ArrayList<>(errorElement).iterator(); } /** @@ -436,7 +406,7 @@ public static Iterator getErrorElements() { * @return the value of the class member {@code SWBUtils.errorElementSize}. */ public static int getErrorElementSize() { - return SWBUtils.errorElementSize; + return errorElementSize; } /** @@ -445,12 +415,12 @@ public static int getErrorElementSize() { * Asigna el valor de la variable de clase {@code SWBUtils.errorElementSize}. *

* - * @param errorElementSize + * @param size * the new value of the class member * {@code SWBUtils.errorElementSize}. */ - public static void setErrorElementSize(int errorElementSize) { - SWBUtils.errorElementSize = errorElementSize; + public static void setErrorElementSize(int size) { + errorElementSize = size; } } @@ -467,13 +437,14 @@ public static void setErrorElementSize(int errorElementSize) { public static class TEXT { private TEXT() {} - + /** * Specifies the value for the charset ISO8859-1. *

* 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:
+ * + * @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. + *

+ */ + 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 regExpSplit(String txt, String regexp) { * */ public static Iterator findInterStr(String str, String pre, String pos) { - ArrayList ret = new ArrayList<>(); + List ret = new ArrayList<>(); int y = 0; do { y = findInterStr(str, pre, pos, y, ret); @@ -1450,6 +1422,7 @@ public static Iterator findInterStr(String str, String pre, String pos) } /** + * @deprecated Use {@link #findInterStr(String, String, String, int, List)} * Finds a substring in {@code str} which position must be after {@code index} * and is delimited by {@code pre} and {@code pos} strings. The substring found * is then stored in {@code arr}. @@ -1476,8 +1449,39 @@ public static Iterator findInterStr(String str, String pre, String pos) * {@code pre} no es encontrado en {@code str}. *

*/ + @Deprecated private static int findInterStr(String str, String pre, String pos, int index, ArrayList arr) { + return findInterStr(str, pre, pos, index, arr); + } + /** + * Finds a substring in {@code str} which position must be after {@code index} + * and is delimited by {@code pre} and {@code pos} strings. The substring found + * is then stored in {@code arr}. + *

+ * 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 arr) { int i = str.indexOf(pre, index); if (i > -1) { i = i + pre.length(); @@ -1493,8 +1497,8 @@ private static int findInterStr(String str, String pre, String pos, int index, A /** * @deprecated * This method is locale dependent implementation and will be removed in future API versions. - * Use DateFormat methods instead. - * + * Use DateFormat methods instead. + * * Obtains the day's name corresponding to the number received specifying the * day of the week. The first day of the week is Sunday and its day number is * zero. @@ -1525,7 +1529,7 @@ public static String getStrDay(int day, String lang) { * @deprecated * This method is locale dependent implementation and will be removed in future API versions. * Use DateFormat methods instead. - * + * * Obtains the month's name corresponding to the number received specifying the * month of the year. The first month of the year is January and its * corresponding number is zero. @@ -1590,7 +1594,7 @@ public static String getStrDate(Date date, String lang) { * en el lenguaje y con el formato especificados. */ public static String getStrDate(Date date, String lang, String format) { - String ret = ""; + String ret; if (format != null) { ret = getStrFormat(date, format, lang); } else if (lang != null) { @@ -1601,7 +1605,7 @@ public static String getStrDate(Date date, String lang, String format) { DateFormat df = new SimpleDateFormat(); ret = df.format(date); } - + if (ret == null || ret.length() == 0) { DateFormat df = new SimpleDateFormat(); ret = df.format(date); @@ -1639,7 +1643,7 @@ private static String getStrFormat(Date date, String format, String lang) { if (null != lang && !lang.isEmpty()) { ln = lang; } - + Locale loc = new Locale(ln); String dayName = new SimpleDateFormat("EEEE", loc).format(date); String dayNumber = new SimpleDateFormat("dd", loc).format(date); @@ -1650,7 +1654,7 @@ private static String getStrFormat(Date date, String format, String lang) { String hour = new SimpleDateFormat("hh", loc).format(date); String minute = new SimpleDateFormat("mm", loc).format(date); String second = new SimpleDateFormat("ss", loc).format(date); - + String ret = format; ret = replaceAll(ret, "Day", dayName.substring(0,1).toUpperCase() + dayName.substring(1)); ret = replaceAll(ret, "DAY", dayName.toUpperCase()); @@ -1679,7 +1683,7 @@ private static String getStrFormat(Date date, String format, String lang) { * meses y años. *

* - * @param CreationDate + * @param creationDate * the date to compare * @param lang * a string indicating the language in which the date is going to be @@ -1705,9 +1709,9 @@ public static String getTimeAgo(Date creationDate, String lang) { * años. *

* - * @param CurrentDate + * @param currentDate * the most recent date to compare - * @param CreationDate + * @param creationDate * the oldest date to compare * @param lang * a string indicating the language in which the date is going to be @@ -1717,6 +1721,7 @@ public static String getTimeAgo(Date creationDate, String lang) { * representa la diferencia entre dos fechas dadas, expresada en la * unidad de tiempo más grande posible. */ + //TODO: Refactor method to return single time unit and remove unit conversion and labeling public static String getTimeAgo(Date currentDate, Date creationDate, String lang) { String ret = ""; int second; @@ -1831,6 +1836,7 @@ public static String getTimeAgo(Date currentDate, Date creationDate, String lang yearCurrent = yearCurrent - 1; } + //TODO: Move specific labeling outside method year = yearCurrent - yearCreation; if ("en".equals(lang)) { if (year > 0) { @@ -1864,29 +1870,6 @@ public static String getTimeAgo(Date currentDate, Date creationDate, String lang return ret; } - /** - * Converts an integer into a string and adds a zero to the left if that integer - * has only one digit. - *

- * 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 parseQueryParams(String path) { } /** + * @deprecated Use {@link #getPropertiesFile(String)} * Creates a properties object from the file whose name equals the value of the * parameter {@code name}. *

@@ -1940,13 +1924,36 @@ public static Map parseQueryParams(String path) { * parámetro {@code name}. *

*/ + @Deprecated public static Properties getPropertyFile(String name) { + return getPropertiesFile(name); + } + + /** + * Creates a properties object from the file whose name equals the value of the + * parameter {@code name}. + *

+ * 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 fileUpload(javax.servlet.http.HttpServletRequest request, String path2Save) { - + public static Iterator fileUpload(javax.servlet.http.HttpServletRequest request, String destPath) { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload fu = new ServletFileUpload(factory); List items = null; + try { items = fu.parseRequest(request); } catch (FileUploadException e) { - e.printStackTrace(); + LOG.error(e); } - if (items != null && path2Save == null) { + + if (items != null && destPath == null) { return items.iterator(); - } else if (items != null && path2Save != null) { + } else if (items != null) { Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); // Si No es un campo de forma comun, es un campo tipo file, grabarlo if (!item.isFormField()) { - File fichero = new File(path2Save + item.getName()); + File fichero = new File(destPath + item.getName()); try { item.write(fichero); } catch (Exception e) { - SWBUtils.log.error(e); + LOG.error(e); } } } @@ -2941,8 +3123,8 @@ public static void log2File(String filePath, String msg) throws IOException { file.mkdirs(); } String logFile = new File(filePath).getCanonicalPath().replace('\\', '/'); - SWBUtils.log2File = new PrintWriter(new FileWriter(logFile, true), true); - SWBUtils.log2File.println(msg); + fileLogWriter = new PrintWriter(new FileWriter(logFile, true), true); + fileLogWriter.println(msg); } /** @@ -2974,41 +3156,39 @@ public static void log2File(String filePath, String msg) throws IOException { * Signals that an I/O exception has occurred. * @author Jorge Jiménez */ - public static final void zip(File directory, File base, ZipOutputStream zos) throws IOException { - + public static void zip(File directory, File base, ZipOutputStream zos) throws IOException { if (directory == null || !directory.exists()) { - return; + throw new FileNotFoundException(); } - byte[] buffer = new byte[SWBUtils.bufferSize]; - int read = 0; + byte[] buffer = new byte[bufferSize]; + int read; File[] files = directory.listFiles(); - for (int i = 0, n = files.length; i < n; i++) { - if (files[i].isDirectory()) { - zip(files[i], base, zos); - } else { - try (FileInputStream in = new FileInputStream(files[i])) { - ZipEntry entry = new ZipEntry(files[i].getPath().substring(base.getPath().length() + 1)); - zos.putNextEntry(entry); - while (-1 != (read = in.read(buffer))) { - zos.write(buffer, 0, read); + + if (null != files) { + for (File fi : files) { + if (fi.isDirectory()) { + zip(fi, base, zos); + } else { + try (FileInputStream in = new FileInputStream(fi)) { + ZipEntry entry = new ZipEntry(fi.getPath().substring(base.getPath().length() + 1)); + zos.putNextEntry(entry); + while (-1 != (read = in.read(buffer))) { + zos.write(buffer, 0, read); + } + zos.closeEntry(); + } catch (FileNotFoundException e) { + LOG.error(e); } - zos.closeEntry(); - in.close(); - } catch (FileNotFoundException e) { - log.error(e); } } } } /** - * Checks if is uT f8. - * - * @param file - * the file - * @return true, if is uT f8 - * @throws IOException - * Signals that an I/O exception has occurred. + * Checks whether a fine is UTF-8 encoded. + * @param file the file + * @return true, if the file is UTF-8 encoded. + * @throws IOException Signals that an I/O exception has occurred. */ public static boolean isUTF8(File file) throws IOException { int c3 = -61; @@ -3028,6 +3208,7 @@ public static boolean isUTF8(File file) throws IOException { } /** + * @deprecated Use {@link #addFilesToZip(File, File[])} * Adds the files received to the specified zip file. *

* 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(), null, null); + public static void unzip(File zip, File destPath) throws IOException { + unzip(zip, destPath, new ArrayList<>(), null, null); } /** @@ -3160,17 +3365,13 @@ public static final void unzip(File zip, File extractTo) throws IOException { * Signals that an I/O exception has occurred. * @author Jorge Jiménez */ - public static final void unzip(File zip, File extractTo, ArrayList fext2parse, String parse, - String parse2) throws IOException { - + public static final void unzip(File zip, File destPath, ArrayList fext2parse, String parse, String parse2) throws IOException { ZipFile archive = new ZipFile(zip); Enumeration e = archive.entries(); while (e.hasMoreElements()) { ZipEntry entry = (ZipEntry) e.nextElement(); - File file = new File(extractTo, TEXT.replaceAll(entry.getName(), "\\", "/")); // TODO:Pienso que con - // esto se soluciona el - // problema de creación - // de rutas en linux + // TODO:Pienso que con esto se soluciona el problema de creación de rutas en linux + File file = new File(destPath, TEXT.replaceAll(entry.getName(), "\\", "/")); if (entry.isDirectory() && !file.exists()) { file.mkdirs(); } else { @@ -3187,7 +3388,7 @@ public static final void unzip(File zip, File extractTo, ArrayList fext2 ext = file.getName().substring(pos + 1); } if (fext2parse.contains(ext)) { - String content = readInputStream(in); + String content = getStringFromInputStream(in); content = content.replaceAll(parse, parse2); in = getStreamFromString(content); } @@ -3200,7 +3401,7 @@ public static final void unzip(File zip, File extractTo, ArrayList fext2 out.close(); in.close(); } catch (Exception ex) { - SWBUtils.log.debug(ex); + LOG.debug(ex); } } } @@ -3222,20 +3423,18 @@ public static final void unzip(File zip, File extractTo, ArrayList fext2 * contiene todas las entradas (archivos) contenidas en el archivo * comprimido. */ - public static final Iterator readZip(String zipName) { - ArrayList itFiles = new ArrayList<>(); + public static Iterator readZip(String zipName) { + List itFiles = new ArrayList<>(); try (ZipFile zf = new ZipFile(zipName)) { Enumeration enu = zf.entries(); while (enu.hasMoreElements()) { ZipEntry zen = (ZipEntry) enu.nextElement(); - if (zen.isDirectory()) { - continue; - } else { + if (!zen.isDirectory()) { itFiles.add(zen); } } } catch (Exception ex) { - SWBUtils.log.error(ex); // MAPS74 + LOG.error(ex); // MAPS74 } return itFiles.iterator(); } @@ -3255,18 +3454,18 @@ public static final Iterator readZip(String zipName) { * * @author Jorge Jiménez */ - public static final String readFileFromZipAsString(String zipName, String file2Read) { + public static String readFileFromZipAsString(String zipName, String file2Read) { String content = null; try (ZipFile zip = new ZipFile(new File(zipName))) { for (Enumeration e = zip.entries(); e.hasMoreElements();) { ZipEntry entry = (ZipEntry) e.nextElement(); if (entry.getName() != null && entry.getName().equals(file2Read)) { InputStream is = zip.getInputStream(entry); - content = readInputStream(is); + content = getStringFromInputStream(is); } } } catch (Exception e) { - SWBUtils.log.debug(e); + LOG.debug(e); } return content; } @@ -3282,7 +3481,7 @@ public static final String readFileFromZipAsString(String zipName, String file2R * @author Jorge Jiménez */ public static class EMAIL { - + private EMAIL () {} /** @@ -3338,11 +3537,11 @@ private EMAIL () {} /** * Sets the sMTP ssl. * - * @param ssl + * @param val * the new sMTP ssl */ - public static void setSMTPSsl(boolean ssl) { - SWBUtils.EMAIL.smtpssl = ssl; + public static void setSMTPSsl(boolean val) { + smtpssl = val; } /** @@ -3351,7 +3550,7 @@ public static void setSMTPSsl(boolean ssl) { * Fija el nombre de dominio o la dirección IP del servidor SMTP a usar. *

* - * @param smtpserver + * @param val * a string representing the domain name or the IP address for the * SMTP server. *

@@ -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 address, - Collection ccEmail, Collection bccEmail, String subject, - String contentType, String data, String login, String password, - ArrayList attachments) { - String ret = null; - try { - HtmlEmail email = new HtmlEmail(); - if (SWBUtils.EMAIL.smtpssl) { - email.setSSLOnConnect(SWBUtils.EMAIL.smtpssl); - } - - if (attachments != null && !attachments.isEmpty()) { - Iterator itAttaches = attachments.iterator(); - while (itAttaches.hasNext()) { - EmailAttachment attchment = itAttaches.next(); - email.attach(attchment); - } - } + @Deprecated + public static String sendMail(String senderEmail, String senderName, Collection recipients, + Collection ccRecipients, Collection bccRecipients, String subject, + String contentType, String body, String login, String password, List attachments) { - email.setHostName(SWBUtils.EMAIL.smtpserver); - if (SWBUtils.EMAIL.smtpport > 0) { - if (SWBUtils.EMAIL.smtpssl) { - email.setSslSmtpPort(Integer.toString(SWBUtils.EMAIL.smtpport) + ")");//Por qué tiene un )? - email.setSmtpPort(SWBUtils.EMAIL.smtpport); - } else { - email.setSmtpPort(SWBUtils.EMAIL.smtpport); - } - } - email.setFrom(fromEmail, fromName); - email.setTo(address); - if (ccEmail != null) { - email.setCc(ccEmail); - } - if (bccEmail != null) { - email.setBcc(bccEmail); - } - email.setSubject(subject); + SWBMail mail = new SWBMail(); + mail.setSenderEmail(senderEmail); + mail.setSenderName(senderName); + mail.setRecipients(recipients); + mail.setCcRecipients(ccRecipients); + mail.setBccRecipients(bccRecipients); + mail.setSubject(subject); + mail.setContentType(contentType); + mail.setMessage(body); + mail.setLogin(login); + mail.setPassword(password); + mail.setAttachments(attachments); - if (contentType != null && contentType.toLowerCase().indexOf("html") != -1) { - email.setHtmlMsg(data); // set the html message - } else { - email.setMsg(data); - } - // Set authentication default to config, as in sendBGEmail method - if (null != SWBUtils.EMAIL.smtpuser && null != SWBUtils.EMAIL.smtppassword) { - email.setAuthenticator(new DefaultAuthenticator(EMAIL.smtpuser, EMAIL.smtppassword)); - } - if (login != null && password != null) { - email.setAuthenticator(new DefaultAuthenticator(login, password)); - } - if (SWBUtils.EMAIL.smtptls) { - email.setStartTLSEnabled(true); - } - ret = email.send(); - } catch (Exception e) { - SWBUtils.log.error(e); - } - return ret; + return sendMail(mail); } /** @@ -3549,51 +3708,58 @@ public static String sendMail(String fromEmail, String fromName, Collection itAttaches = message.getAttachments().iterator(); - while (itAttaches.hasNext()) { - EmailAttachment attchment = itAttaches.next(); - email.attach(attchment); - } - - email.setHostName(SWBUtils.EMAIL.smtpserver); - if (SWBUtils.EMAIL.smtpport > 0) { - email.setSmtpPort(SWBUtils.EMAIL.smtpport); - } - email.setFrom(message.getFromEmail(), message.getFromName()); - email.setTo(message.getAddresses()); - if (message.getCcEmail() != null) { - email.setCc(message.getCcEmail()); - } - if (message.getBccEmail() != null) { - email.setBcc(message.getBccEmail()); - } - email.setSubject(message.getSubject()); - - if (message.getContentType().equalsIgnoreCase("HTML")) { - email.setHtmlMsg(message.getData()); // set the html message - } else { - email.setTextMsg(message.getData()); - } - // Set authentication default to config, as in sendBGEmail method - if (null != SWBUtils.EMAIL.smtpuser && null != SWBUtils.EMAIL.smtppassword) { - email.setAuthentication(EMAIL.smtpuser, EMAIL.smtppassword); - } - if (message.getLogin() != null && message.getPassword() != null) { - email.setAuthentication(message.getLogin(), message.getPassword()); - } - if (SWBUtils.EMAIL.smtptls) { - email.setStartTLSEnabled(true); - } - ret = email.send(); - } catch (Exception e) { - SWBUtils.log.error(e); - } - return ret; + try { + HtmlEmail email = new HtmlEmail(); + email.setHostName(smtpserver); + email.setSSLOnConnect(smtpssl); + email.setStartTLSEnabled(smtptls); + email.setSSLCheckServerIdentity(smtpssl || smtptls); + + if (message.getAttachments() != null) { + for (EmailAttachment attachment: message.getAttachments()) { + email.attach(attachment); + } + } + + if (smtpport > 0) { + if (smtpssl) { + email.setSslSmtpPort(Integer.toString(smtpport)); + } + email.setSmtpPort(smtpport); + } + + email.setFrom(message.getSenderEmail(), message.getSenderName()); + email.setTo(message.getRecipients()); + + if (message.getCcRecipients() != null) { + email.setCc(message.getCcRecipients()); + } + + if (message.getBccRecipients() != null) { + email.setBcc(message.getBccRecipients()); + } + email.setSubject(message.getSubject()); + + if (message.getContentType() != null && message.getContentType().toLowerCase().contains("html")) { + email.setHtmlMsg(message.getMessage()); // set the html message + } else { + email.setMsg(message.getMessage()); + } + + // Set authentication default to config, as in sendBGEmail method + if (null != smtpuser && null != smtppassword) { + email.setAuthenticator(new DefaultAuthenticator(smtpuser, smtppassword)); + } + + if (message.getLogin() != null && message.getPassword() != null) { + email.setAuthenticator(new DefaultAuthenticator(message.getLogin(), message.getPassword())); + } + + return email.send(); + } catch (Exception e) { + LOG.error(e); + } + return null; } /** @@ -3604,7 +3770,7 @@ public static String sendMail(SWBMail message) { * {@code EMAIL.adminEmail}, requiriendo la información mínima. *

* - * @param toEmail + * @param recipient * toEmail a string representing the repicients' e-mail accounts. * This string can contain more than one e-mail accounts, * semicolon-separated. If it is {@code null} the e-mail will not be @@ -3622,32 +3788,22 @@ public static String sendMail(SWBMail message) { * @throws SocketException * the socket exception */ - public static String sendMail(String toEmail, String subject, String msg) { - try { - ArrayList acol = new ArrayList<>(); - if (toEmail != null && toEmail.indexOf(';') > 0) { - StringTokenizer strTokens = new StringTokenizer(toEmail, ";"); - while (strTokens.hasMoreTokens()) { - String token = strTokens.nextToken(); - if (token == null) { - continue; - } - InternetAddress address = new InternetAddress(); - address.setAddress(token); - acol.add(address); - } - } else if (toEmail != null) { - InternetAddress address = new InternetAddress(); - address.setAddress(toEmail); - acol.add(address); - } - // Send my with authentication information from config by default as in method - // sendBGEmail - SWBUtils.EMAIL.sendMail(SWBUtils.EMAIL.adminEmail, "", acol, null, null, subject, null, msg, - EMAIL.smtpuser, EMAIL.smtppassword, null); - } catch (Exception e) { - SWBUtils.log.error(e); + public static String sendMail(String recipient, String subject, String msg) { + if (null != recipient && null != subject && null != msg) { + List recipients = parseAddressList(recipient); + + SWBMail mail = new SWBMail(); + mail.setSenderEmail(adminEmail); + mail.setSenderName(""); + mail.setRecipients(recipients); + mail.setSubject(subject); + mail.setMessage(msg); + mail.setLogin(smtpuser); + mail.setPassword(smtppassword); + + return sendMail(mail); } + return null; } @@ -3659,7 +3815,7 @@ public static String sendMail(String toEmail, String subject, String msg) { * correo del remitente como la asignada a {@code EMAIL.adminEmail}. *

* - * @param toEmail + * @param recipient * a string representing the repicients' e-mail accounts. This string * can contain more than one e-mail accounts, semicolon-separated. If * it is {@code null} the e-mail will not be sent. @@ -3673,56 +3829,46 @@ public static String sendMail(String toEmail, String subject, String msg) { * si ocurre algún error en la creación del remitente * de correos. *

- * @throws SocketException - * the socket exception */ - public static void sendBGEmail(String toEmail, String subject, String body) throws java.net.SocketException { + public static void sendBGEmail(String recipient, String subject, String body) { + List recipients = parseAddressList(recipient); - ArrayList acol = new ArrayList<>(); - if (toEmail != null && toEmail.indexOf(';') > 0) { - StringTokenizer strTokens = new StringTokenizer(toEmail, ";"); - while (strTokens.hasMoreTokens()) { - String token = strTokens.nextToken(); - if (token == null) { - continue; - } - InternetAddress address = new InternetAddress(); - address.setAddress(token); - acol.add(address); - } - } else if (toEmail != null) { - InternetAddress address = new InternetAddress(); - address.setAddress(toEmail); - acol.add(address); - } - SWBUtils.EMAIL.sendBGEmail(SWBUtils.EMAIL.adminEmail, null, acol, null, null, subject, null, body, - SWBUtils.EMAIL.smtpuser, SWBUtils.EMAIL.smtppassword, null); + SWBMail mail = new SWBMail(); + mail.setSenderEmail(adminEmail); + mail.setRecipients(recipients); + mail.setSubject(subject); + mail.setMessage(body); + mail.setLogin(smtpuser); + mail.setPassword(smtppassword); + + sendBGEmail(mail); } /** - * Sends an e-mail in background mode with the information supplied. + * @deprecated Use {@link #sendBGEmail(SWBMail)} + * Sends an e-mail in background mode with the information supplied. *

* 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 address, - Collection ccEmail, Collection bccEmail, String subject, - String contentType, String data, String login, String password, ArrayList attachments) - throws java.net.SocketException { + @Deprecated + public static void sendBGEmail(String senderEmail, String senderName, Collection recipients, + Collection ccRecipients, Collection bccRecipients, String subject, + String contentType, String body, String login, String password, List attachments) { SWBMail message = new SWBMail(); - if (fromEmail == null && SWBUtils.EMAIL.adminEmail != null) { - fromEmail = SWBUtils.EMAIL.adminEmail; + message.setContentType(null == contentType ? "text/html" : contentType); + + if (senderEmail == null && adminEmail != null) { + senderEmail = adminEmail; } - if (fromEmail != null) { - message.setFromEmail(fromEmail); + + if (senderEmail != null) { + message.setSenderEmail(senderEmail); } - if (fromName != null) { - message.setFromName(fromName); + + if (senderName != null) { + message.setSenderName(senderName); } - if (address != null) { - message.setAddress((ArrayList) address); + + if (recipients != null) { + message.setRecipients(recipients); } - if (ccEmail != null) { - message.setCcEmail(ccEmail); + + if (ccRecipients!= null) { + message.setCcRecipients(ccRecipients); } - if (bccEmail != null) { - message.setBccEmail(bccEmail); + + if (bccRecipients != null) { + message.setBccRecipients(bccRecipients); } + if (subject != null) { message.setSubject(subject); } - if (contentType == null) { - contentType = "text/html"; - } - if (contentType != null) { - message.setContentType(contentType); - } - if (data != null) { - message.setData(data); + + if (body != null) { + message.setMessage(body); } - if (SWBUtils.EMAIL.smtpuser != null) { - message.setLogin(SWBUtils.EMAIL.smtpuser); + + if (smtpuser != null) { + message.setLogin(smtpuser); } + if (login != null) { message.setLogin(login); } - if (SWBUtils.EMAIL.smtppassword != null) { - message.setPassword(SWBUtils.EMAIL.smtppassword); + + if (smtppassword != null) { + message.setPassword(smtppassword); } + if (password != null) { message.setPassword(password); } + if (attachments != null) { message.setAttachments(attachments); } - SWBMailSender swbMailSender = new SWBMailSender(); - swbMailSender.addEMail(message); - swbMailSender.start(); + sendBGEmail(message); + } + + /** + * Parses a semi-colon separated list of e-mail addresses. No address validation is performed. + * @param addressList semi-colon separated list of e-mail addresses. + * @return List of parsed {@link InternetAddress} objects. + */ + private static List parseAddressList(String addressList) { + ArrayList recipients = new ArrayList<>(); + + if (null != addressList && !addressList.isEmpty()) { + String[] addresses; + if (addressList.contains(";")) { + addresses = addressList.split(";"); + for (int i = 0; i < addresses.length; i++) { + addresses[i] = addresses[i].trim(); + } + } else { + addresses = new String[1]; + addresses[0] = addressList.trim(); + } + + for (String address : addresses) { + InternetAddress iaddress = new InternetAddress(); + iaddress.setAddress(address); + recipients.add(iaddress); + } + } + + return recipients; } /** @@ -3823,17 +4003,9 @@ public static void sendBGEmail(String fromEmail, String fromName, Collection - * 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(SWBMail message) throws java.net.SocketException { + public static void sendBGEmail(SWBMail message) { SWBMailSender swbMailSender = new SWBMailSender(); swbMailSender.addEMail(message); swbMailSender.start(); @@ -3847,11 +4019,11 @@ public static void sendBGEmail(SWBMail message) throws java.net.SocketException * enviar mensajes. *

* - * @param smtpuser + * @param val * a string representing a user's name registered in the SMTP server. */ - public static void setSMTPUser(String smtpuser) { - SWBUtils.EMAIL.smtpuser = smtpuser; + public static void setSMTPUser(String val) { + smtpuser = val; } /** @@ -3862,12 +4034,12 @@ public static void setSMTPUser(String smtpuser) { * SMTP para enviar mensajes. *

* - * @param smtppassword + * @param val * a string representing a user's password registered in the SMTP * server. */ - public static void setSMTPPassword(String smtppassword) { - SWBUtils.EMAIL.smtppassword = smtppassword; + public static void setSMTPPassword(String val) { + smtppassword = val; } /** @@ -3888,7 +4060,7 @@ public static boolean isValidEmailAddress(String emailAddress) { } /** - * Provides several common operations to perform involving DOM documents and + * Provides several common operations to perform processing of DOM documents and * their contents. *

* 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étodo commit 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 ArrayList batchs; /** - * Creates a new instance of PoolStatement. + * Creates a new instance of {@link AutoPreparedStatement}. * - * @param aconn - * the aconn - * @param query - * the query - * @throws SQLException - * the sQL exception + * @param aconn {@link AutoConnection} object for statement creation. + * @param query SQL query String. + * @throws SQLException if a connection can't be established. */ public AutoPreparedStatement(AutoConnection aconn, String query) throws SQLException { batchs = new ArrayList(); @@ -102,10 +64,8 @@ public AutoPreparedStatement(AutoConnection aconn, String query) throws SQLExcep } /** - * Check statement. - * - * @throws SQLException - * the sQL exception + * Checks if statement can be created and added to batch list. + * @throws SQLException if Statement cannot be created by a database connection exception. */ private void checkStatement() throws SQLException { if (!closed && aconn.getNativeConnection() != conn) { @@ -127,13 +87,10 @@ private void checkStatement() throws SQLException { * * @see java.sql.Statement#addBatch(java.lang.String) */ - public void addBatch(String str) throws java.sql.SQLException { - if (debug) { - LOG.debug("addBatch:" + str); - } + public void addBatch(String sql) throws SQLException { checkStatement(); - st.addBatch(str); - batchs.add(str); + st.addBatch(sql); + batchs.add(sql); } /* @@ -141,7 +98,7 @@ public void addBatch(String str) throws java.sql.SQLException { * * @see java.sql.Statement#cancel() */ - public void cancel() throws java.sql.SQLException { + public void cancel() throws SQLException { checkStatement(); st.cancel(); } @@ -151,7 +108,7 @@ public void cancel() throws java.sql.SQLException { * * @see java.sql.Statement#clearBatch() */ - public void clearBatch() throws java.sql.SQLException { + public void clearBatch() throws SQLException { checkStatement(); st.clearBatch(); batchs.clear(); @@ -162,7 +119,7 @@ public void clearBatch() throws java.sql.SQLException { * * @see java.sql.Statement#clearWarnings() */ - public void clearWarnings() throws java.sql.SQLException { + public void clearWarnings() throws SQLException { checkStatement(); st.clearWarnings(); } @@ -172,7 +129,7 @@ public void clearWarnings() throws java.sql.SQLException { * * @see java.sql.Statement#close() */ - public void close() throws java.sql.SQLException { + public void close() throws SQLException { closed = true; st.close(); } @@ -182,12 +139,9 @@ public void close() throws java.sql.SQLException { * * @see java.sql.Statement#execute(java.lang.String) */ - public boolean execute(String str) throws java.sql.SQLException { - if (debug) { - LOG.debug("execute:" + str); - } + public boolean execute(String sql) throws SQLException { checkStatement(); - return st.execute(str); + return st.execute(sql); } /* @@ -195,16 +149,7 @@ public boolean execute(String str) throws java.sql.SQLException { * * @see java.sql.Statement#executeBatch() */ - public int[] executeBatch() throws java.sql.SQLException { - if (debug) { - LOG.debug("*************************************"); - LOG.debug("executeBatch():" + query); - Iterator it = batchs.iterator(); - while (it.hasNext()) { - String string = it.next(); - LOG.debug(": " + string); - } - } + public int[] executeBatch() throws SQLException { checkStatement(); return st.executeBatch(); } @@ -214,12 +159,9 @@ public int[] executeBatch() throws java.sql.SQLException { * * @see java.sql.Statement#executeQuery(java.lang.String) */ - public java.sql.ResultSet executeQuery(String str) throws java.sql.SQLException { - if (debug) { - LOG.debug("executeQuery:" + str); - } + public ResultSet executeQuery(String sql) throws SQLException { checkStatement(); - return st.executeQuery(str); + return st.executeQuery(sql); } /* @@ -227,12 +169,9 @@ public java.sql.ResultSet executeQuery(String str) throws java.sql.SQLException * * @see java.sql.Statement#executeUpdate(java.lang.String) */ - public int executeUpdate(String str) throws java.sql.SQLException { - if (debug) { - LOG.debug("executeUpdate:" + str); - } + public int executeUpdate(String sql) throws SQLException { checkStatement(); - return st.executeUpdate(str); + return st.executeUpdate(sql); } /* @@ -240,7 +179,7 @@ public int executeUpdate(String str) throws java.sql.SQLException { * * @see java.sql.Statement#getConnection() */ - public java.sql.Connection getConnection() throws java.sql.SQLException { + public Connection getConnection() throws SQLException { checkStatement(); return aconn; } @@ -250,7 +189,7 @@ public java.sql.Connection getConnection() throws java.sql.SQLException { * * @see java.sql.Statement#getFetchDirection() */ - public int getFetchDirection() throws java.sql.SQLException { + public int getFetchDirection() throws SQLException { checkStatement(); return st.getFetchDirection(); } @@ -260,7 +199,7 @@ public int getFetchDirection() throws java.sql.SQLException { * * @see java.sql.Statement#getFetchSize() */ - public int getFetchSize() throws java.sql.SQLException { + public int getFetchSize() throws SQLException { checkStatement(); return st.getFetchSize(); } @@ -270,7 +209,7 @@ public int getFetchSize() throws java.sql.SQLException { * * @see java.sql.Statement#getMaxFieldSize() */ - public int getMaxFieldSize() throws java.sql.SQLException { + public int getMaxFieldSize() throws SQLException { checkStatement(); return st.getMaxFieldSize(); } @@ -280,7 +219,7 @@ public int getMaxFieldSize() throws java.sql.SQLException { * * @see java.sql.Statement#getMaxRows() */ - public int getMaxRows() throws java.sql.SQLException { + public int getMaxRows() throws SQLException { checkStatement(); return st.getMaxRows(); } @@ -290,7 +229,7 @@ public int getMaxRows() throws java.sql.SQLException { * * @see java.sql.Statement#getMoreResults() */ - public boolean getMoreResults() throws java.sql.SQLException { + public boolean getMoreResults() throws SQLException { checkStatement(); return st.getMoreResults(); } @@ -300,7 +239,7 @@ public boolean getMoreResults() throws java.sql.SQLException { * * @see java.sql.Statement#getQueryTimeout() */ - public int getQueryTimeout() throws java.sql.SQLException { + public int getQueryTimeout() throws SQLException { checkStatement(); return st.getQueryTimeout(); } @@ -310,10 +249,7 @@ public int getQueryTimeout() throws java.sql.SQLException { * * @see java.sql.Statement#getResultSet() */ - public java.sql.ResultSet getResultSet() throws java.sql.SQLException { - if (debug) { - LOG.debug("getResultSet"); - } + public ResultSet getResultSet() throws SQLException { checkStatement(); return st.getResultSet(); } @@ -323,7 +259,7 @@ public java.sql.ResultSet getResultSet() throws java.sql.SQLException { * * @see java.sql.Statement#getResultSetConcurrency() */ - public int getResultSetConcurrency() throws java.sql.SQLException { + public int getResultSetConcurrency() throws SQLException { checkStatement(); return st.getResultSetConcurrency(); } @@ -333,7 +269,7 @@ public int getResultSetConcurrency() throws java.sql.SQLException { * * @see java.sql.Statement#getResultSetType() */ - public int getResultSetType() throws java.sql.SQLException { + public int getResultSetType() throws SQLException { checkStatement(); return st.getResultSetType(); } @@ -343,7 +279,7 @@ public int getResultSetType() throws java.sql.SQLException { * * @see java.sql.Statement#getUpdateCount() */ - public int getUpdateCount() throws java.sql.SQLException { + public int getUpdateCount() throws SQLException { checkStatement(); return st.getUpdateCount(); } @@ -353,7 +289,7 @@ public int getUpdateCount() throws java.sql.SQLException { * * @see java.sql.Statement#getWarnings() */ - public java.sql.SQLWarning getWarnings() throws java.sql.SQLException { + public java.sql.SQLWarning getWarnings() throws SQLException { checkStatement(); return st.getWarnings(); } @@ -363,9 +299,9 @@ public java.sql.SQLWarning getWarnings() throws java.sql.SQLException { * * @see java.sql.Statement#setCursorName(java.lang.String) */ - public void setCursorName(String str) throws java.sql.SQLException { + public void setCursorName(String name) throws SQLException { checkStatement(); - st.setCursorName(str); + st.setCursorName(name); } /* @@ -373,9 +309,9 @@ public void setCursorName(String str) throws java.sql.SQLException { * * @see java.sql.Statement#setEscapeProcessing(boolean) */ - public void setEscapeProcessing(boolean param) throws java.sql.SQLException { + public void setEscapeProcessing(boolean enable) throws SQLException { checkStatement(); - st.setEscapeProcessing(param); + st.setEscapeProcessing(enable); } /* @@ -383,9 +319,9 @@ public void setEscapeProcessing(boolean param) throws java.sql.SQLException { * * @see java.sql.Statement#setFetchDirection(int) */ - public void setFetchDirection(int param) throws java.sql.SQLException { + public void setFetchDirection(int direction) throws SQLException { checkStatement(); - st.setFetchDirection(param); + st.setFetchDirection(direction); } /* @@ -393,9 +329,9 @@ public void setFetchDirection(int param) throws java.sql.SQLException { * * @see java.sql.Statement#setFetchSize(int) */ - public void setFetchSize(int param) throws java.sql.SQLException { + public void setFetchSize(int rows) throws SQLException { checkStatement(); - st.setFetchSize(param); + st.setFetchSize(rows); } /* @@ -403,9 +339,9 @@ public void setFetchSize(int param) throws java.sql.SQLException { * * @see java.sql.Statement#setMaxFieldSize(int) */ - public void setMaxFieldSize(int param) throws java.sql.SQLException { + public void setMaxFieldSize(int max) throws SQLException { checkStatement(); - st.setMaxFieldSize(param); + st.setMaxFieldSize(max); } /* @@ -413,9 +349,9 @@ public void setMaxFieldSize(int param) throws java.sql.SQLException { * * @see java.sql.Statement#setMaxRows(int) */ - public void setMaxRows(int param) throws java.sql.SQLException { + public void setMaxRows(int max) throws SQLException { checkStatement(); - st.setMaxRows(param); + st.setMaxRows(max); } /* @@ -423,15 +359,14 @@ public void setMaxRows(int param) throws java.sql.SQLException { * * @see java.sql.Statement#setQueryTimeout(int) */ - public void setQueryTimeout(int param) throws java.sql.SQLException { + public void setQueryTimeout(int seconds) throws SQLException { checkStatement(); - st.setQueryTimeout(param); + st.setQueryTimeout(seconds); } /** - * Checks if is closed. - * - * @return true, if is closed + * Checks if statement is closed. + * @return true if is statement is closed. */ public boolean isClosed() { return closed; @@ -443,12 +378,9 @@ public boolean isClosed() { * * @see java.sql.Statement#execute(java.lang.String, java.lang.String[]) */ - public boolean execute(String str, String[] str1) throws java.sql.SQLException { - if (debug) { - LOG.debug("execute:" + str + " " + str1); - } + public boolean execute(String sql, String[] columnNames) throws SQLException { checkStatement(); - return st.execute(str, str1); + return st.execute(sql, columnNames); } /* @@ -456,12 +388,9 @@ public boolean execute(String str, String[] str1) throws java.sql.SQLException { * * @see java.sql.Statement#execute(java.lang.String, int[]) */ - public boolean execute(String str, int[] values) throws java.sql.SQLException { - if (debug) { - LOG.debug("execute:" + str + " " + values); - } + public boolean execute(String sql, int[] columnIndexes) throws SQLException { checkStatement(); - return st.execute(str, values); + return st.execute(sql, columnIndexes); } /* @@ -469,12 +398,9 @@ public boolean execute(String str, int[] values) throws java.sql.SQLException { * * @see java.sql.Statement#execute(java.lang.String, int) */ - public boolean execute(String str, int param) throws java.sql.SQLException { - if (debug) { - LOG.debug("execute:" + str + " " + param); - } + public boolean execute(String sql, int autoGeneratedKeys) throws SQLException { checkStatement(); - return st.execute(str, param); + return st.execute(sql, autoGeneratedKeys); } /* @@ -482,7 +408,7 @@ public boolean execute(String str, int param) throws java.sql.SQLException { * * @see java.sql.Statement#getResultSetHoldability() */ - public int getResultSetHoldability() throws java.sql.SQLException { + public int getResultSetHoldability() throws SQLException { checkStatement(); return st.getResultSetHoldability(); } @@ -492,9 +418,9 @@ public int getResultSetHoldability() throws java.sql.SQLException { * * @see java.sql.Statement#getMoreResults(int) */ - public boolean getMoreResults(int param) throws java.sql.SQLException { + public boolean getMoreResults(int current) throws SQLException { checkStatement(); - return st.getMoreResults(param); + return st.getMoreResults(current); } /* @@ -502,12 +428,9 @@ public boolean getMoreResults(int param) throws java.sql.SQLException { * * @see java.sql.Statement#executeUpdate(java.lang.String, java.lang.String[]) */ - public int executeUpdate(String str, String[] str1) throws java.sql.SQLException { - if (debug) { - LOG.debug("executeUpdate():" + str + " " + str1); - } + public int executeUpdate(String sql, String[] columnNames) throws SQLException { checkStatement(); - return st.executeUpdate(str, str1); + return st.executeUpdate(sql, columnNames); } /* @@ -515,12 +438,9 @@ public int executeUpdate(String str, String[] str1) throws java.sql.SQLException * * @see java.sql.Statement#executeUpdate(java.lang.String, int) */ - public int executeUpdate(String str, int param) throws java.sql.SQLException { - if (debug) { - LOG.debug("executeUpdate():" + str + " " + param); - } + public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException { checkStatement(); - return st.executeUpdate(str, param); + return st.executeUpdate(sql, autoGeneratedKeys); } /* @@ -528,12 +448,9 @@ public int executeUpdate(String str, int param) throws java.sql.SQLException { * * @see java.sql.Statement#executeUpdate(java.lang.String, int[]) */ - public int executeUpdate(String str, int[] values) throws java.sql.SQLException { - if (debug) { - LOG.debug("executeUpdate():" + str + " " + values); - } + public int executeUpdate(String sql, int[] columnIndexes) throws SQLException { checkStatement(); - return st.executeUpdate(str, values); + return st.executeUpdate(sql, columnIndexes); } /* @@ -541,7 +458,7 @@ public int executeUpdate(String str, int[] values) throws java.sql.SQLException * * @see java.sql.Statement#getGeneratedKeys() */ - public java.sql.ResultSet getGeneratedKeys() throws java.sql.SQLException { + public ResultSet getGeneratedKeys() throws SQLException { checkStatement(); return st.getGeneratedKeys(); } @@ -552,9 +469,6 @@ public java.sql.ResultSet getGeneratedKeys() throws java.sql.SQLException { * @see java.sql.PreparedStatement#executeQuery() */ public ResultSet executeQuery() throws SQLException { - if (debug) { - LOG.debug("executeQuery():" + query); - } checkStatement(); return st.executeQuery(); } @@ -565,15 +479,6 @@ public ResultSet executeQuery() throws SQLException { * @see java.sql.PreparedStatement#executeUpdate() */ public int executeUpdate() throws SQLException { - if (debug) { - System.out.println("executeUpdate():" + query); - } - if (debug) { - LOG.debug("----------------------------------------------"); - LOG.debug("--> execute():" + query); - LOG.debug("--> args:" + args); - args = ""; - } checkStatement(); return st.executeUpdate(); } @@ -584,9 +489,6 @@ public int executeUpdate() throws SQLException { * @see java.sql.PreparedStatement#setNull(int, int) */ public void setNull(int parameterIndex, int sqlType) throws SQLException { - if (debug) { - args += " " + parameterIndex + " " + sqlType; - } checkStatement(); st.setNull(parameterIndex, sqlType); } @@ -597,9 +499,6 @@ public void setNull(int parameterIndex, int sqlType) throws SQLException { * @see java.sql.PreparedStatement#setBoolean(int, boolean) */ public void setBoolean(int parameterIndex, boolean x) throws SQLException { - if (debug) { - args += " " + parameterIndex + " " + x; - } checkStatement(); st.setBoolean(parameterIndex, x); } @@ -610,9 +509,6 @@ public void setBoolean(int parameterIndex, boolean x) throws SQLException { * @see java.sql.PreparedStatement#setByte(int, byte) */ public void setByte(int parameterIndex, byte x) throws SQLException { - if (debug) { - args += " " + parameterIndex + " " + x; - } checkStatement(); st.setByte(parameterIndex, x); } @@ -623,9 +519,6 @@ public void setByte(int parameterIndex, byte x) throws SQLException { * @see java.sql.PreparedStatement#setShort(int, short) */ public void setShort(int parameterIndex, short x) throws SQLException { - if (debug) { - args += " " + parameterIndex + " " + x; - } checkStatement(); st.setShort(parameterIndex, x); } @@ -636,9 +529,6 @@ public void setShort(int parameterIndex, short x) throws SQLException { * @see java.sql.PreparedStatement#setInt(int, int) */ public void setInt(int parameterIndex, int x) throws SQLException { - if (debug) { - args += " " + parameterIndex + " " + x; - } checkStatement(); st.setInt(parameterIndex, x); } @@ -649,9 +539,6 @@ public void setInt(int parameterIndex, int x) throws SQLException { * @see java.sql.PreparedStatement#setLong(int, long) */ public void setLong(int parameterIndex, long x) throws SQLException { - if (debug) { - args += " " + parameterIndex + " " + x; - } checkStatement(); st.setLong(parameterIndex, x); } @@ -662,9 +549,6 @@ public void setLong(int parameterIndex, long x) throws SQLException { * @see java.sql.PreparedStatement#setFloat(int, float) */ public void setFloat(int parameterIndex, float x) throws SQLException { - if (debug) { - args += " " + parameterIndex + " " + x; - } checkStatement(); st.setFloat(parameterIndex, x); } @@ -675,9 +559,6 @@ public void setFloat(int parameterIndex, float x) throws SQLException { * @see java.sql.PreparedStatement#setDouble(int, double) */ public void setDouble(int parameterIndex, double x) throws SQLException { - if (debug) { - args += " " + parameterIndex + " " + x; - } checkStatement(); st.setDouble(parameterIndex, x); } @@ -688,9 +569,6 @@ public void setDouble(int parameterIndex, double x) throws SQLException { * @see java.sql.PreparedStatement#setBigDecimal(int, java.math.BigDecimal) */ public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException { - if (debug) { - args += " " + parameterIndex + " " + x; - } checkStatement(); st.setBigDecimal(parameterIndex, x); } @@ -701,9 +579,6 @@ public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException * @see java.sql.PreparedStatement#setString(int, java.lang.String) */ public void setString(int parameterIndex, String x) throws SQLException { - if (debug) { - args += " " + parameterIndex + " " + x; - } checkStatement(); st.setString(parameterIndex, x); } @@ -714,9 +589,6 @@ public void setString(int parameterIndex, String x) throws SQLException { * @see java.sql.PreparedStatement#setBytes(int, byte[]) */ public void setBytes(int parameterIndex, byte[] x) throws SQLException { - if (debug) { - args += " " + parameterIndex + " " + x; - } checkStatement(); st.setBytes(parameterIndex, x); } @@ -727,9 +599,6 @@ public void setBytes(int parameterIndex, byte[] x) throws SQLException { * @see java.sql.PreparedStatement#setDate(int, java.sql.Date) */ public void setDate(int parameterIndex, Date x) throws SQLException { - if (debug) { - args += " " + parameterIndex + " " + x; - } checkStatement(); st.setDate(parameterIndex, x); } @@ -740,9 +609,6 @@ public void setDate(int parameterIndex, Date x) throws SQLException { * @see java.sql.PreparedStatement#setTime(int, java.sql.Time) */ public void setTime(int parameterIndex, Time x) throws SQLException { - if (debug) { - args += " " + parameterIndex + " " + x; - } checkStatement(); st.setTime(parameterIndex, x); } @@ -753,9 +619,6 @@ public void setTime(int parameterIndex, Time x) throws SQLException { * @see java.sql.PreparedStatement#setTimestamp(int, java.sql.Timestamp) */ public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException { - if (debug) { - args += " " + parameterIndex + " " + x; - } checkStatement(); st.setTimestamp(parameterIndex, x); } @@ -779,7 +642,6 @@ public void setAsciiStream(int parameterIndex, InputStream x, int length) throws public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException { checkStatement(); st.setCharacterStream(parameterIndex, new InputStreamReader(x), length); - //st.setUnicodeStream(parameterIndex, x, length); } /* @@ -839,39 +701,23 @@ public void setObject(int parameterIndex, Object x) throws SQLException { * @see java.sql.PreparedStatement#execute() */ public boolean execute() throws SQLException { - checkStatement(); boolean ret; - long time = 0; - if (debug) { - time = System.currentTimeMillis(); - LOG.debug("----------------------------------------------"); - LOG.debug("--> execute():" + query); - LOG.debug("--> args:" + args); - args = ""; - } + checkStatement(); try { ret = st.execute(); } catch (SQLException se) { - // System.out.println("SQLEx:"+se.getMessage()); if (aconn.checkConnection()) { - //System.out.println("P1"); checkStatement(); ret = st.execute(); - } else if (se.getMessage().indexOf("SocketException") > -1) { - //System.out.println("P2"); + } else if (se.getMessage().contains("SocketException")) { aconn.changeConnection(); checkStatement(); ret = st.execute(); } else { - //System.out.println("P3"); throw se; } } - - if (debug) { - LOG.debug("------------------" + (System.currentTimeMillis() - time) + "-----------------------"); - } return ret; } diff --git a/src/main/java/org/semanticwb/base/db/AutoStatement.java b/src/main/java/org/semanticwb/base/db/AutoStatement.java index 5f42d52..25dc3b9 100644 --- a/src/main/java/org/semanticwb/base/db/AutoStatement.java +++ b/src/main/java/org/semanticwb/base/db/AutoStatement.java @@ -22,13 +22,13 @@ */ package org.semanticwb.base.db; +import org.semanticwb.Logger; +import org.semanticwb.SWBUtils; + import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; -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. diff --git a/src/main/java/org/semanticwb/base/db/DBConnectionManager.java b/src/main/java/org/semanticwb/base/db/DBConnectionManager.java index 6e6c9f2..330938e 100644 --- a/src/main/java/org/semanticwb/base/db/DBConnectionManager.java +++ b/src/main/java/org/semanticwb/base/db/DBConnectionManager.java @@ -22,78 +22,52 @@ */ package org.semanticwb.base.db; +import org.semanticwb.Logger; +import org.semanticwb.SWBUtils; +import org.semanticwb.base.util.SWBProperties; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.sql.DataSource; import java.io.FileNotFoundException; import java.io.InputStream; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.Properties; -import java.util.StringTokenizer; - -import javax.naming.Context; -import javax.naming.InitialContext; -import javax.sql.DataSource; - -import org.semanticwb.Logger; -import org.semanticwb.SWBUtils; -import org.semanticwb.base.util.SWBProperties; +import java.util.*; /** - * Esta clase proporciona acceso a uno o más connection pools - * definidos en el archivo de propiedades db.properties. + * Class to manage several connection pools defined in db.properties configuration file. * * @author Javier Solis Gonzalez (jsolis@infotec.com.mx) */ public class DBConnectionManager { - - /** The log. */ private static Logger log = SWBUtils.getLogger(DBConnectionManager.class); - - /** The drivers. */ private ArrayList drivers = new ArrayList<>(); - - /** The pools. */ private Hashtable pools = new Hashtable<>(); - - /** The is jndi. */ private boolean isJNDI; - - /** The JNDI patern. */ - private String JNDIPatern; - - /** The init ctx. */ + private String jndiPattern; private Context initCtx; - - /** The time lock. */ private PoolConnectionTimeLock timeLock = new PoolConnectionTimeLock(); /** - * Instantiates a new dB connection manager. + * Creates a new {@link DBConnectionManager}. */ - public DBConnectionManager() - { + public DBConnectionManager() { log.event("Initializing DBConnectionManager..."); init(); } /** - * Gets the num connections. - * - * @return the num connections - * @return + * Gets the total number of free connections available in all managed pools. + * @return free connection count on all pools. */ - public int getNumConnections() - { + public int getNumConnections() { int cl = 0; - Enumeration allPools = pools.elements(); - if (!isJNDI) - { - while (allPools.hasMoreElements()) - { + if (!isJNDI) { + Enumeration allPools = pools.elements(); + while (allPools.hasMoreElements()) { DBConnectionPool pool = (DBConnectionPool) allPools.nextElement(); cl += pool.freeConnections.size(); } @@ -102,20 +76,15 @@ public int getNumConnections() } /** - * Gets the connections. - * - * @param name the name - * @return the connections - * @return + * Gets total count of connections of a named Pool. + * @param name Pool name. + * @return number of connections. */ - public int getConnections(String name) - { + public int getConnections(String name) { int cl = 0; - if (!isJNDI) - { + if (!isJNDI) { DBConnectionPool pool = (DBConnectionPool) pools.get(name); - if (pool != null) - { + if (pool != null) { cl = pool.checkedOut; } } @@ -123,20 +92,15 @@ public int getConnections(String name) } /** - * Gets the free connections. - * - * @param name the name - * @return the free connections - * @return + * Gets count of free connections on a named Pool. + * @param name pool name. + * @return free connections count. */ - public int getFreeConnections(String name) - { + public int getFreeConnections(String name) { int cl = 0; - if (!isJNDI) - { + if (!isJNDI) { DBConnectionPool pool = (DBConnectionPool) pools.get(name); - if (pool != null) - { + if (pool != null) { cl = pool.freeConnections.size(); } } @@ -144,183 +108,142 @@ public int getFreeConnections(String name) } /** - * Cierra una conexi�n del pool especificado. - * - * @param name the name - * @param con the con + * Closes a connection on a named Pool. + * @param name pool name. + * @param con {@link Connection} object to close. */ - public void freeConnection(String name, Connection con) - { - if (!isJNDI) - { + public void freeConnection(String name, Connection con) { + if (!isJNDI) { DBConnectionPool pool = (DBConnectionPool) pools.get(name); - if (pool != null) - { + if (pool != null) { pool.freeConnection(con); } - } else - { - try - { - if (con != null) - { + } else { + try { + if (con != null) { con.close(); } - } catch (SQLException ex) - { - log.error("Error to create JNDI Pool Connection...", ex); + } catch (SQLException ex) { + log.error("Error closing JNDI Pool Connection...", ex); } } } /** - * Regresa una conexión que no pertenece al pool. - * - * @param name the name - * @return Connection La conexi�n o nulo. + * Gets a {@link Connection} object related with no Pool from a named Pool. + * @param name pool name. + * @return new connection or null. */ - public Connection getNoPoolConnection(String name) - { - Connection ret = null; + public Connection getNoPoolConnection(String name) { DBConnectionPool pool = (DBConnectionPool) pools.get(name); - if (pool != null) - { - ret = pool.newNoPoolConnection(); + if (pool != null) { + return pool.newNoPoolConnection(); } - return ret; + return null; } /** - * Regresa una conexión que no se registra en el pool, pero que se auto restablece si se piede la conexion. - * - * @param name the name - * @return Connection La conexión o nulo. + * Gets an {@link AutoConnection} object related with no Pool from a named Pool. + * @param name pool name. + * @return new connection or null. */ - public Connection getAutoConnection(String name) - { - Connection ret = null; + public Connection getAutoConnection(String name) { DBConnectionPool pool = (DBConnectionPool) pools.get(name); - if (pool != null) - { - ret = pool.newAutoConnection(); + if (pool != null) { + return pool.newAutoConnection(); } - return ret; + return null; } /** - * Regresa una conexión abierta. Si ninguna otra conexión está disponible y el número máximo - * de conexiones no se ha alcanzado, una nueva conexión es creada. - * - * @param name the name - * @return Connection La conexión o nulo. + * Gets an open connection or creates a new one without description. + * @param name Pool name. + * @return new connection or null. */ - public Connection getConnection(String name) - { + public Connection getConnection(String name) { return getConnection(name, null); } /** - * Regresa una conexión abierta. Si ninguna otra conexión está disponible y el número máximo - * de conexiones no se ha alcanzado, una nueva conexión es creada. + * Gets an open connection or creates a new one with given description. * - * @param name the name - * @param description the description - * @return Connection La conexión o nulo. + * @param name pool name. + * @param description connection description. + * @return new connection or null.. */ - public Connection getConnection(String name, String description) - { + public Connection getConnection(String name, String description) { Connection ret = null; - if (!isJNDI) - { + if (!isJNDI) { DBConnectionPool pool = (DBConnectionPool) pools.get(name); - if (pool != null) - { + if (pool != null) { PoolConnection con = (PoolConnection) pool.getConnection(); ret = con; } - } 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 Connection Pool " + name); - } catch (Exception ex) - { + } catch (Exception ex) { log.error("Error to get DataSource of Context...", ex); } - } - try - { - ret = ds.getConnection(); - } catch (SQLException ex) - { - log.error("Error to get JNDI Pool Connection...", ex); + } else { + try { + ret = ds.getConnection(); + } catch (SQLException ex) { + log.error("Error to get JNDI Pool Connection...", ex); + } } } return ret; } /** - * Regresa una conexión abierta. Si ninguna otra conexión está disponible y el número máximo - * de conexiones no se ha alcanzado, una nueva conexión es creada. Si el número máximo ha sido - * alcanzado espera hasta que una conexión este disponible o el tiempo especificado haya - * transcurrido. + * Gets an open connection or creates a new one. It will wait a maximum of time 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 vec = new ArrayList<>(); - - /** The pool. */ + private java.sql.Connection con; + private ArrayList statements = new ArrayList<>(); private DBConnectionPool pool; - - /** The isclosed. */ - private boolean isclosed = false; - - /** The description. */ + private boolean isClosed = false; private String description = ""; - - /** The id. */ private long id = 0; - - /** The idleTime. */ - private long idleTime = 0; - - /** The destroy. */ + private long idleTime; private boolean destroy = false; - - /** The isdestroyed. */ - private volatile boolean isdestroyed = false; - - /** The stack. */ + private volatile boolean isDestroyed = false; private StackTraceElement[] stack = null; private String threadName = null; + /** + * Constructor. Creates a new instance of {@link PoolConnection}. + * @param con connection object to wrap in. + */ public PoolConnection(Connection con) { this(con, null); } /** - * Instantiates a new pool connection. - * - * @param con - * the con - * @param pool - * the pool + * Constructor. Creates a new instance of {@link PoolConnection} using a specified {@link DBConnectionPool}. + * @param con connection object to wrap in. + * @param pool connection pool to use. */ public PoolConnection(Connection con, DBConnectionPool pool) { idleTime = System.currentTimeMillis(); @@ -118,18 +76,17 @@ public PoolConnection(Connection con, DBConnectionPool pool) { } /** - * Inits the. + * Inits the instance. */ public void init() { - isclosed = false; + isClosed = false; description = ""; id = 0; } /** - * Getter for property id. - * - * @return Value of property id. + * Gets connection id. + * @return connection id. * */ public long getId() { @@ -137,11 +94,8 @@ public long getId() { } /** - * Setter for property id. - * - * @param id - * New value of property id. - * + * Sets connection id. + * @param id connection id. */ public void setId(long id) { threadName = Thread.currentThread().getName(); @@ -151,7 +105,6 @@ public void setId(long id) { /** * Gets the stack trace elements. - * * @return the stack trace elements */ public StackTraceElement[] getStackTraceElements() { @@ -159,10 +112,8 @@ public StackTraceElement[] getStackTraceElements() { } /** - * Prints the track trace. - * - * @param out - * the out + * Prints the track trace to a {@link PrintStream}. + * @param out print stream. */ public void printTrackTrace(PrintStream out) { for (int x = 0; x < stack.length; x++) { @@ -171,32 +122,27 @@ public void printTrackTrace(PrintStream out) { } /** - * Gets the native connection. - * - * @return the native connection - * @return + * Gets wrapped {@link Connection} object. + * @return wrapped connection. */ - public java.sql.Connection getNativeConnection() { + public Connection getNativeConnection() { return con; } /** - * Getter for property pool. - * - * @return Value of property pool. - * + * Gets the {@link DBConnectionPool} object + * @return connection pool. */ public DBConnectionPool getPool() { return pool; } /** - * Getter for property description. - * - * @return Value of property description. - * + * Gets the description of this Pool. If no description is set explicitly, a concatenation + * of stack trace and thread name is returned. + * @return Pool description. */ - public java.lang.String getDescription() { + public String getDescription() { if (description == null || description.length() == 0) { StringBuilder ret = new StringBuilder(); ret.append(threadName); @@ -212,66 +158,46 @@ public java.lang.String getDescription() { } /** - * Setter for property description. - * - * @param description - * New value of property description. - * + * Sets the description for this Pool. + * @param description pool description. */ - public void setDescription(java.lang.String description) { + public void setDescription(String description) { this.description = description; } /** * Close statements. - * - * @return true, if successful - * @return + * @return true if statements were closed with no errors. */ public boolean closeStatements() { - boolean noerrors = true; - while (!vec.isEmpty()) { - PoolStatement st = (PoolStatement) vec.get(0); - if (st != null) { + boolean success = true; + while (!statements.isEmpty()) { + PoolStatement st = (PoolStatement) statements.get(0); + if (st != null && !st.isClosed()) { try { - if (!st.isClosed()) { - ResultSet rs = st.getResultSet(); - if (rs != null) { - rs.close(); - } - st.close(); - log.warn("Statement was not closed..., " + description); - noerrors = false; + ResultSet rs = st.getResultSet(); + if (rs != null) { + rs.close(); } + st.close(); + log.warn("Statement was not closed..., " + description); + success = false; } catch (SQLException noe) {/* Es correcto el error, ya que el susuario cerro la conexion */ } } - vec.remove(0); + statements.remove(0); } - return noerrors; + return success; } /** - * _close. - * - */ - public void _close() { - destroyConnection(); - } - - /** - * 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 an database error occurs. */ public void close() throws SQLException { - if (!isclosed) { + if (!isClosed) { if (destroy) { log.trace("Connection.close(destroy):" + getId()); try { @@ -281,48 +207,45 @@ public void close() throws SQLException { log.error("Connection " + description + ", close.setAutocomit(false):", e); } } - isclosed = true; - if (pool != null) + + isClosed = true; + if (pool != null) { pool.getConnectionManager().getTimeLock().removeConnection(this); + } + idleTime = System.currentTimeMillis(); try { closeStatements(); } catch (Exception e) { log.error("Connection " + description + ", closeStatement:", e); } + try { - if (pool != null) + if (pool != null) { pool.freeConnection(this); + log.trace("close:(" + getId() + "," + pool.getName() + "):" + pool.checkedOut); + } } catch (Exception e) { log.error("Connection " + description + ", freeConnection:", e); } - if (pool != null) - 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étodo commit 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 (!param) { + * 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 { + if (!enable) { destroy = true; } - con.setAutoCommit(param); + con.setAutoCommit(enable); } /* @@ -403,8 +326,8 @@ public void clearWarnings() throws SQLException { * * @see java.sql.Connection#nativeSQL(java.lang.String) */ - public String nativeSQL(String str) throws SQLException { - return con.nativeSQL(str); + public String nativeSQL(String sql) throws SQLException { + return con.nativeSQL(sql); } /* @@ -412,8 +335,8 @@ public String nativeSQL(String str) throws SQLException { * * @see java.sql.Connection#prepareStatement(java.lang.String, int, int) */ - public PreparedStatement prepareStatement(String str, int param, int param2) throws SQLException { - return con.prepareStatement(str, param, param2); + public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { + return con.prepareStatement(sql, resultSetType, resultSetConcurrency); } /* @@ -421,8 +344,8 @@ public PreparedStatement prepareStatement(String str, int param, int param2) thr * * @see java.sql.Connection#setTransactionIsolation(int) */ - public void setTransactionIsolation(int param) throws SQLException { - con.setTransactionIsolation(param); + public void setTransactionIsolation(int level) throws SQLException { + con.setTransactionIsolation(level); } /* @@ -430,9 +353,9 @@ public void setTransactionIsolation(int param) throws SQLException { * * @see java.sql.Connection#setReadOnly(boolean) */ - public void setReadOnly(boolean param) throws SQLException { + public void setReadOnly(boolean readOnly) throws SQLException { destroy = true; - con.setReadOnly(param); + con.setReadOnly(readOnly); } /* @@ -440,9 +363,9 @@ public void setReadOnly(boolean param) throws SQLException { * * @see java.sql.Connection#setCatalog(java.lang.String) */ - public void setCatalog(String str) throws SQLException { + public void setCatalog(String catalog) throws SQLException { destroy = true; - con.setCatalog(str); + con.setCatalog(catalog); } /* @@ -451,7 +374,7 @@ public void setCatalog(String str) throws SQLException { * @see java.sql.Connection#isClosed() */ public boolean isClosed() throws SQLException { - return isclosed || con.isClosed(); + return isClosed || con.isClosed(); } /* @@ -461,7 +384,7 @@ public boolean isClosed() throws SQLException { */ public Statement createStatement() throws SQLException { Statement st = new PoolStatement(con.createStatement(), this); - vec.add(st); + statements.add(st); return st; } @@ -470,9 +393,9 @@ public Statement createStatement() throws SQLException { * * @see java.sql.Connection#createStatement(int, int) */ - public Statement createStatement(int param, int param1) throws SQLException { - Statement st = new PoolStatement(con.createStatement(param, param1), this); - vec.add(st); + public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { + Statement st = new PoolStatement(con.createStatement(resultSetType, resultSetConcurrency), this); + statements.add(st); return st; } @@ -481,8 +404,8 @@ public Statement createStatement(int param, int param1) throws SQLException { * * @see java.sql.Connection#prepareStatement(java.lang.String) */ - public PreparedStatement prepareStatement(String str) throws SQLException { - return new PoolPreparedStatement(con.prepareStatement(str), str, this); + public PreparedStatement prepareStatement(String sql) throws SQLException { + return new PoolPreparedStatement(con.prepareStatement(sql), sql, this); } /* @@ -499,8 +422,8 @@ public boolean getAutoCommit() throws SQLException { * * @see java.sql.Connection#prepareCall(java.lang.String) */ - public CallableStatement prepareCall(String str) throws SQLException { - return con.prepareCall(str); + public CallableStatement prepareCall(String sql) throws SQLException { + return con.prepareCall(sql); } /* @@ -517,8 +440,8 @@ public void commit() throws SQLException { * * @see java.sql.Connection#prepareCall(java.lang.String, int, int) */ - public CallableStatement prepareCall(String str, int param, int param2) throws SQLException { - return con.prepareCall(str, param, param2); + public CallableStatement prepareCall(String sql, int resultType, int resultConcurrency) throws SQLException { + return con.prepareCall(sql, resultType, resultConcurrency); } /* @@ -531,24 +454,28 @@ public void rollback() throws SQLException { } /** - * Destroy connection. + * Destroys connection. */ protected void destroyConnection() { - if (isdestroyed == false) { - isdestroyed = true; - isclosed = true; + if (!isDestroyed) { + isDestroyed = true; + isClosed = true; if (pool != null) { pool.checkedOut--; pool.getConnectionManager().getTimeLock().removeConnection(this); } + try { - if (!con.isClosed()) + if (!con.isClosed()) { con.close(); + } } catch (Exception e) { log.error("Connection " + description + " finalize", e); } - if (pool != null) + + if (pool != null) { log.debug("destroyConnection:(" + getId() + "," + pool.getName() + "):" + pool.checkedOut); + } } } @@ -562,7 +489,7 @@ protected void finalize() throws Throwable { // We are no longer referenced by anyone (including the // connection pool). Time to close down. try { - if (isdestroyed == false) { + if (!isDestroyed) { log.warn("finalize(" + getId() + ")..., connection was not closed, " + description); destroyConnection(); } @@ -578,10 +505,9 @@ protected void finalize() throws Throwable { * * @see java.sql.Connection#setSavepoint() */ - public java.sql.Savepoint setSavepoint() throws java.sql.SQLException { + public Savepoint setSavepoint() throws SQLException { destroy = true; return con.setSavepoint(); - // return null; } /* @@ -589,9 +515,9 @@ public java.sql.Savepoint setSavepoint() throws java.sql.SQLException { * * @see java.sql.Connection#setHoldability(int) */ - public void setHoldability(int param) throws java.sql.SQLException { + public void setHoldability(int holdability) throws SQLException { destroy = true; - con.setHoldability(param); + con.setHoldability(holdability); } /* @@ -599,8 +525,8 @@ public void setHoldability(int param) throws java.sql.SQLException { * * @see java.sql.Connection#prepareStatement(java.lang.String, int) */ - public java.sql.PreparedStatement prepareStatement(java.lang.String str, int param) throws java.sql.SQLException { - return con.prepareStatement(str, param); + public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { + return con.prepareStatement(sql, autoGeneratedKeys); } /* @@ -608,9 +534,8 @@ public java.sql.PreparedStatement prepareStatement(java.lang.String str, int par * * @see java.sql.Connection#prepareStatement(java.lang.String, int, int, int) */ - public java.sql.PreparedStatement prepareStatement(java.lang.String str, int param, int param2, int param3) - throws java.sql.SQLException { - return con.prepareStatement(str, param, param2, param3); + public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { + return con.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); } /* @@ -618,9 +543,8 @@ public java.sql.PreparedStatement prepareStatement(java.lang.String str, int par * * @see java.sql.Connection#prepareStatement(java.lang.String, int[]) */ - public java.sql.PreparedStatement prepareStatement(java.lang.String str, int[] values) - throws java.sql.SQLException { - return con.prepareStatement(str, values); + public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { + return con.prepareStatement(sql, columnIndexes); } /* @@ -628,7 +552,7 @@ public java.sql.PreparedStatement prepareStatement(java.lang.String str, int[] v * * @see java.sql.Connection#getHoldability() */ - public int getHoldability() throws java.sql.SQLException { + public int getHoldability() throws SQLException { return con.getHoldability(); } @@ -637,7 +561,7 @@ public int getHoldability() throws java.sql.SQLException { * * @see java.sql.Connection#setSavepoint(java.lang.String) */ - public java.sql.Savepoint setSavepoint(java.lang.String str) throws java.sql.SQLException { + public Savepoint setSavepoint(String str) throws SQLException { destroy = true; return con.setSavepoint(str); } @@ -647,8 +571,8 @@ public java.sql.Savepoint setSavepoint(java.lang.String str) throws java.sql.SQL * * @see java.sql.Connection#createStatement(int, int, int) */ - public java.sql.Statement createStatement(int param, int param1, int param2) throws java.sql.SQLException { - return con.createStatement(param, param1, param2); + public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { + return con.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); } /* @@ -656,9 +580,8 @@ public java.sql.Statement createStatement(int param, int param1, int param2) thr * * @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 { - return con.prepareCall(str, param, param2, param3); + public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { + return con.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); } /* @@ -666,7 +589,7 @@ public java.sql.CallableStatement prepareCall(java.lang.String str, int param, i * * @see java.sql.Connection#releaseSavepoint(java.sql.Savepoint) */ - public void releaseSavepoint(java.sql.Savepoint savepoint) throws java.sql.SQLException { + public void releaseSavepoint(Savepoint savepoint) throws SQLException { con.releaseSavepoint(savepoint); } @@ -676,9 +599,8 @@ public void releaseSavepoint(java.sql.Savepoint savepoint) throws java.sql.SQLEx * @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 { - return con.prepareStatement(str, str1); + public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { + return con.prepareStatement(sql, columnNames); } /* @@ -686,15 +608,14 @@ public java.sql.PreparedStatement prepareStatement(java.lang.String str, java.la * * @see java.sql.Connection#rollback(java.sql.Savepoint) */ - public void rollback(java.sql.Savepoint savepoint) throws java.sql.SQLException { + public void rollback(Savepoint savepoint) throws SQLException { destroy = true; con.rollback(savepoint); } /** - * Getter for property idle_time. - * - * @return Value of property idle_time. + * Gets the idle time. + * @return idle time. */ public long getIdleTime() { return idleTime; diff --git a/src/main/java/org/semanticwb/base/db/PoolConnectionTimeLock.java b/src/main/java/org/semanticwb/base/db/PoolConnectionTimeLock.java index 350bdaf..fe7f2b2 100644 --- a/src/main/java/org/semanticwb/base/db/PoolConnectionTimeLock.java +++ b/src/main/java/org/semanticwb/base/db/PoolConnectionTimeLock.java @@ -22,17 +22,14 @@ */ package org.semanticwb.base.db; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Timer; -import java.util.TimerTask; -import java.util.concurrent.ConcurrentHashMap; - import org.semanticwb.Logger; import org.semanticwb.SWBUtils; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + /** + * Manages connection time to avoid resource usage locking. * Administra la duración de las conexiones con el fin de identificar cuando una * conexión excedio el tiempo limite permitido (300sg) de duración, al estar * siendo utilizada por un recurso. @@ -40,29 +37,20 @@ * @author Javier Solis Gonzalez (jsolis@infotec.com.mx) */ public class PoolConnectionTimeLock extends TimerTask { - - /** The log. */ private static Logger log = SWBUtils.getLogger(PoolConnectionTimeLock.class); - - /** The timer. */ private Timer timer = null; - /** The pools. */ private ConcurrentHashMap pools = new ConcurrentHashMap(); - - /** The last time. */ private volatile long lastTime = System.nanoTime(); /** - * Creates a new instance of PoolConnectionTimeLock. + * Constructor. Creates a new instance of {@link PoolConnectionTimeLock}. */ public PoolConnectionTimeLock() { } /** - * Adds the connection. - * - * @param con - * the con + * Adds a {@link PoolConnection} to the list of managed connections. + * @param con connection to add. */ public void addConnection(PoolConnection con) { if (con != null) { @@ -78,7 +66,7 @@ public void addConnection(PoolConnection con) { pool = new ConcurrentHashMap(); pools.put(con.getPool().getName(), pool); } - pool.put(Long.valueOf(con.getId()), con.getDescription()); + pool.put(con.getId(), con.getDescription()); } catch (Exception e) { log.error(e); } @@ -86,17 +74,15 @@ public void addConnection(PoolConnection con) { } /** - * Removes the connection. - * - * @param con - * the con + * Removes a {@link PoolConnection} from the list of managed connections. + * @param con connection to remove. */ public void removeConnection(PoolConnection con) { if (con != null) { try { ConcurrentHashMap pool = (ConcurrentHashMap) pools.get(con.getPool().getName()); if (pool != null) { - pool.remove(Long.valueOf(con.getId())); + pool.remove(con.getId()); con.getPool().addHit(System.currentTimeMillis() - con.getIdleTime()); } } catch (Exception e) { @@ -129,7 +115,7 @@ public void run() { } /** - * Destroy. + * Destroys {@link PoolConnectionTimeLock}. */ public void destroy() { log.info("PoolConnectionTimeLock Finished" + "..."); @@ -141,7 +127,7 @@ public void destroy() { } /** - * Inits the. + * Inits the {@link PoolConnectionTimeLock}. */ public void init() { log.info("PoolConnectionTimeLock Started" + "..."); @@ -150,10 +136,10 @@ public void init() { } /** - * Stop. + * Stops the {@link PoolConnectionTimeLock}. */ public void stop() { - log.info("PoolConnectionTimeLock Stoped" + "..."); + log.info("PoolConnectionTimeLock Stopped" + "..."); if (timer != null) { timer.cancel(); this.cancel(); @@ -162,9 +148,8 @@ public void stop() { } /** - * Getter for property pools. - * - * @return Value of property pools. + * Gets a map with the managed connections. + * @return map of managed connections. * */ public HashMap getPools() { diff --git a/src/main/java/org/semanticwb/base/db/PoolPreparedStatement.java b/src/main/java/org/semanticwb/base/db/PoolPreparedStatement.java index 1d1f425..aadcae6 100644 --- a/src/main/java/org/semanticwb/base/db/PoolPreparedStatement.java +++ b/src/main/java/org/semanticwb/base/db/PoolPreparedStatement.java @@ -22,79 +22,44 @@ */ 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.Calendar; -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. + * Implementation of {@link PreparedStatement} for usage with a {@link PoolConnection}. * @author Javier Solis Gonzalez (jsolis@infotec.com.mx) */ public class PoolPreparedStatement implements java.sql.PreparedStatement { - - private static final Logger LOG = SWBUtils.getLogger(PoolPreparedStatement.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 con. */ private Connection con; /** - * Creates a new instance of PoolStatement. - * - * @param st the st - * @param con the con + * Creates a new instance of a {@link PoolStatement}. + * @param st the statement. + * @param con the connection. */ - public PoolPreparedStatement(PreparedStatement st, Connection con) - { + public PoolPreparedStatement(PreparedStatement st, Connection con) { this.st = st; this.con = con; } /** - * Creates a new instance of PoolStatement. - * - * @param st the st - * @param query the query - * @param con the con - */ - public PoolPreparedStatement(PreparedStatement st, String query, Connection con) - { + * Creates a new instance of {@link PoolStatement}. + * @param st the statement. + * @param query the SQL query String. + * @param con the connection. + */ + public PoolPreparedStatement(PreparedStatement st, String query, Connection con) { this.st = st; this.query = query; this.con = con; @@ -103,40 +68,35 @@ public PoolPreparedStatement(PreparedStatement st, String query, Connection con) /* (non-Javadoc) * @see java.sql.Statement#addBatch(java.lang.String) */ - public void addBatch(String str) throws java.sql.SQLException - { - st.addBatch(str); + public void addBatch(String sql) throws SQLException { + st.addBatch(sql); } /* (non-Javadoc) * @see java.sql.Statement#cancel() */ - public void cancel() throws java.sql.SQLException - { + public void cancel() throws SQLException { st.cancel(); } /* (non-Javadoc) * @see java.sql.Statement#clearBatch() */ - public void clearBatch() throws java.sql.SQLException - { + public void clearBatch() throws SQLException { st.clearBatch(); } /* (non-Javadoc) * @see java.sql.Statement#clearWarnings() */ - public void clearWarnings() throws java.sql.SQLException - { + public void clearWarnings() throws SQLException { st.clearWarnings(); } /* (non-Javadoc) * @see java.sql.Statement#close() */ - public void close() throws java.sql.SQLException - { + public void close() throws SQLException { closed = true; st.close(); } @@ -144,215 +104,169 @@ public void close() throws java.sql.SQLException /* (non-Javadoc) * @see java.sql.Statement#execute(java.lang.String) */ - public boolean execute(String str) throws java.sql.SQLException - { - if (debug) - { - LOG.debug("execute:" + str); - } - return st.execute(str); + public boolean execute(String sql) throws SQLException { + return st.execute(sql); } /* (non-Javadoc) * @see java.sql.Statement#executeBatch() */ - public int[] executeBatch() throws java.sql.SQLException - { - if (debug) - { - LOG.debug("executeBatch():"); - } + public int[] executeBatch() throws SQLException { return st.executeBatch(); } /* (non-Javadoc) * @see java.sql.Statement#executeQuery(java.lang.String) */ - public java.sql.ResultSet executeQuery(String str) throws java.sql.SQLException - { - if (debug) - { - LOG.debug("executeQuery:" + str); - } - return st.executeQuery(str); + public ResultSet executeQuery(String sql) throws SQLException { + return st.executeQuery(sql); } /* (non-Javadoc) * @see java.sql.Statement#executeUpdate(java.lang.String) */ - public int executeUpdate(String str) throws java.sql.SQLException - { - if (debug) - { - LOG.debug("executeUpdate:" + str); - } - return st.executeUpdate(str); + public int executeUpdate(String sql) throws SQLException { + return st.executeUpdate(sql); } /* (non-Javadoc) * @see java.sql.Statement#getConnection() */ - public java.sql.Connection getConnection() throws java.sql.SQLException - { - //return st.getConnection(); + public Connection getConnection() throws SQLException { return con; } /* (non-Javadoc) * @see java.sql.Statement#getFetchDirection() */ - public int getFetchDirection() throws java.sql.SQLException - { + public int getFetchDirection() throws SQLException { return st.getFetchDirection(); } /* (non-Javadoc) * @see java.sql.Statement#getFetchSize() */ - public int getFetchSize() throws java.sql.SQLException - { + public int getFetchSize() throws SQLException { return st.getFetchSize(); } /* (non-Javadoc) * @see java.sql.Statement#getMaxFieldSize() */ - public int getMaxFieldSize() throws java.sql.SQLException - { + public int getMaxFieldSize() throws SQLException { return st.getMaxFieldSize(); } /* (non-Javadoc) * @see java.sql.Statement#getMaxRows() */ - public int getMaxRows() throws java.sql.SQLException - { + public int getMaxRows() throws SQLException { return st.getMaxRows(); } /* (non-Javadoc) * @see java.sql.Statement#getMoreResults() */ - public boolean getMoreResults() throws java.sql.SQLException - { + public boolean getMoreResults() throws SQLException { return st.getMoreResults(); } /* (non-Javadoc) * @see java.sql.Statement#getQueryTimeout() */ - public int getQueryTimeout() throws java.sql.SQLException - { + public int getQueryTimeout() throws SQLException { return st.getQueryTimeout(); } /* (non-Javadoc) * @see java.sql.Statement#getResultSet() */ - public java.sql.ResultSet getResultSet() throws java.sql.SQLException - { - if (debug) - { - LOG.debug("getResultSet"); - } + public java.sql.ResultSet getResultSet() throws SQLException { return st.getResultSet(); } /* (non-Javadoc) * @see java.sql.Statement#getResultSetConcurrency() */ - public int getResultSetConcurrency() throws java.sql.SQLException - { + public int getResultSetConcurrency() throws SQLException { return st.getResultSetConcurrency(); } /* (non-Javadoc) * @see java.sql.Statement#getResultSetType() */ - public int getResultSetType() throws java.sql.SQLException - { + public int getResultSetType() throws SQLException { return st.getResultSetType(); } /* (non-Javadoc) * @see java.sql.Statement#getUpdateCount() */ - public int getUpdateCount() throws java.sql.SQLException - { + public int getUpdateCount() throws SQLException { return st.getUpdateCount(); } /* (non-Javadoc) * @see java.sql.Statement#getWarnings() */ - public java.sql.SQLWarning getWarnings() throws java.sql.SQLException - { + public java.sql.SQLWarning getWarnings() throws SQLException { return st.getWarnings(); } /* (non-Javadoc) * @see java.sql.Statement#setCursorName(java.lang.String) */ - public void setCursorName(String str) throws java.sql.SQLException - { - st.setCursorName(str); + public void setCursorName(String name) throws SQLException { + st.setCursorName(name); } /* (non-Javadoc) * @see java.sql.Statement#setEscapeProcessing(boolean) */ - public void setEscapeProcessing(boolean param) throws java.sql.SQLException - { - st.setEscapeProcessing(param); + public void setEscapeProcessing(boolean enable) throws SQLException { + st.setEscapeProcessing(enable); } /* (non-Javadoc) * @see java.sql.Statement#setFetchDirection(int) */ - public void setFetchDirection(int param) throws java.sql.SQLException - { - st.setFetchDirection(param); + public void setFetchDirection(int direction) throws SQLException { + st.setFetchDirection(direction); } /* (non-Javadoc) * @see java.sql.Statement#setFetchSize(int) */ - public void setFetchSize(int param) throws java.sql.SQLException - { - st.setFetchSize(param); + public void setFetchSize(int fetchSize) throws SQLException { + st.setFetchSize(fetchSize); } /* (non-Javadoc) * @see java.sql.Statement#setMaxFieldSize(int) */ - public void setMaxFieldSize(int param) throws java.sql.SQLException - { - st.setMaxFieldSize(param); + public void setMaxFieldSize(int max) throws SQLException { + st.setMaxFieldSize(max); } /* (non-Javadoc) * @see java.sql.Statement#setMaxRows(int) */ - public void setMaxRows(int param) throws java.sql.SQLException - { - st.setMaxRows(param); + public void setMaxRows(int max) throws SQLException { + st.setMaxRows(max); } /* (non-Javadoc) * @see java.sql.Statement#setQueryTimeout(int) */ - public void setQueryTimeout(int param) throws java.sql.SQLException - { - st.setQueryTimeout(param); + public void setQueryTimeout(int seconds) throws SQLException { + st.setQueryTimeout(seconds); } /** - * Checks if is closed. - * - * @return true, if is closed + * Checks if statement is closed. + * @return true if it is closed. */ - public boolean isClosed() - { + public boolean isClosed() { return closed; } @@ -360,593 +274,424 @@ public boolean isClosed() /* (non-Javadoc) * @see java.sql.Statement#execute(java.lang.String, java.lang.String[]) */ -public boolean execute(String str, String[] str1) throws java.sql.SQLException - { - if (debug) - { - LOG.debug("execute:" + str + " " + str1); - } - return st.execute(str, str1); + public boolean execute(String sql, String[] columnNames) throws SQLException { + return st.execute(sql, columnNames); } /* (non-Javadoc) * @see java.sql.Statement#execute(java.lang.String, int[]) */ - public boolean execute(String str, int[] values) throws java.sql.SQLException - { - if (debug) - { - LOG.debug("execute:" + str + " " + values); - } - return st.execute(str, values); + public boolean execute(String sql, int[] columnIndexes) throws SQLException { + return st.execute(sql, columnIndexes); } /* (non-Javadoc) * @see java.sql.Statement#execute(java.lang.String, int) */ - public boolean execute(String str, int param) throws java.sql.SQLException - { - if (debug) - { - LOG.debug("execute:" + str + " " + param); - } - return st.execute(str, param); + public boolean execute(String sql, int autoGeneratedKeys) throws SQLException { + return st.execute(sql, autoGeneratedKeys); } /* (non-Javadoc) * @see java.sql.Statement#getResultSetHoldability() */ - public int getResultSetHoldability() throws java.sql.SQLException - { + public int getResultSetHoldability() throws SQLException { return st.getResultSetHoldability(); } /* (non-Javadoc) * @see java.sql.Statement#getMoreResults(int) */ - public boolean getMoreResults(int param) throws java.sql.SQLException - { - return st.getMoreResults(param); + public boolean getMoreResults(int current) throws SQLException { + return st.getMoreResults(current); } /* (non-Javadoc) * @see java.sql.Statement#executeUpdate(java.lang.String, java.lang.String[]) */ - public int executeUpdate(String str, String[] str1) throws java.sql.SQLException - { - if (debug) - { - LOG.debug("executeUpdate():" + str + " " + str1); - } - return st.executeUpdate(str, str1); + public int executeUpdate(String sql, String[] columnNames) throws SQLException { + return st.executeUpdate(sql, columnNames); } /* (non-Javadoc) * @see java.sql.Statement#executeUpdate(java.lang.String, int) */ - public int executeUpdate(String str, int param) throws java.sql.SQLException - { - if (debug) - { - LOG.debug("executeUpdate():" + str + " " + param); - } - return st.executeUpdate(str, param); + public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException { + return st.executeUpdate(sql, autoGeneratedKeys); } /* (non-Javadoc) * @see java.sql.Statement#executeUpdate(java.lang.String, int[]) */ - public int executeUpdate(String str, int[] values) throws java.sql.SQLException - { - if (debug) - { - LOG.debug("executeUpdate():" + str + " " + values); - } - return st.executeUpdate(str, values); + public int executeUpdate(String sql, int[] columnIndexes) throws SQLException { + return st.executeUpdate(sql, columnIndexes); } /* (non-Javadoc) * @see java.sql.Statement#getGeneratedKeys() */ - public java.sql.ResultSet getGeneratedKeys() throws java.sql.SQLException - { + public ResultSet getGeneratedKeys() throws SQLException { return st.getGeneratedKeys(); } /* (non-Javadoc) * @see java.sql.PreparedStatement#executeQuery() */ - public ResultSet executeQuery() throws SQLException - { - if (debug) - { - LOG.debug("executeQuery():" + query); - } + public ResultSet executeQuery() throws SQLException { return st.executeQuery(); } /* (non-Javadoc) * @see java.sql.PreparedStatement#executeUpdate() */ - public int executeUpdate() throws SQLException - { - if (debug) - { - LOG.debug("executeUpdate():" + query); - } + public int executeUpdate() throws SQLException { return st.executeUpdate(); } /* (non-Javadoc) * @see java.sql.PreparedStatement#setNull(int, int) */ - public void setNull(int parameterIndex, int sqlType) throws SQLException - { - if (debug) - { - args += " " + parameterIndex + " " + sqlType; - } + public void setNull(int parameterIndex, int sqlType) throws SQLException { st.setNull(parameterIndex, sqlType); } /* (non-Javadoc) * @see java.sql.PreparedStatement#setBoolean(int, boolean) */ - public void setBoolean(int parameterIndex, boolean x) throws SQLException - { - if (debug) - { - args += " " + parameterIndex + " " + x; - } + public void setBoolean(int parameterIndex, boolean x) throws SQLException { st.setBoolean(parameterIndex, x); } /* (non-Javadoc) * @see java.sql.PreparedStatement#setByte(int, byte) */ - public void setByte(int parameterIndex, byte x) throws SQLException - { - if (debug) - { - args += " " + parameterIndex + " " + x; - } + public void setByte(int parameterIndex, byte x) throws SQLException { st.setByte(parameterIndex, x); } /* (non-Javadoc) * @see java.sql.PreparedStatement#setShort(int, short) */ - public void setShort(int parameterIndex, short x) throws SQLException - { - if (debug) - { - args += " " + parameterIndex + " " + x; - } + public void setShort(int parameterIndex, short x) throws SQLException { st.setShort(parameterIndex, x); } /* (non-Javadoc) * @see java.sql.PreparedStatement#setInt(int, int) */ - public void setInt(int parameterIndex, int x) throws SQLException - { - if (debug) - { - args += " " + parameterIndex + " " + x; - } + public void setInt(int parameterIndex, int x) throws SQLException { st.setInt(parameterIndex, x); } /* (non-Javadoc) * @see java.sql.PreparedStatement#setLong(int, long) */ - public void setLong(int parameterIndex, long x) throws SQLException - { - if (debug) - { - args += " " + parameterIndex + " " + x; - } + public void setLong(int parameterIndex, long x) throws SQLException { st.setLong(parameterIndex, x); } /* (non-Javadoc) * @see java.sql.PreparedStatement#setFloat(int, float) */ - public void setFloat(int parameterIndex, float x) throws SQLException - { - if (debug) - { - args += " " + parameterIndex + " " + x; - } + public void setFloat(int parameterIndex, float x) throws SQLException { st.setFloat(parameterIndex, x); } /* (non-Javadoc) * @see java.sql.PreparedStatement#setDouble(int, double) */ - public void setDouble(int parameterIndex, double x) throws SQLException - { - if (debug) - { - args += " " + parameterIndex + " " + x; - } + public void setDouble(int parameterIndex, double x) throws SQLException { st.setDouble(parameterIndex, x); } /* (non-Javadoc) * @see java.sql.PreparedStatement#setBigDecimal(int, java.math.BigDecimal) */ - public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException - { - if (debug) - { - args += " " + parameterIndex + " " + x; - } + public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException { st.setBigDecimal(parameterIndex, x); } /* (non-Javadoc) * @see java.sql.PreparedStatement#setString(int, java.lang.String) */ - public void setString(int parameterIndex, String x) throws SQLException - { - if (debug) - { - args += " " + parameterIndex + " " + x; - } + public void setString(int parameterIndex, String x) throws SQLException { st.setString(parameterIndex, x); } /* (non-Javadoc) * @see java.sql.PreparedStatement#setBytes(int, byte[]) */ - public void setBytes(int parameterIndex, byte[] x) throws SQLException - { - if (debug) - { - args += " " + parameterIndex + " " + x; - } + public void setBytes(int parameterIndex, byte[] x) throws SQLException { st.setBytes(parameterIndex, x); } /* (non-Javadoc) * @see java.sql.PreparedStatement#setDate(int, java.sql.Date) */ - public void setDate(int parameterIndex, Date x) throws SQLException - { - if (debug) - { - args += " " + parameterIndex + " " + x; - } + public void setDate(int parameterIndex, Date x) throws SQLException { st.setDate(parameterIndex, x); } /* (non-Javadoc) * @see java.sql.PreparedStatement#setTime(int, java.sql.Time) */ - public void setTime(int parameterIndex, Time x) throws SQLException - { - if (debug) - { - args += " " + parameterIndex + " " + x; - } + public void setTime(int parameterIndex, Time x) throws SQLException { st.setTime(parameterIndex, x); } /* (non-Javadoc) * @see java.sql.PreparedStatement#setTimestamp(int, java.sql.Timestamp) */ - public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException - { - if (debug) - { - args += " " + parameterIndex + " " + x; - } + public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException { st.setTimestamp(parameterIndex, x); } - /* (non-Javadoc) * @see java.sql.PreparedStatement#setAsciiStream(int, java.io.InputStream, int) */ - public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException - { + public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException { st.setAsciiStream(parameterIndex, x, length); } /* (non-Javadoc) * @see java.sql.PreparedStatement#setUnicodeStream(int, java.io.InputStream, int) */ - public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException - { - st.setCharacterStream(parameterIndex, new InputStreamReader(x), length); - //st.setUnicodeStream(parameterIndex, x, length); + public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException { + st.setCharacterStream(parameterIndex, new InputStreamReader(x), length); } /* (non-Javadoc) * @see java.sql.PreparedStatement#setBinaryStream(int, java.io.InputStream, int) */ - public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException - { + public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException { st.setBinaryStream(parameterIndex, x, length); } /* (non-Javadoc) * @see java.sql.PreparedStatement#clearParameters() */ - public void clearParameters() throws SQLException - { + public void clearParameters() throws SQLException { st.clearParameters(); } /* (non-Javadoc) * @see java.sql.PreparedStatement#setObject(int, java.lang.Object, int, int) */ - public void setObject(int parameterIndex, Object x, int targetSqlType, int scale) throws SQLException - { + public void setObject(int parameterIndex, Object x, int targetSqlType, int scale) throws SQLException { st.setObject(parameterIndex, x, targetSqlType, scale); } /* (non-Javadoc) * @see java.sql.PreparedStatement#setObject(int, java.lang.Object, int) */ - public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException - { + public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException { st.setObject(parameterIndex, x, targetSqlType); } /* (non-Javadoc) * @see java.sql.PreparedStatement#setObject(int, java.lang.Object) */ - public void setObject(int parameterIndex, Object x) throws SQLException - { + public void setObject(int parameterIndex, Object x) throws SQLException { st.setObject(parameterIndex, x); } /* (non-Javadoc) * @see java.sql.PreparedStatement#execute() */ - public boolean execute() throws SQLException - { + public boolean execute() throws SQLException { boolean ret; - long time = 0; - if (debug) - { - time = System.currentTimeMillis(); - LOG.debug("----------------------------------------------"); - LOG.debug("--> execute():" + query); - LOG.debug("--> args:" + args); - args = ""; - } ret = st.execute(); - if (debug) - { - LOG.debug("------------------" + (System.currentTimeMillis() - time) + "-----------------------"); - } return ret; } /* (non-Javadoc) * @see java.sql.PreparedStatement#addBatch() */ - public void addBatch() throws SQLException - { + public void addBatch() throws SQLException { st.addBatch(); } /* (non-Javadoc) * @see java.sql.PreparedStatement#setCharacterStream(int, java.io.Reader, int) */ - public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException - { + public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException { st.setCharacterStream(parameterIndex, reader, length); } /* (non-Javadoc) * @see java.sql.PreparedStatement#setRef(int, java.sql.Ref) */ - public void setRef(int i, Ref x) throws SQLException - { + public void setRef(int i, Ref x) throws SQLException { st.setRef(i, x); } /* (non-Javadoc) * @see java.sql.PreparedStatement#setBlob(int, java.sql.Blob) */ - public void setBlob(int i, Blob x) throws SQLException - { + public void setBlob(int i, Blob x) throws SQLException { st.setBlob(i, x); } /* (non-Javadoc) * @see java.sql.PreparedStatement#setClob(int, java.sql.Clob) */ - public void setClob(int i, Clob x) throws SQLException - { + public void setClob(int i, Clob x) throws SQLException { st.setClob(i, x); } /* (non-Javadoc) * @see java.sql.PreparedStatement#setArray(int, java.sql.Array) */ - public void setArray(int i, Array x) throws SQLException - { + public void setArray(int i, Array x) throws SQLException { st.setArray(i, x); } /* (non-Javadoc) * @see java.sql.PreparedStatement#getMetaData() */ - public ResultSetMetaData getMetaData() throws SQLException - { + public ResultSetMetaData getMetaData() throws SQLException { return st.getMetaData(); } /* (non-Javadoc) * @see java.sql.PreparedStatement#setDate(int, java.sql.Date, java.util.Calendar) */ - public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException - { + public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException { st.setDate(parameterIndex, x, cal); } /* (non-Javadoc) * @see java.sql.PreparedStatement#setTime(int, java.sql.Time, java.util.Calendar) */ - public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException - { + public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException { st.setTime(parameterIndex, x, cal); } /* (non-Javadoc) * @see java.sql.PreparedStatement#setTimestamp(int, java.sql.Timestamp, java.util.Calendar) */ - public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException - { + public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } /* (non-Javadoc) * @see java.sql.PreparedStatement#setNull(int, int, java.lang.String) */ - public void setNull(int paramIndex, int sqlType, String typeName) throws SQLException - { + public void setNull(int paramIndex, int sqlType, String typeName) throws SQLException { st.setNull(paramIndex, sqlType, typeName); } /* (non-Javadoc) * @see java.sql.PreparedStatement#setURL(int, java.net.URL) */ - public void setURL(int parameterIndex, URL x) throws SQLException - { + public void setURL(int parameterIndex, URL x) throws SQLException { st.setURL(parameterIndex, x); } /* (non-Javadoc) * @see java.sql.PreparedStatement#getParameterMetaData() */ - public ParameterMetaData getParameterMetaData() throws SQLException - { + public ParameterMetaData getParameterMetaData() throws SQLException { return st.getParameterMetaData(); } //********************************** version 1.6 public void setPoolable(boolean poolable) throws SQLException { - st.setPoolable(poolable); + st.setPoolable(poolable); } public boolean isPoolable() throws SQLException { - return st.isPoolable(); + return st.isPoolable(); } public T unwrap(Class iface) throws SQLException { - return st.unwrap(iface); + return st.unwrap(iface); } public boolean isWrapperFor(Class iface) throws SQLException { - return st.isWrapperFor(iface); + return st.isWrapperFor(iface); } - public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException - { - st.setAsciiStream(parameterIndex, x, length); + public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException { + st.setAsciiStream(parameterIndex, x, length); } - public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException - { - st.setAsciiStream(parameterIndex, x); + public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException { + st.setAsciiStream(parameterIndex, x); } - public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException - { - st.setBinaryStream(parameterIndex, x, length); + public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException { + st.setBinaryStream(parameterIndex, x, length); } - public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException - { - st.setBinaryStream(parameterIndex, x); + public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException { + st.setBinaryStream(parameterIndex, x); } - public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException - { - st.setBlob(parameterIndex, inputStream, length); + public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException { + st.setBlob(parameterIndex, inputStream, length); } - public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException - { - st.setBlob(parameterIndex, inputStream); + public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException { + st.setBlob(parameterIndex, inputStream); } - public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException - { - st.setCharacterStream(parameterIndex, reader, length); + public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException { + st.setCharacterStream(parameterIndex, reader, length); } - public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException - { - st.setCharacterStream(parameterIndex, reader); + public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException { + st.setCharacterStream(parameterIndex, reader); } - public void setClob(int parameterIndex, Reader reader, long length) throws SQLException - { - st.setClob(parameterIndex, reader, length); + public void setClob(int parameterIndex, Reader reader, long length) throws SQLException { + st.setClob(parameterIndex, reader, length); } - public void setClob(int parameterIndex, Reader reader) throws SQLException - { - st.setClob(parameterIndex, reader); + public void setClob(int parameterIndex, Reader reader) throws SQLException { + st.setClob(parameterIndex, reader); } - public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException - { - st.setNCharacterStream(parameterIndex, value, length); + public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException { + st.setNCharacterStream(parameterIndex, value, length); } - public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException - { - st.setNCharacterStream(parameterIndex, value); + public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException { + st.setNCharacterStream(parameterIndex, value); } - public void setNClob(int parameterIndex, NClob value) throws SQLException - { - st.setNClob(parameterIndex, value); + public void setNClob(int parameterIndex, NClob value) throws SQLException { + st.setNClob(parameterIndex, value); } - public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException - { - st.setNClob(parameterIndex, reader, length); + public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException { + st.setNClob(parameterIndex, reader, length); } - public void setNClob(int parameterIndex, Reader reader) throws SQLException - { - st.setNClob(parameterIndex, reader); + public void setNClob(int parameterIndex, Reader reader) throws SQLException { + st.setNClob(parameterIndex, reader); } - public void setNString(int parameterIndex, String value) throws SQLException - { - st.setNString(parameterIndex, value); + public void setNString(int parameterIndex, String value) throws SQLException { + st.setNString(parameterIndex, value); } - public void setRowId(int parameterIndex, RowId x) throws SQLException - { - st.setRowId(parameterIndex, x); + public void setRowId(int parameterIndex, RowId x) throws SQLException { + st.setRowId(parameterIndex, x); } - public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException - { - st.setSQLXML(parameterIndex, xmlObject); + public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException { + st.setSQLXML(parameterIndex, xmlObject); } /* MAPS74 - JDK 7 SE Wrapper */ @Override - public void closeOnCompletion() throws SQLException - { + public void closeOnCompletion() throws SQLException { st.closeOnCompletion(); } @Override - public boolean isCloseOnCompletion() throws SQLException - { + public boolean isCloseOnCompletion() throws SQLException { return isCloseOnCompletion(); } } diff --git a/src/main/java/org/semanticwb/base/db/PoolStatement.java b/src/main/java/org/semanticwb/base/db/PoolStatement.java index 96f761b..3cb3355 100644 --- a/src/main/java/org/semanticwb/base/db/PoolStatement.java +++ b/src/main/java/org/semanticwb/base/db/PoolStatement.java @@ -27,29 +27,18 @@ import java.sql.Statement; /** - * Objeto que sobrescribe la clase Statement para poder tener control la misma - * desde el Pool de conexiones. - * + * Implementation of {@link Statement} for usage with a {@link PoolConnection}. * @author Javier Solis Gonzalez (jsolis@infotec.com.mx) */ public class PoolStatement implements java.sql.Statement { - - /** The st. */ Statement st; - - /** The closed. */ boolean closed = false; - - /** The con. */ Connection con; /** - * Creates a new instance of PoolStatement. - * - * @param st - * the st - * @param con - * the con + * Constructor. Creates a new instance of {@link PoolStatement}. + * @param st the statement. + * @param con the connection. */ public PoolStatement(Statement st, Connection con) { this.st = st; @@ -61,8 +50,8 @@ public PoolStatement(Statement st, Connection con) { * * @see java.sql.Statement#addBatch(java.lang.String) */ - public void addBatch(String str) throws java.sql.SQLException { - st.addBatch(str); + public void addBatch(String sql) throws SQLException { + st.addBatch(sql); } /* @@ -70,7 +59,7 @@ public void addBatch(String str) throws java.sql.SQLException { * * @see java.sql.Statement#cancel() */ - public void cancel() throws java.sql.SQLException { + public void cancel() throws SQLException { st.cancel(); } @@ -79,7 +68,7 @@ public void cancel() throws java.sql.SQLException { * * @see java.sql.Statement#clearBatch() */ - public void clearBatch() throws java.sql.SQLException { + public void clearBatch() throws SQLException { st.clearBatch(); } @@ -88,7 +77,7 @@ public void clearBatch() throws java.sql.SQLException { * * @see java.sql.Statement#clearWarnings() */ - public void clearWarnings() throws java.sql.SQLException { + public void clearWarnings() throws SQLException { st.clearWarnings(); } @@ -97,7 +86,7 @@ public void clearWarnings() throws java.sql.SQLException { * * @see java.sql.Statement#close() */ - public void close() throws java.sql.SQLException { + public void close() throws SQLException { closed = true; st.close(); } @@ -107,8 +96,8 @@ public void close() throws java.sql.SQLException { * * @see java.sql.Statement#execute(java.lang.String) */ - public boolean execute(String str) throws java.sql.SQLException { - return st.execute(str); + public boolean execute(String sql) throws SQLException { + return st.execute(sql); } /* @@ -116,7 +105,7 @@ public boolean execute(String str) throws java.sql.SQLException { * * @see java.sql.Statement#executeBatch() */ - public int[] executeBatch() throws java.sql.SQLException { + public int[] executeBatch() throws SQLException { return st.executeBatch(); } @@ -125,8 +114,8 @@ public int[] executeBatch() throws java.sql.SQLException { * * @see java.sql.Statement#executeQuery(java.lang.String) */ - public java.sql.ResultSet executeQuery(String str) throws java.sql.SQLException { - return st.executeQuery(str); + public java.sql.ResultSet executeQuery(String sql) throws SQLException { + return st.executeQuery(sql); } /* @@ -134,8 +123,8 @@ public java.sql.ResultSet executeQuery(String str) throws java.sql.SQLException * * @see java.sql.Statement#executeUpdate(java.lang.String) */ - public int executeUpdate(String str) throws java.sql.SQLException { - return st.executeUpdate(str); + public int executeUpdate(String sql) throws SQLException { + return st.executeUpdate(sql); } /* @@ -143,7 +132,7 @@ public int executeUpdate(String str) throws java.sql.SQLException { * * @see java.sql.Statement#getConnection() */ - public java.sql.Connection getConnection() throws java.sql.SQLException { + public java.sql.Connection getConnection() throws SQLException { return con; } @@ -152,7 +141,7 @@ public java.sql.Connection getConnection() throws java.sql.SQLException { * * @see java.sql.Statement#getFetchDirection() */ - public int getFetchDirection() throws java.sql.SQLException { + public int getFetchDirection() throws SQLException { return st.getFetchDirection(); } @@ -161,7 +150,7 @@ public int getFetchDirection() throws java.sql.SQLException { * * @see java.sql.Statement#getFetchSize() */ - public int getFetchSize() throws java.sql.SQLException { + public int getFetchSize() throws SQLException { return st.getFetchSize(); } @@ -170,7 +159,7 @@ public int getFetchSize() throws java.sql.SQLException { * * @see java.sql.Statement#getMaxFieldSize() */ - public int getMaxFieldSize() throws java.sql.SQLException { + public int getMaxFieldSize() throws SQLException { return st.getMaxFieldSize(); } @@ -179,7 +168,7 @@ public int getMaxFieldSize() throws java.sql.SQLException { * * @see java.sql.Statement#getMaxRows() */ - public int getMaxRows() throws java.sql.SQLException { + public int getMaxRows() throws SQLException { return st.getMaxRows(); } @@ -188,7 +177,7 @@ public int getMaxRows() throws java.sql.SQLException { * * @see java.sql.Statement#getMoreResults() */ - public boolean getMoreResults() throws java.sql.SQLException { + public boolean getMoreResults() throws SQLException { return st.getMoreResults(); } @@ -197,7 +186,7 @@ public boolean getMoreResults() throws java.sql.SQLException { * * @see java.sql.Statement#getQueryTimeout() */ - public int getQueryTimeout() throws java.sql.SQLException { + public int getQueryTimeout() throws SQLException { return st.getQueryTimeout(); } @@ -206,7 +195,7 @@ public int getQueryTimeout() throws java.sql.SQLException { * * @see java.sql.Statement#getResultSet() */ - public java.sql.ResultSet getResultSet() throws java.sql.SQLException { + public java.sql.ResultSet getResultSet() throws SQLException { return st.getResultSet(); } @@ -215,7 +204,7 @@ public java.sql.ResultSet getResultSet() throws java.sql.SQLException { * * @see java.sql.Statement#getResultSetConcurrency() */ - public int getResultSetConcurrency() throws java.sql.SQLException { + public int getResultSetConcurrency() throws SQLException { return st.getResultSetConcurrency(); } @@ -224,7 +213,7 @@ public int getResultSetConcurrency() throws java.sql.SQLException { * * @see java.sql.Statement#getResultSetType() */ - public int getResultSetType() throws java.sql.SQLException { + public int getResultSetType() throws SQLException { return st.getResultSetType(); } @@ -233,7 +222,7 @@ public int getResultSetType() throws java.sql.SQLException { * * @see java.sql.Statement#getUpdateCount() */ - public int getUpdateCount() throws java.sql.SQLException { + public int getUpdateCount() throws SQLException { return st.getUpdateCount(); } @@ -242,7 +231,7 @@ public int getUpdateCount() throws java.sql.SQLException { * * @see java.sql.Statement#getWarnings() */ - public java.sql.SQLWarning getWarnings() throws java.sql.SQLException { + public java.sql.SQLWarning getWarnings() throws SQLException { return st.getWarnings(); } @@ -251,8 +240,8 @@ public java.sql.SQLWarning getWarnings() throws java.sql.SQLException { * * @see java.sql.Statement#setCursorName(java.lang.String) */ - public void setCursorName(String str) throws java.sql.SQLException { - st.setCursorName(str); + public void setCursorName(String name) throws SQLException { + st.setCursorName(name); } /* @@ -260,8 +249,8 @@ public void setCursorName(String str) throws java.sql.SQLException { * * @see java.sql.Statement#setEscapeProcessing(boolean) */ - public void setEscapeProcessing(boolean param) throws java.sql.SQLException { - st.setEscapeProcessing(param); + public void setEscapeProcessing(boolean enable) throws SQLException { + st.setEscapeProcessing(enable); } /* @@ -269,8 +258,8 @@ public void setEscapeProcessing(boolean param) throws java.sql.SQLException { * * @see java.sql.Statement#setFetchDirection(int) */ - public void setFetchDirection(int param) throws java.sql.SQLException { - st.setFetchDirection(param); + public void setFetchDirection(int direction) throws SQLException { + st.setFetchDirection(direction); } /* @@ -278,8 +267,8 @@ public void setFetchDirection(int param) throws java.sql.SQLException { * * @see java.sql.Statement#setFetchSize(int) */ - public void setFetchSize(int param) throws java.sql.SQLException { - st.setFetchSize(param); + public void setFetchSize(int size) throws SQLException { + st.setFetchSize(size); } /* @@ -287,8 +276,8 @@ public void setFetchSize(int param) throws java.sql.SQLException { * * @see java.sql.Statement#setMaxFieldSize(int) */ - public void setMaxFieldSize(int param) throws java.sql.SQLException { - st.setMaxFieldSize(param); + public void setMaxFieldSize(int max) throws SQLException { + st.setMaxFieldSize(max); } /* @@ -296,8 +285,8 @@ public void setMaxFieldSize(int param) throws java.sql.SQLException { * * @see java.sql.Statement#setMaxRows(int) */ - public void setMaxRows(int param) throws java.sql.SQLException { - st.setMaxRows(param); + public void setMaxRows(int max) throws SQLException { + st.setMaxRows(max); } /* @@ -305,14 +294,13 @@ public void setMaxRows(int param) throws java.sql.SQLException { * * @see java.sql.Statement#setQueryTimeout(int) */ - public void setQueryTimeout(int param) throws java.sql.SQLException { - st.setQueryTimeout(param); + public void setQueryTimeout(int secons) throws SQLException { + st.setQueryTimeout(secons); } /** - * Checks if is closed. - * - * @return true, if is closed + * Checks if statement is closed. + * @return true, if it is closed. */ public boolean isClosed() { return closed; @@ -324,8 +312,8 @@ public boolean isClosed() { * * @see java.sql.Statement#execute(java.lang.String, java.lang.String[]) */ - public boolean execute(String str, String[] str1) throws java.sql.SQLException { - return st.execute(str, str1); + public boolean execute(String sql, String[] columnNames) throws SQLException { + return st.execute(sql, columnNames); } /* @@ -333,8 +321,8 @@ public boolean execute(String str, String[] str1) throws java.sql.SQLException { * * @see java.sql.Statement#execute(java.lang.String, int[]) */ - public boolean execute(String str, int[] values) throws java.sql.SQLException { - return st.execute(str, values); + public boolean execute(String sql, int[] columnIndexes) throws SQLException { + return st.execute(sql, columnIndexes); } /* @@ -342,8 +330,8 @@ public boolean execute(String str, int[] values) throws java.sql.SQLException { * * @see java.sql.Statement#execute(java.lang.String, int) */ - public boolean execute(String str, int param) throws java.sql.SQLException { - return st.execute(str, param); + public boolean execute(String sql, int autoGeneratedKeys) throws SQLException { + return st.execute(sql, autoGeneratedKeys); } /* @@ -351,7 +339,7 @@ public boolean execute(String str, int param) throws java.sql.SQLException { * * @see java.sql.Statement#getResultSetHoldability() */ - public int getResultSetHoldability() throws java.sql.SQLException { + public int getResultSetHoldability() throws SQLException { return st.getResultSetHoldability(); } @@ -360,8 +348,8 @@ public int getResultSetHoldability() throws java.sql.SQLException { * * @see java.sql.Statement#getMoreResults(int) */ - public boolean getMoreResults(int param) throws java.sql.SQLException { - return st.getMoreResults(param); + public boolean getMoreResults(int current) throws SQLException { + return st.getMoreResults(current); } /* @@ -369,8 +357,8 @@ public boolean getMoreResults(int param) throws java.sql.SQLException { * * @see java.sql.Statement#executeUpdate(java.lang.String, java.lang.String[]) */ - public int executeUpdate(String str, String[] str1) throws java.sql.SQLException { - return st.executeUpdate(str, str1); + public int executeUpdate(String sql, String[] columnNames) throws SQLException { + return st.executeUpdate(sql, columnNames); } /* @@ -378,8 +366,8 @@ public int executeUpdate(String str, String[] str1) throws java.sql.SQLException * * @see java.sql.Statement#executeUpdate(java.lang.String, int) */ - public int executeUpdate(String str, int param) throws java.sql.SQLException { - return st.executeUpdate(str, param); + public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException { + return st.executeUpdate(sql, autoGeneratedKeys); } /* @@ -387,8 +375,8 @@ public int executeUpdate(String str, int param) throws java.sql.SQLException { * * @see java.sql.Statement#executeUpdate(java.lang.String, int[]) */ - public int executeUpdate(String str, int[] values) throws java.sql.SQLException { - return st.executeUpdate(str, values); + public int executeUpdate(String sql, int[] columnIndexes) throws SQLException { + return st.executeUpdate(sql, columnIndexes); } /* diff --git a/src/main/java/org/semanticwb/base/util/ErrorElement.java b/src/main/java/org/semanticwb/base/util/ErrorElement.java index 4edd11e..3452cc0 100644 --- a/src/main/java/org/semanticwb/base/util/ErrorElement.java +++ b/src/main/java/org/semanticwb/base/util/ErrorElement.java @@ -25,153 +25,123 @@ import java.util.Date; /** - * Objeto: Representa y contiene una exception junto con un identificador y la - * fecha en la que se genero. + * Class to hold information about an error. Used in SWBAErrorElementViewer of SemanticWebBuilder Portal + * and {@link org.semanticwb.base.util.imp.Logger4jImpl} classes. Instances of this class are managed by + * {@link org.semanticwb.SWBUtils.ERROR} static class and stored in memory as a + * {@link org.semanticwb.SWBUtils} class attribute. * @author Javier Solis Gonzalez */ public class ErrorElement { - - /** The counter. */ static long counter; - - /** The id. */ private long id = 0; - - /** The msg. */ - private String msg = null; - - /** The date. */ + private String msg; private java.util.Date date; - - /** The throwable. */ private Throwable throwable; - - /** The cls. */ private Class cls; - - /** The level. */ private String level; + private static final String NEWLINE = "\n"; /** * Gets the error class. - * * @return the error class */ - public Class getErrorClass() - { + public Class getErrorClass() { return cls; } /** - * Gets the error level. - * - * @return the error level + * Gets the error level + * @return the error level. */ - public String getErrorLevel() - { + public String getErrorLevel() { return level; } /** - * Creates a new instance of ErrorElement. - * - * @param e the e - * @param msg the msg - * @param cls the cls - * @param level the level + * Constructor. Creates a new instance of {@link ErrorElement}. + * @param throwable the {@link Throwable} object related to the logged error. + * @param message the error message. + * @param cls class where error is generated. + * @param level the error level. */ - public ErrorElement(Throwable e, String msg, Class cls, String level) - { + public ErrorElement(Throwable throwable, String message, Class cls, String level) { id = getCounter(); date = new java.util.Date(); - throwable = e; - this.msg = msg; + this.throwable = throwable; + this.msg = message; } /** - * Gets the counter. - * - * @return the counter + * Gets the error counter. + * @return the counter. */ - public static synchronized long getCounter() - { + public static synchronized long getCounter() { return counter++; } /** - * Getter for property id. - * @return Value of property id. + * Gets the error id. + * @return error id. */ - public long getId() - { + public long getId() { return id; } /** - * Getter for property date. - * @return Value of property date. + * Gets error date. + * @return error date. */ - public Date getDate() - { + public Date getDate() { return date; } /** - * Getter for property throwable. - * @return Value of property throwable. + * Gets the error {@link Throwable} object. + * @return throwable. */ - public Throwable getThrowable() - { + public Throwable getThrowable() { return throwable; } /** - * Gets the message. - * - * @return the message + * Gets the error message. + * @return error message. */ - public String getMessage() - { - if (msg != null) - { + public String getMessage() { + if (msg != null) { return msg; //La alternativa a este multiple return implica crear objetos que no se utilizaran } return throwable.toString(); } /** - * Gets the stack trace. - * - * @return the stack trace + * Gets the error stack trace. + * @return the stack trace. */ - public String getStackTrace() - { + public String getStackTrace() { return printThrowable(throwable); } /** - * Prints the throwable. - * - * @param th the th - * @return the string + * Prints a {@link Throwable} object stack trace information. + * @param throwableobj the {@link Throwable} object. + * @return String with a stack trace information of a {@link Throwable}. */ - private String printThrowable(Throwable th) - { + private String printThrowable(Throwable throwableobj) { StringBuilder bug = new StringBuilder(); - if (th != null) - { - bug.append(date + ": " + th.getMessage() + "\n"); - StackTraceElement []elements = th.getStackTrace(); - bug.append("// " + th + "\n"); - for (int x = 0; x < elements.length; x++) - { - bug.append("// " + elements[x] + "\n"); + if (throwableobj != null) { + bug.append(date).append(": ").append(throwableobj.getMessage()).append(NEWLINE); + + StackTraceElement []elements = throwableobj.getStackTrace(); + bug.append("// ").append(throwableobj).append(NEWLINE); + + for (int x = 0; x < elements.length; x++) { + bug.append("// ").append(elements[x]).append(NEWLINE); } - Throwable rth = th.getCause(); - if (rth != null && rth != th) - { - bug.append("\nRoot Cause:\n\n"); + Throwable rth = throwableobj.getCause(); + if (rth != null && rth != throwableobj) { + bug.append(NEWLINE).append("Root Cause:").append(NEWLINE).append(NEWLINE); bug.append(printThrowable(rth)); } } diff --git a/src/main/java/org/semanticwb/base/util/FilterRule.java b/src/main/java/org/semanticwb/base/util/FilterRule.java deleted file mode 100644 index 368f28e..0000000 --- a/src/main/java/org/semanticwb/base/util/FilterRule.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * SemanticWebBuilder es una plataforma para el desarrollo de portales y aplicaciones de integración, - * colaboración y conocimiento, que gracias al uso de tecnología semántica puede generar contextos de - * información alrededor de algún tema de interés o bien integrar información y aplicaciones de diferentes - * fuentes, donde a la información se le asigna un significado, de forma que pueda ser interpretada y - * procesada por personas y/o sistemas, es una creación original del Fondo de Información y Documentación - * para la Industria INFOTEC, cuyo registro se encuentra actualmente en trámite. - * - * INFOTEC pone a su disposición la herramienta SemanticWebBuilder a través de su licenciamiento abierto al público (‘open source’), - * en virtud del cual, usted podrá usarlo en las mismas condiciones con que INFOTEC lo ha diseñado y puesto a su disposición; - * aprender de él; distribuirlo a terceros; acceder a su código fuente y modificarlo, y combinarlo o enlazarlo con otro software, - * todo ello de conformidad con los términos y condiciones de la LICENCIA ABIERTA AL PÚBLICO que otorga INFOTEC para la utilización - * del SemanticWebBuilder 4.0. - * - * INFOTEC no otorga garantía sobre SemanticWebBuilder, de ninguna especie y naturaleza, ni implícita ni explícita, - * siendo usted completamente responsable de la utilización que le dé y asumiendo la totalidad de los riesgos que puedan derivar - * de la misma. - * - * Si usted tiene cualquier duda o comentario sobre SemanticWebBuilder, INFOTEC pone a su disposición la siguiente - * dirección electrónica: - * http://www.semanticwebbuilder.org - */ -package org.semanticwb.base.util; - -/** - * - * @author javier.solis.g - */ -public interface FilterRule -{ - public boolean filter(Object obj); -} diff --git a/src/main/java/org/semanticwb/base/util/GIFEncoder.java b/src/main/java/org/semanticwb/base/util/GIFEncoder.java deleted file mode 100644 index 4588747..0000000 --- a/src/main/java/org/semanticwb/base/util/GIFEncoder.java +++ /dev/null @@ -1,671 +0,0 @@ -/* - * SemanticWebBuilder es una plataforma para el desarrollo de portales y aplicaciones de integración, - * colaboración y conocimiento, que gracias al uso de tecnología semántica puede generar contextos de - * información alrededor de algún tema de interés o bien integrar información y aplicaciones de diferentes - * fuentes, donde a la información se le asigna un significado, de forma que pueda ser interpretada y - * procesada por personas y/o sistemas, es una creación original del Fondo de Información y Documentación - * para la Industria INFOTEC, cuyo registro se encuentra actualmente en trámite. - * - * INFOTEC pone a su disposición la herramienta SemanticWebBuilder a través de su licenciamiento abierto al público ('open source'), - * en virtud del cual, usted podrá usarlo en las mismas condiciones con que INFOTEC lo ha diseñado y puesto a su disposición; - * aprender de él; distribuirlo a terceros; acceder a su código fuente y modificarlo, y combinarlo o enlazarlo con otro software, - * todo ello de conformidad con los términos y condiciones de la LICENCIA ABIERTA AL PÚBLICO que otorga INFOTEC para la utilización - * del SemanticWebBuilder 4.0. - * - * INFOTEC no otorga garantía sobre SemanticWebBuilder, de ninguna especie y naturaleza, ni implícita ni explícita, - * siendo usted completamente responsable de la utilización que le dé y asumiendo la totalidad de los riesgos que puedan derivar - * de la misma. - * - * Si usted tiene cualquier duda o comentario sobre SemanticWebBuilder, INFOTEC pone a su disposición la siguiente - * dirección electrónica: - * http://www.semanticwebbuilder.org.mx - */ -package org.semanticwb.base.util; - -import java.awt.AWTException; -import java.awt.Image; -import java.awt.image.PixelGrabber; -/* - * @(#)GIFEncoder.java 0.90 4/21/96 Adam Doppelt - */ -import java.io.IOException; -import java.io.OutputStream; - -/** - * GIFEncoder is a class which takes an image and saves it to a stream - * using the GIF file format (Graphics Interchange - * Format). A GIFEncoder - * is constructed with either an AWT Image (which must be fully - * loaded) or a set of RGB arrays. The image can be written out with a - * call to Write.

- * - * Three caveats: - *

    - *
  • GIFEncoder will convert the image to indexed color upon - * construction. This will take some time, depending on the size of - * the image. Also, actually writing the image out (Write) will take - * time.

    - * - *

  • The image cannot have more than 256 colors, since GIF is an 8 - * bit format. For a 24 bit to 8 bit quantization algorithm, see - * Graphics Gems II III.2 by Xialoin Wu. Or check out his C source.

    - * - *

  • Since the image must be completely loaded into memory, - * GIFEncoder may have problems with large images. Attempting to - * encode an image which will not fit into memory will probably - * result in the following exception:

    - * java.awt.AWTException: Grabber returned false: 192

    - *

- * - * GIFEncoder is based upon gifsave.c, which was written and released - * by:

- *

- * Sverre H. Huseby
- * Bjoelsengt. 17
- * N-0468 Oslo
- * Norway

- * - * Phone: +47 2 230539
- * sverrehu@ifi.uio.no

- *

- * @version DWC 0.91 1997-09-28 derived from version 0.90 21 Apr 1996 - * @author - * Adam Doppelt - * @author - * David W. Croft - */ -public class GIFEncoder { - - /** The height_. */ - short width_, height_; - - /** The num colors_. */ - int numColors_; - - /** The colors_. */ - byte pixels_[], colors_[]; - //ScreenDescriptor sd_; - //ImageDescriptor id_; - - /** - * Construct a GIFEncoder. The constructor will convert the image to - * an indexed color array. This may take some time.

- * - * @param image The image to encode. The image must be - * completely loaded. - * @throws AWTException the aWT exception - * @exception AWTException Will be thrown if the pixel grab fails. This - * can happen if Java runs out of memory. It may also indicate that the image - * contains more than 256 colors. - */ - public GIFEncoder(Image image) throws AWTException - { - width_ = (short) image.getWidth(null); - height_ = (short) image.getHeight(null); - - int values[] = new int[width_ * height_]; - PixelGrabber grabber = new PixelGrabber( - image, 0, 0, width_, height_, values, 0, width_); - - try - { - if (grabber.grabPixels() != true) - { - throw new AWTException("Grabber returned false: " - + grabber.status()); - } - } catch (InterruptedException e) - { - //do nothing - } - - byte r[][] = new byte[width_][height_]; - byte g[][] = new byte[width_][height_]; - byte b[][] = new byte[width_][height_]; - toRGB(width_, height_, values, r, g, b); - ToIndexedColor(r, g, b); - } - - /** - * Construct a GIFEncoder. The constructor will convert the image to - * an indexed color array. This may take some time.

- * - * Each array stores intensity values for the image. In other words, - * r[x][y] refers to the red intensity of the pixel at column x, row - * y.

- * - * @param r An array containing the red intensity values. - * @param g An array containing the green intensity values. - * @param b An array containing the blue intensity values. - * @throws AWTException the aWT exception - * @exception AWTException Will be thrown if the image contains more than - * 256 colors. - */ - public GIFEncoder(byte r[][], byte g[][], byte b[][]) throws AWTException - { - width_ = (short) (r.length); - height_ = (short) (r[0].length); - - ToIndexedColor(r, g, b); - } - - /** - * *******************************************************************. - * - * @param width the width - * @param height the height - * @param values the values - * @throws AWTException the aWT exception - * @author - * David W. Croft - * ******************************************************************* - */ - public GIFEncoder( - short width, - short height, - int[] values) throws AWTException - { - ////////////////////////////////////////////////////////////////////// - this.width_ = width; - this.height_ = height; - byte[][] r = new byte[width][height]; - byte[][] g = new byte[width][height]; - byte[][] b = new byte[width][height]; - toRGB(width, height, values, r, g, b); - ToIndexedColor(r, g, b); - } - - /** - * Writes the image out to a stream in the GIF file format. This will - * be a single GIF87a image, non-interlaced, with no background color. - * This may take some time.

- * - * @param output The stream to output to. This should probably be a - * buffered stream. - * @throws IOException Signals that an I/O exception has occurred. - * @exception IOException Will be thrown if a write operation fails. - */ - public void Write(OutputStream output) throws IOException - { - BitUtils.WriteString(output, "GIF87a"); - - ScreenDescriptor sd = new ScreenDescriptor(width_, height_, - numColors_); - sd.Write(output); - - output.write(colors_, 0, colors_.length); - - ImageDescriptor id = new ImageDescriptor(width_, height_, ','); - id.Write(output); - - byte codesize = BitUtils.BitsNeeded(numColors_); - if (codesize == 1) - { - ++codesize; - } - output.write(codesize); - - LZWCompressor.LZWCompress(output, codesize, pixels_); - output.write(0); - - id = new ImageDescriptor((byte) 0, (byte) 0, ';'); - id.Write(output); - output.flush(); - } - - /** - * To indexed color. - * - * @param r the r - * @param g the g - * @param b the b - * @throws AWTException the aWT exception - */ - void ToIndexedColor(byte r[][], byte g[][], - byte b[][]) throws AWTException - { - pixels_ = new byte[width_ * height_]; - colors_ = new byte[256 * 3]; - int colornum = 0; - for (int x = 0; x < width_; ++x) - { - for (int y = 0; y < height_; ++y) - { - int search; - for (search = 0; search < colornum; ++search) - { - if (colors_[search * 3] == r[x][y] - && colors_[search * 3 + 1] == g[x][y] - && colors_[search * 3 + 2] == b[x][y]) - { - break; - } - } - - if (search > 255) - { - throw new AWTException("Too many colors."); - } - - pixels_[y * width_ + x] = (byte) search; - - if (search == colornum) - { - colors_[search * 3] = r[x][y]; - colors_[search * 3 + 1] = g[x][y]; - colors_[search * 3 + 2] = b[x][y]; - ++colornum; - } - } - } - numColors_ = 1 << BitUtils.BitsNeeded(colornum); - byte copy[] = new byte[numColors_ * 3]; - System.arraycopy(colors_, 0, copy, 0, numColors_ * 3); - colors_ = copy; - } - - /** - * ******************************************************************* - * Loads the values of three 8-bit arrays (red, green, blue) of - * arrays ([ width ] [ height ]) with the masked values from a - * 24-bit color array of length width * height. - * - * @param width the width - * @param height the height - * @param values the values - * @param r the r - * @param g the g - * @param b the b - * @throws AWTException the aWT exception - * @author - * David W. Croft - * ******************************************************************* - */ - public static void toRGB( - short width, - short height, - int[] values, - byte[][] r, - byte[][] g, - byte[][] b) throws AWTException - { - ////////////////////////////////////////////////////////////////////// - if (values.length != width * height) - { - throw new AWTException("values.length != width * height"); - } - if ((r.length != width) - || (g.length != width) - || (b.length != width)) - { - throw new AWTException("r, g, or b array length != width"); - } - if ((r[ 0].length != height) - || (g[ 0].length != height) - || (b[ 0].length != height)) - { - throw new AWTException("r, g, or b array length != height"); - } - int index = 0; - for (int y = 0; y < height; y++) - { - for (int x = 0; x < width; x++) - { - int noalpha = values[index] & 0xFFFFFF; - r[x][y] = (byte) (noalpha >>> 16); - g[x][y] = (byte) (noalpha >>> 8); - b[x][y] = (byte) (noalpha); - index++; - } - } - } -} - -class BitFile { - - OutputStream output_; - byte buffer_[]; - int index_, bitsLeft_; - - public BitFile(OutputStream output) - { - output_ = output; - buffer_ = new byte[256]; - index_ = 0; - bitsLeft_ = 8; - } - - public void Flush() throws IOException - { - int numBytes = index_ + (bitsLeft_ == 8 ? 0 : 1); - if (numBytes > 0) - { - output_.write(numBytes); - output_.write(buffer_, 0, numBytes); - buffer_[0] = 0; - index_ = 0; - bitsLeft_ = 8; - } - } - - public void WriteBits(int bits, int numbits) throws IOException - { - int bitsWritten = 0; - int numBytes = 255; - do - { - if ((index_ == 254 && bitsLeft_ == 0) || index_ > 254) - { - output_.write(numBytes); - output_.write(buffer_, 0, numBytes); - - buffer_[0] = 0; - index_ = 0; - bitsLeft_ = 8; - } - - if (numbits <= bitsLeft_) - { - buffer_[index_] |= (bits & ((1 << numbits) - 1)) - << (8 - bitsLeft_); - bitsWritten += numbits; - bitsLeft_ -= numbits; - numbits = 0; - } else - { - buffer_[index_] |= (bits & ((1 << bitsLeft_) - 1)) - << (8 - bitsLeft_); - bitsWritten += bitsLeft_; - bits >>= bitsLeft_; - numbits -= bitsLeft_; - buffer_[++index_] = 0; - bitsLeft_ = 8; - } - } while (numbits != 0); - } -} - -class LZWStringTable { - - private final static int RES_CODES = 2; - private final static short HASH_FREE = (short) 0xFFFF; - private final static short NEXT_FIRST = (short) 0xFFFF; - private final static int MAXBITS = 12; - private final static int MAXSTR = (1 << MAXBITS); - private final static short HASHSIZE = 9973; - private final static short HASHSTEP = 2039; - byte strChr_[]; - short strNxt_[]; - short strHsh_[]; - short numStrings_; - - public LZWStringTable() - { - strChr_ = new byte[MAXSTR]; - strNxt_ = new short[MAXSTR]; - strHsh_ = new short[HASHSIZE]; - } - - public int AddCharString(short index, byte b) - { - int hshidx; - - if (numStrings_ >= MAXSTR) - { - return 0xFFFF; - } - - hshidx = Hash(index, b); - while (strHsh_[hshidx] != HASH_FREE) - { - hshidx = (hshidx + HASHSTEP) % HASHSIZE; - } - - strHsh_[hshidx] = numStrings_; - strChr_[numStrings_] = b; - strNxt_[numStrings_] = (index != HASH_FREE) ? index : NEXT_FIRST; - - return numStrings_++; - } - - public short FindCharString(short index, byte b) - { - int hshidx, nxtidx; - - if (index == HASH_FREE) - { - return b; - } - - hshidx = Hash(index, b); - while ((nxtidx = strHsh_[hshidx]) != HASH_FREE) - { - if (strNxt_[nxtidx] == index && strChr_[nxtidx] == b) - { - return (short) nxtidx; - } - hshidx = (hshidx + HASHSTEP) % HASHSIZE; - } - - return (short) 0xFFFF; - } - - public void ClearTable(int codesize) - { - numStrings_ = 0; - - for (int q = 0; q < HASHSIZE; q++) - { - strHsh_[q] = HASH_FREE; - } - - int w = (1 << codesize) + RES_CODES; - for (int q = 0; q < w; q++) - { - AddCharString((short) 0xFFFF, (byte) q); - } - } - - static public int Hash(short index, byte lastbyte) - { - return ((int) ((short) (lastbyte << 8) ^ index) & 0xFFFF) % HASHSIZE; - } -} - -class LZWCompressor { - - public static void LZWCompress(OutputStream output, int codesize, - byte toCompress[]) throws IOException - { - byte c; - short index; - int clearcode, endofinfo, numbits, limit, errcode; - short prefix = (short) 0xFFFF; - - BitFile bitFile = new BitFile(output); - LZWStringTable strings = new LZWStringTable(); - - clearcode = 1 << codesize; - endofinfo = clearcode + 1; - - numbits = codesize + 1; - limit = (1 << numbits) - 1; - - strings.ClearTable(codesize); - bitFile.WriteBits(clearcode, numbits); - - for (int loop = 0; loop < toCompress.length; ++loop) - { - c = toCompress[loop]; - if ((index = strings.FindCharString(prefix, c)) != -1) - { - prefix = index; - } else - { - bitFile.WriteBits(prefix, numbits); - if (strings.AddCharString(prefix, c) > limit) - { - if (++numbits > 12) - { - bitFile.WriteBits(clearcode, numbits - 1); - strings.ClearTable(codesize); - numbits = codesize + 1; - } - limit = (1 << numbits) - 1; - } - - prefix = (short) ((short) c & 0xFF); - } - } - - if (prefix != -1) - { - bitFile.WriteBits(prefix, numbits); - } - - bitFile.WriteBits(endofinfo, numbits); - bitFile.Flush(); - } -} - -class ScreenDescriptor { - - public short localScreenWidth_, localScreenHeight_; - private byte byte_; - public byte backgroundColorIndex_, pixelAspectRatio_; - - public ScreenDescriptor(short width, short height, int numColors) - { - localScreenWidth_ = width; - localScreenHeight_ = height; - SetGlobalColorTableSize((byte) (BitUtils.BitsNeeded(numColors) - 1)); - SetGlobalColorTableFlag((byte) 1); - SetSortFlag((byte) 0); - SetColorResolution((byte) 7); - backgroundColorIndex_ = 0; - pixelAspectRatio_ = 0; - } - - public void Write(OutputStream output) throws IOException - { - BitUtils.WriteWord(output, localScreenWidth_); - BitUtils.WriteWord(output, localScreenHeight_); - output.write(byte_); - output.write(backgroundColorIndex_); - output.write(pixelAspectRatio_); - } - - public void SetGlobalColorTableSize(byte num) - { - byte_ |= (num & 7); - } - - public void SetSortFlag(byte num) - { - byte_ |= (num & 1) << 3; - } - - public void SetColorResolution(byte num) - { - byte_ |= (num & 7) << 4; - } - - public void SetGlobalColorTableFlag(byte num) - { - byte_ |= (num & 1) << 7; - } -} - -class ImageDescriptor { - - public byte separator_; - public short leftPosition_, topPosition_, width_, height_; - private byte byte_; - - public ImageDescriptor(short width, short height, char separator) - { - separator_ = (byte) separator; - leftPosition_ = 0; - topPosition_ = 0; - width_ = width; - height_ = height; - SetLocalColorTableSize((byte) 0); - SetReserved((byte) 0); - SetSortFlag((byte) 0); - SetInterlaceFlag((byte) 0); - SetLocalColorTableFlag((byte) 0); - } - - public void Write(OutputStream output) throws IOException - { - output.write(separator_); - BitUtils.WriteWord(output, leftPosition_); - BitUtils.WriteWord(output, topPosition_); - BitUtils.WriteWord(output, width_); - BitUtils.WriteWord(output, height_); - output.write(byte_); - } - - public void SetLocalColorTableSize(byte num) - { - byte_ |= (num & 7); - } - - public void SetReserved(byte num) - { - byte_ |= (num & 3) << 3; - } - - public void SetSortFlag(byte num) - { - byte_ |= (num & 1) << 5; - } - - public void SetInterlaceFlag(byte num) - { - byte_ |= (num & 1) << 6; - } - - public void SetLocalColorTableFlag(byte num) - { - byte_ |= (num & 1) << 7; - } -} - -class BitUtils { - - public static byte BitsNeeded(int n) - { - byte ret = 1; - - if (n-- == 0) - { - return 0; - } - - while ((n >>= 1) != 0) - { - ++ret; - } - - return ret; - } - - public static void WriteWord(OutputStream output, - short w) throws IOException - { - output.write(w & 0xFF); - output.write((w >> 8) & 0xFF); - } - - static void WriteString(OutputStream output, - String string) throws IOException - { - for (int loop = 0; loop < string.length(); ++loop) - { - output.write((byte) (string.charAt(loop))); - } - } -} diff --git a/src/main/java/org/semanticwb/base/util/GenericFilterRule.java b/src/main/java/org/semanticwb/base/util/GenericFilterRule.java deleted file mode 100644 index cfc1a98..0000000 --- a/src/main/java/org/semanticwb/base/util/GenericFilterRule.java +++ /dev/null @@ -1,15 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package org.semanticwb.base.util; - -/** - * - * @author carlos.ramos - */ -public interface GenericFilterRule -{ - public boolean filter(T obj); -} - diff --git a/src/main/java/org/semanticwb/base/util/HashMapCache.java b/src/main/java/org/semanticwb/base/util/HashMapCache.java index 06414ff..d269c6d 100644 --- a/src/main/java/org/semanticwb/base/util/HashMapCache.java +++ b/src/main/java/org/semanticwb/base/util/HashMapCache.java @@ -17,8 +17,7 @@ * de la misma. * * Si usted tiene cualquier duda o comentario sobre SemanticWebBuilder, INFOTEC pone a su disposición la siguiente - * dirección electrónica: - * http://www.semanticwebbuilder.org.mx + * dirección electrónica: http://www.semanticwebbuilder.org.mx */ package org.semanticwb.base.util; @@ -29,126 +28,122 @@ import java.util.concurrent.ConcurrentHashMap; /** - * + * Cached HashMap implementation. Uses a cropped linked list internally to keep cache. * @author javier.solis.g */ -public class HashMapCache implements Map -{ +public class HashMapCache implements Map { private int maxSize; ConcurrentHashMap map; LinkedList linked; - - public HashMapCache(int maxSize) - { - map=new ConcurrentHashMap(); - linked= new LinkedList(); - this.maxSize=maxSize; + + /** + * Constructor. Creates a new {@link HashMapCache} with maxSize elements. + * @param maxSize maximum number of elements in the cached Hash Map. + */ + public HashMapCache(int maxSize) { + map = new ConcurrentHashMap(); + linked = new LinkedList(); + this.maxSize = maxSize; } /** - * @return the maxSize + * Gets the maximum number of elements in the cached Hash Map. + * @return maximum number of elements. */ - public int getMaxSize() - { + public int getMaxSize() { return maxSize; } /** - * @param maxSize the maxSize to set + * Sets the maximum number of elements in the cached Hash Map. + * @param maxSize maximum number of elements. */ - public void setMaxSize(int maxSize) - { + public void setMaxSize(int maxSize) { this.maxSize = maxSize; } @Override - public int size() - { + public int size() { return map.size(); } @Override - public boolean isEmpty() - { + public boolean isEmpty() { return map.isEmpty(); } @Override - public boolean containsKey(Object obj) - { + public boolean containsKey(Object obj) { return map.containsKey(obj); } @Override - public boolean containsValue(Object obj) - { + public boolean containsValue(Object obj) { return map.containsValue(obj); } @Override - public V get(Object o) - { - if(o==null)return null; - return map.get(o); + public V get(Object key) { + if(key == null) { + return null; + } + return map.get(key); } @Override - public V put(K k, V v) - { - if(k==null)return null; - V r=map.put(k, v); - linked.add(k); - if(map.size()>maxSize) - { + public V put(K key, V value) { + if(key == null) { + return null; + } + + V r = map.put(key, value); + linked.add(key); + + if(map.size() > maxSize) { crop(); - } + } + return r; } - - private synchronized void crop() - { - while(!linked.isEmpty() && map.size()>maxSize) - { - Object obj=linked.poll(); + + /** + * Crops elements from cache. + */ + private synchronized void crop() { + while(!linked.isEmpty() && map.size() > maxSize) { + Object obj = linked.poll(); map.remove(obj); } } @Override - public void putAll(Map map) - { + public void putAll(Map map) { this.map.putAll(map); } @Override - public void clear() - { + public void clear() { map.clear(); linked.clear(); } @Override - public Set keySet() - { + public Set keySet() { return map.keySet(); } @Override - public Collection values() - { + public Collection values() { return map.values(); } @Override - public Set> entrySet() - { + public Set> entrySet() { return map.entrySet(); } @Override - public V remove(Object o) - { - return map.remove(o); + public V remove(Object key) { + return map.remove(key); } - } diff --git a/src/main/java/org/semanticwb/base/util/JarFile.java b/src/main/java/org/semanticwb/base/util/JarFile.java new file mode 100644 index 0000000..906a574 --- /dev/null +++ b/src/main/java/org/semanticwb/base/util/JarFile.java @@ -0,0 +1,267 @@ +/* + * SemanticWebBuilder es una plataforma para el desarrollo de portales y aplicaciones de integración, + * colaboración y conocimiento, que gracias al uso de tecnología semántica puede generar contextos de + * información alrededor de algún tema de interés o bien integrar información y aplicaciones de diferentes + * fuentes, donde a la información se le asigna un significado, de forma que pueda ser interpretada y + * procesada por personas y/o sistemas, es una creación original del Fondo de Información y Documentación + * para la Industria INFOTEC, cuyo registro se encuentra actualmente en trámite. + * + * INFOTEC pone a su disposición la herramienta SemanticWebBuilder a través de su licenciamiento abierto al público (‘open source’), + * en virtud del cual, usted podrá usarlo en las mismas condiciones con que INFOTEC lo ha diseñado y puesto a su disposición; + * aprender de él; distribuirlo a terceros; acceder a su código fuente y modificarlo, y combinarlo o enlazarlo con otro software, + * todo ello de conformidad con los términos y condiciones de la LICENCIA ABIERTA AL PÚBLICO que otorga INFOTEC para la utilización + * del SemanticWebBuilder 4.0. + * + * INFOTEC no otorga garantía sobre SemanticWebBuilder, de ninguna especie y naturaleza, ni implícita ni explícita, + * siendo usted completamente responsable de la utilización que le dé y asumiendo la totalidad de los riesgos que puedan derivar + * de la misma. + * + * Si usted tiene cualquier duda o comentario sobre SemanticWebBuilder, INFOTEC pone a su disposición la siguiente + * dirección electrónica: + * http://www.semanticwebbuilder.org + */ +package org.semanticwb.base.util; + +import org.semanticwb.Logger; +import org.semanticwb.SWBUtils; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +/** + * Wrapper class for accessing JAR Files. + */ +public class JarFile { + private static final Logger LOG = SWBUtils.getLogger(JarFile.class); + + /** + * The path. + */ + private String path; + + /** + * The exists. + */ + private boolean exists; + + /** + * The is dir. + */ + private boolean isDir; + + /** + * The length. + */ + private long length; + + /** + * The last modified. + */ + private long lastModified; + + private long stamp = System.currentTimeMillis(); + + private boolean replaced = false; + + /** + * The f. + */ + private File f = null; + + /** + * The zip path. + */ + private byte[] cache = null; + + private ZipEntry ze = null; + + /** + * Instantiates a new jar file. + * @param path the path + */ + public JarFile(String path) { + this.setPath(path); + } + + /** + * Instantiates a new jar file. + * + * @param f the f + * @param zf the zip path + */ + public JarFile(ZipEntry f, ZipFile zf) { + //this.zf=zf; + this.ze = f; + this.path = "/" + f.getName(); + exists = true; + if (exists) { + isDir = f.isDirectory(); + if (!isDir) { + length = f.getSize(); + lastModified = f.getTime(); + } + loadCache(zf); + } else { + + } + } + + /** + * Load cache. + */ + private void loadCache() { + loadCache(null); + } + + /** + * Load cache. + */ + private void loadCache(ZipFile zf) { + try { + InputStream in = getInputStream(zf); + ByteArrayOutputStream out = new ByteArrayOutputStream((int) length); + if (null != in) { + SWBUtils.IO.copyStream(in, out); + cache = out.toByteArray(); + } + } catch (Exception e) { + LOG.error(e); + } + } + + /** + * Gets the input stream. + * + * @return the input stream + */ + public InputStream getInputStream() { + return getInputStream(null); + } + + /** + * Gets the input stream. + * + * @return the input stream + */ + public InputStream getInputStream(ZipFile zf) { + try { + if (ze != null) { + if (zf != null) + return zf.getInputStream(ze); + else + return getClass().getResourceAsStream(path); + } else { + return new FileInputStream(f); + } + } catch (Exception e) { + LOG.error(e); + return null; + } + } + + + /** + * Gets the cache. + * + * @return the cache + */ + public byte[] getCache() { + return cache; + } + + /** + * Exists. + * + * @return true, if successful + */ + public boolean exists() { + return exists; + } + + /** + * Checks if is directory. + * + * @return true, if is directory + */ + public boolean isDirectory() { + return isDir; + } + + /** + * Gets the path. + * + * @return the path + */ + public String getPath() { + return path; + } + + /** + * Sets the path. + * + * @param p the new path + */ + public void setPath(String p) { + this.path = p; + f = new File(SWBUtils.getApplicationPath() + path); + exists = f.exists(); + if (exists) { + isDir = f.isDirectory(); + if (!isDir) { + length = f.length(); + lastModified = f.lastModified(); + } + } else { + + } + } + + /** + * Length. + * + * @return the long + */ + public long length() { + return length; + } + + /** + * Last modified. + * + * @return the long + */ + public long lastModified() { + return lastModified; + } + + /** + * Checks for cache. + * + * @return true, if successful + */ + public boolean hasCache() { + return cache != null; + } + + public boolean isExpired() { + return System.currentTimeMillis() > (stamp + 60000L); + } + + public void touch() { + stamp = System.currentTimeMillis(); + } + + public boolean isReplaced() { + return replaced; + } + + public void setReplaced(boolean replaced) { + this.replaced = replaced; + } + + +} \ No newline at end of file diff --git a/src/main/java/org/semanticwb/base/util/LexiSortable.java b/src/main/java/org/semanticwb/base/util/LexiSortable.java index da5e26b..5006f6e 100644 --- a/src/main/java/org/semanticwb/base/util/LexiSortable.java +++ b/src/main/java/org/semanticwb/base/util/LexiSortable.java @@ -17,37 +17,38 @@ * de la misma. * * Si usted tiene cualquier duda o comentario sobre SemanticWebBuilder, INFOTEC pone a su disposición la siguiente - * dirección electrónica: - * http://www.semanticwebbuilder.org.mx + * dirección electrónica: http://www.semanticwebbuilder.org.mx */ package org.semanticwb.base.util; - +//TODO: Check usage rights on this code. See https://gist.github.com/jfager/490768 public class LexiSortable { // Lookup table to find hex digits from bytes. - private final static char[] HEX_DIGITS = { - '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' + private static final char[] HEX_DIGITS = { + '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; // Lookup table to find bytes from hex digits. private static final byte[] BYTE_LOOKUP = new byte['F' + 1]; + // 16 chars to represent a long in hex, plus a type token. + private static final int LEXI_STRING_LEN = 17; + // All zeroes except the sign bit. + private static final long SIGN_MASK = 0x8000000000000000L; + static { for (int i = 0; i < HEX_DIGITS.length; i++) { BYTE_LOOKUP[HEX_DIGITS[i]] = (byte) i; } } - // 16 chars to represent a long in hex, plus a type token. - private static final int LEXI_STRING_LEN = 17; - - // Utility method converts a long to a hex string and prepends + // Utility method converts a long to a hex string and prepends // a type token private static String toHexString(char type, long i) { final char[] buf = new char[LEXI_STRING_LEN]; int charPos = LEXI_STRING_LEN; do { - // read bottom 4 bits to lookup hex char for + // read bottom 4 bits to lookup hex char for // current position buf[--charPos] = HEX_DIGITS[(int) (i & 0xf)]; // shift so we can do it again for the next. @@ -57,31 +58,28 @@ private static String toHexString(char type, long i) { return new String(buf); } - // Utility method converts a hex string to a long. - // It ignores the leading type token; verification + // Utility method converts a hex string to a long. + // It ignores the leading type token; verification // needs to be handled by the calling function. private static long fromHexString(final String s) { final byte[] bytes = s.getBytes(); long out = 0L; for (int i = 1; i < LEXI_STRING_LEN; i++) { - // first shift is wasted, but after that, - // move previously xor'd bits out of the - // way so they don't get clobbered by + // first shift is wasted, but after that, + // move previously xor'd bits out of the + // way so they don't get clobbered by // subsequent chars. out <<= 4; - // Note that we shifted 4 bits b/c we're - // using hex, but we have to XOR a byte - // at a time. This is fine, b/c the high - // bits of the bytes stored in the lookup + // Note that we shifted 4 bits b/c we're + // using hex, but we have to XOR a byte + // at a time. This is fine, b/c the high + // bits of the bytes stored in the lookup // table are zeroed out. out ^= BYTE_LOOKUP[bytes[i]]; } return out; } - // All zeroes except the sign bit. - private static final long SIGN_MASK = 0x8000000000000000L; - /** * Returns a string s for long l such that for any long l' * where l < l', s.compareTo(toLexiSortable(l')) < 0. @@ -115,7 +113,7 @@ public static long longFromLexiSortable(final String s) { // long back. return tmp ^ SIGN_MASK; } - + public static String toLexiSortable(final double d) { long tmp = Double.doubleToRawLongBits(d); return toHexString('d', (tmp < 0) ? ~tmp : (tmp ^ SIGN_MASK)); @@ -129,5 +127,5 @@ public static double doubleFromLexiSortable(final String s) { long tmp = fromHexString(s); tmp = (tmp < 0) ? (tmp ^ SIGN_MASK) : ~tmp; return Double.longBitsToDouble(tmp); - } + } } diff --git a/src/main/java/org/semanticwb/base/util/SFBase64.java b/src/main/java/org/semanticwb/base/util/SFBase64.java index 64f30e2..1039a3f 100644 --- a/src/main/java/org/semanticwb/base/util/SFBase64.java +++ b/src/main/java/org/semanticwb/base/util/SFBase64.java @@ -22,6 +22,9 @@ */ package org.semanticwb.base.util; +import org.semanticwb.Logger; +import org.semanticwb.SWBUtils; + import java.io.IOException; import java.util.Base64; @@ -52,6 +55,7 @@ * @version 1.3.4 */ public class SFBase64 { + public static final Logger LOG = SWBUtils.getLogger(SFBase64.class); /** Specify encoding (value is true). */ public static final boolean ENCODE = true; @@ -64,8 +68,7 @@ public class SFBase64 { /** The new line character (\n) as a byte. */ private static final byte NEW_LINE = (byte) '\n'; /** The 64 valid Base64 values. */ - private static final byte[] ALPHABET = - { + private static final byte[] ALPHABET = { (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', @@ -77,12 +80,12 @@ public class SFBase64 { (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/' }; + /** * Translates a Base64 value to either its 6-bit reconstruction value * or a negative number indicating some other meaning. **/ - private static final byte[] DECODABET = - { + private static final byte[] DECODABET = { -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 -5, -5, // Whitespace: Tab and Linefeed -9, -9, // Decimal 11 - 12 @@ -104,217 +107,18 @@ public class SFBase64 { 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' -9, -9, -9, -9 // Decimal 123 - 126 - /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ }; - + /** The Constant WHITE_SPACE_ENC. */ private static final byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding - + /** The Constant EQUALS_SIGN_ENC. */ private static final byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding /** Defeats instantiation. */ - private SFBase64() - { + private SFBase64() { } - /** - * Testing. Feel free--in fact I encourage you--to throw out - * this entire "main" method when you actually deploy this code. - * - * @param args the arguments - */ - public static void main(String[] args) - { - try - { - // Test encoding/decoding byte arrays - { - byte[] bytes1 = - { - (byte) 2, (byte) 2, (byte) 3, (byte) 0, (byte) 9 - }; // My zip code - - byte[] dbytes = decode(encodeBytes(bytes1)); - } // end testing byte arrays - // Test Input Stream - { - // Read GIF stored in base64 form. - java.io.FileInputStream fis = new java.io.FileInputStream("test.gif.b64"); - SFBase64.InputStream b64is = new SFBase64.InputStream(fis, DECODE); - - byte[] bytes = new byte[0]; - int b = -1; - while ((b = b64is.read()) >= 0) - { - byte[] temp = new byte[bytes.length + 1]; - System.arraycopy(bytes, 0, temp, 0, bytes.length); - temp[bytes.length] = (byte) b; - bytes = temp; - } // end while: terribly inefficient way to read data - b64is.close(); - javax.swing.ImageIcon iicon = new javax.swing.ImageIcon(bytes); - javax.swing.JLabel jlabel = new javax.swing.JLabel("Read from test.gif.b64", iicon, 0); - javax.swing.JFrame jframe = new javax.swing.JFrame(); - jframe.getContentPane().add(jlabel); - jframe.pack(); - jframe.show(); - - // Write raw bytes to file - java.io.FileOutputStream fos = new java.io.FileOutputStream("test.gif_out"); - fos.write(bytes); - fos.close(); - - // Read raw bytes and encode - fis = new java.io.FileInputStream("test.gif_out"); - b64is = new SFBase64.InputStream(fis, ENCODE); - byte[] ebytes = new byte[0]; - b = -1; - while ((b = b64is.read()) >= 0) - { - byte[] temp = new byte[ebytes.length + 1]; - System.arraycopy(ebytes, 0, temp, 0, ebytes.length); - temp[ebytes.length] = (byte) b; - ebytes = temp; - } // end while: terribly inefficient way to read data - b64is.close(); - String s = new String(ebytes); - javax.swing.JTextArea jta = new javax.swing.JTextArea(s); - javax.swing.JScrollPane jsp = new javax.swing.JScrollPane(jta); - jframe = new javax.swing.JFrame(); - jframe.setTitle("Read from test.gif_out"); - jframe.getContentPane().add(jsp); - jframe.pack(); - jframe.show(); - - // Write encoded bytes to file - fos = new java.io.FileOutputStream("test.gif.b64_out"); - fos.write(ebytes); - - // Read GIF stored in base64 form. - fis = new java.io.FileInputStream("test.gif.b64_out"); - b64is = new SFBase64.InputStream(fis, DECODE); - byte[] edbytes = new byte[0]; - b = -1; - while ((b = b64is.read()) >= 0) - { - byte[] temp = new byte[edbytes.length + 1]; - System.arraycopy(edbytes, 0, temp, 0, edbytes.length); - temp[edbytes.length] = (byte) b; - edbytes = temp; - } // end while: terribly inefficient way to read data - b64is.close(); - iicon = new javax.swing.ImageIcon(edbytes); - jlabel = new javax.swing.JLabel("Read from test.gif.b64_out", iicon, 0); - jframe = new javax.swing.JFrame(); - jframe.getContentPane().add(jlabel); - jframe.pack(); - jframe.show(); - } // end: Test Input Stream - // Test Output Stream - { - // Read raw bytes - java.io.FileInputStream fis = new java.io.FileInputStream("test.gif_out"); - byte[] rbytes = new byte[0]; - int b = -1; - while ((b = fis.read()) >= 0) - { - byte[] temp = new byte[rbytes.length + 1]; - System.arraycopy(rbytes, 0, temp, 0, rbytes.length); - temp[rbytes.length] = (byte) b; - rbytes = temp; - } // end while: terribly inefficient way to read data - fis.close(); - - // Write raw bytes to encoded file - java.io.FileOutputStream fos = new java.io.FileOutputStream("test.gif.b64_out2"); - SFBase64.OutputStream b64os = new SFBase64.OutputStream(fos, ENCODE); - b64os.write(rbytes); - b64os.close(); - - - // Read raw bytes that are actually encoded (but we'll ignore that) - fis = new java.io.FileInputStream("test.gif.b64_out2"); - byte[] rebytes = new byte[0]; - b = -1; - while ((b = fis.read()) >= 0) - { - byte[] temp = new byte[rebytes.length + 1]; - System.arraycopy(rebytes, 0, temp, 0, rebytes.length); - temp[rebytes.length] = (byte) b; - rebytes = temp; - } // end while: terribly inefficient way to read data - fis.close(); - String s = new String(rebytes); - javax.swing.JTextArea jta = new javax.swing.JTextArea(s); - javax.swing.JScrollPane jsp = new javax.swing.JScrollPane(jta); - javax.swing.JFrame jframe = new javax.swing.JFrame(); - jframe.setTitle("Read from test.gif.b64_out2"); - jframe.getContentPane().add(jsp); - jframe.pack(); - jframe.show(); - - // Write encoded bytes to decoded raw file - fos = new java.io.FileOutputStream("test.gif_out2"); - b64os = new SFBase64.OutputStream(fos, DECODE); - b64os.write(rebytes); - b64os.close(); - javax.swing.ImageIcon iicon = new javax.swing.ImageIcon("test.gif_out2"); - javax.swing.JLabel jlabel = new javax.swing.JLabel("Read from test.gif_out2", iicon, 0); - jframe = new javax.swing.JFrame(); - jframe.getContentPane().add(jlabel); - jframe.pack(); - jframe.show(); - - } // end: Test Output Stream - // Test wagner's files - { - //TODO: Revisar estas rutas absolutas de Windows - java.io.FileInputStream fis = new java.io.FileInputStream("D:\\temp\\testencoding.txt"); - SFBase64.InputStream b64is = new SFBase64.InputStream(fis, DECODE); - java.io.FileOutputStream fos = new java.io.FileOutputStream("D:\\temp\\file.zip"); - int b; - while ((b = b64is.read()) >= 0) - { - fos.write(b); - } - fos.close(); - b64is.close(); - - } // end test wagner's file - - } // end try - catch (Exception e) - { - e.printStackTrace(); - } - } // end main - - - /* ******** E N C O D I N G M E T H O D S ******** */ - /** - * Encodes the first three bytes of array threeBytes - * and returns a four-byte array in Base64 notation. - * - * @param threeBytes the array to convert - * @param numSigBytes the num sig bytes - * @return four byte array in Base64 notation. - * @since 1.3 - */ -// private static byte[] encode3to4(byte[] threeBytes) -// { -// return encode3to4(threeBytes, 3); -// } // end encodeToBytes - /** * Encodes up to the first three bytes of array threeBytes * and returns a four-byte array in Base64 notation. @@ -328,8 +132,7 @@ public static void main(String[] args) * @return four byte array in Base64 notation. * @since 1.3 */ - private static byte[] encode3to4(byte[] threeBytes, int numSigBytes) - { + private static byte[] encode3to4(byte[] threeBytes, int numSigBytes) { byte[] dest = new byte[4]; encode3to4(threeBytes, 0, numSigBytes, dest, 0); return dest; @@ -347,7 +150,7 @@ private static byte[] encode3to4(byte[] threeBytes, int numSigBytes) * the destination array. * The actual number of significant bytes in your array is * given by numSigBytes. - * + * * @param source the array to convert * @param srcOffset the index where conversion begins * @param numSigBytes the number of significant bytes in your array @@ -356,10 +159,7 @@ private static byte[] encode3to4(byte[] threeBytes, int numSigBytes) * @return the array * @since 1.3 */ - private static byte[] encode3to4( - byte[] source, int srcOffset, int numSigBytes, - byte[] destination, int destOffset) - { + private static byte[] encode3to4(byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset) { // 1 2 3 // 01234567890123456789012345678901 Bit position // --------000000001111111122222222 Array position from threeBytes @@ -375,8 +175,7 @@ private static byte[] encode3to4( | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0) | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0); - switch (numSigBytes) - { + switch (numSigBytes) { case 3: destination[destOffset] = ALPHABET[(inBuff >>> 18)]; destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; @@ -413,8 +212,7 @@ private static byte[] encode3to4( * @return The Base64-encoded object * @since 1.4 */ - public static String encodeObject(java.io.Serializable serializableObject) - { + public static String encodeObject(java.io.Serializable serializableObject) { return encodeObject(serializableObject, true); } // end encodeObject @@ -429,44 +227,34 @@ public static String encodeObject(java.io.Serializable serializableObject) * @return The Base64-encoded object * @since 1.4 */ - public static String encodeObject(java.io.Serializable serializableObject, boolean breakLines) - { + public static String encodeObject(java.io.Serializable serializableObject, boolean breakLines) { java.io.ByteArrayOutputStream baos = null; java.io.OutputStream b64os = null; java.io.ObjectOutputStream oos = null; - try - { + try { baos = new java.io.ByteArrayOutputStream(); b64os = new SFBase64.OutputStream(baos, SFBase64.ENCODE, breakLines); oos = new java.io.ObjectOutputStream(b64os); oos.writeObject(serializableObject); - } // end try - catch (java.io.IOException e) - { + } catch (java.io.IOException e) { e.printStackTrace(); return null; - } // end catch - finally - { - try - { + } finally { + try { oos.close(); - } catch (Exception e) - { // Abandonamos calladamente el stream + } catch (Exception e) { // Abandonamos calladamente el stream } - try - { + + try { b64os.close(); - } catch (Exception e) - { // Abandonamos calladamente el stream + } catch (Exception e) { // Abandonamos calladamente el stream } - try - { + + try { baos.close(); - } catch (Exception e) - { // Abandonamos calladamente el stream + } catch (Exception e) { // Abandonamos calladamente el stream } } // end finally @@ -477,13 +265,12 @@ public static String encodeObject(java.io.Serializable serializableObject, boole * Encodes a byte array into Base64 notation. * Equivalen to calling * encodeBytes( source, 0, source.length ) - * + * * @param source The data to convert * @return the string * @since 1.4 */ - public static String encodeBytes(byte[] source) - { + public static String encodeBytes(byte[] source) { return encodeBytes(source, true); } // end encodeBytes @@ -491,34 +278,32 @@ public static String encodeBytes(byte[] source) * Encodes a byte array into Base64 notation. * Equivalen to calling * encodeBytes( source, 0, source.length ) - * + * * @param source The data to convert * @param breakLines Break lines at 80 characters or less. * @return the string * @since 1.4 */ - public static String encodeBytes(byte[] source, boolean breakLines) - { + public static String encodeBytes(byte[] source, boolean breakLines) { return encodeBytes(source, 0, source.length, breakLines); } // end encodeBytes /** * Encodes a byte array into Base64 notation. - * + * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @return the string * @since 1.4 */ - public static String encodeBytes(byte[] source, int off, int len) - { + public static String encodeBytes(byte[] source, int off, int len) { return encodeBytes(source, off, len, true); } // end encodeBytes /** * Encodes a byte array into Base64 notation. - * + * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert @@ -526,8 +311,7 @@ public static String encodeBytes(byte[] source, int off, int len) * @return the string * @since 1.4 */ - public static String encodeBytes(byte[] source, int off, int len, boolean breakLines) - { + public static String encodeBytes(byte[] source, int off, int len, boolean breakLines) { int len43 = len * 4 / 3; byte[] outBuff = new byte[(len43) // Main 4:3 + ((len % 3) > 0 ? 4 : 0) // Account for padding @@ -536,21 +320,18 @@ public static String encodeBytes(byte[] source, int off, int len, boolean breakL int e = 0; int len2 = len - 2; int lineLength = 0; - for (; d < len2; d += 3, e += 4) - { + for (; d < len2; d += 3, e += 4) { encode3to4(source, d + off, 3, outBuff, e); lineLength += 4; - if (breakLines && lineLength == MAX_LINE_LENGTH) - { + if (breakLines && lineLength == MAX_LINE_LENGTH) { outBuff[e + 4] = NEW_LINE; e++; lineLength = 0; } // end if: end of line } // en dfor: each piece of array - if (d < len) - { + if (d < len) { encode3to4(source, d + off, len - d, outBuff, e); e += 4; } // end if: some padding needed @@ -566,8 +347,7 @@ public static String encodeBytes(byte[] source, int off, int len, boolean breakL * @return the encoded string * @since 1.3 */ - public static String encodeString(String s) - { + public static String encodeString(String s) { return encodeString(s, true); } // end encodeString @@ -580,8 +360,7 @@ public static String encodeString(String s) * @return the encoded string * @since 1.3 */ - public static String encodeString(String s, boolean breakLines) - { + public static String encodeString(String s, boolean breakLines) { return encodeBytes(s.getBytes(), breakLines); } // end encodeString @@ -595,14 +374,12 @@ public static String encodeString(String s, boolean breakLines) * @return array with decoded values * @since 1.3 */ - private static byte[] decode4to3(byte[] fourBytes) - { + private static byte[] decode4to3(byte[] fourBytes) { byte[] outBuff1 = new byte[3]; int count = decode4to3(fourBytes, 0, outBuff1, 0); byte[] outBuff2 = new byte[count]; - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { outBuff2[i] = outBuff1[i]; } @@ -631,11 +408,9 @@ private static byte[] decode4to3(byte[] fourBytes) * @return the number of decoded bytes converted * @since 1.3 */ - private static int decode4to3(byte[] source, int srcOffset, byte[] destination, int destOffset) - { + private static int decode4to3(byte[] source, int srcOffset, byte[] destination, int destOffset) { // Example: Dk== - if (source[srcOffset + 2] == EQUALS_SIGN) - { + if (source[srcOffset + 2] == EQUALS_SIGN) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); @@ -645,8 +420,7 @@ private static int decode4to3(byte[] source, int srcOffset, byte[] destination, destination[destOffset] = (byte) (outBuff >>> 16); return 1; } // Example: DkL= - else if (source[srcOffset + 3] == EQUALS_SIGN) - { + else if (source[srcOffset + 3] == EQUALS_SIGN) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) @@ -659,10 +433,8 @@ else if (source[srcOffset + 3] == EQUALS_SIGN) destination[destOffset + 1] = (byte) (outBuff >>> 8); return 2; } // Example: DkLE - else - { - try - { + else { + try { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) @@ -679,8 +451,7 @@ else if (source[srcOffset + 3] == EQUALS_SIGN) destination[destOffset + 2] = (byte) (outBuff); return 3; - } catch (Exception e) - { + } catch (Exception e) { System.out.println("" + source[srcOffset] + ": " + (DECODABET[source[srcOffset]])); System.out.println("" + source[srcOffset + 1] + ": " + (DECODABET[source[srcOffset + 1]])); System.out.println("" + source[srcOffset + 2] + ": " + (DECODABET[source[srcOffset + 2]])); @@ -697,10 +468,8 @@ else if (source[srcOffset + 3] == EQUALS_SIGN) * @return the decoded data * @since 1.4 */ - public static byte[] decode(String s) - { + public static byte[] decode(String s) { byte[] bytes = s.getBytes(); - //System.out.println("\n\n\n-->\n" + bytes.length + "---" +s.length() +"\n\n\n"); return decode(bytes, 0, bytes.length); } // end decode @@ -714,8 +483,7 @@ public static byte[] decode(String s) * @return The data as a string * @since 1.4 */ - public static String decodeToString(String s) - { + public static String decodeToString(String s) { return new String(decode(s)); } // end decodeToString @@ -727,43 +495,32 @@ public static String decodeToString(String s) * @return The decoded and deserialized object * @since 1.4 */ - public static Object decodeToObject(String encodedObject) - { + public static Object decodeToObject(String encodedObject) { byte[] objBytes = decode(encodedObject); java.io.ByteArrayInputStream bais = null; java.io.ObjectInputStream ois = null; - try - { + try { bais = new java.io.ByteArrayInputStream(objBytes); ois = new java.io.ObjectInputStream(bais); return ois.readObject(); - } // end try - catch (java.io.IOException e) - { + } catch (java.io.IOException e) { e.printStackTrace(); return null; - } // end catch - catch (java.lang.ClassNotFoundException e) - { + } catch (java.lang.ClassNotFoundException e) { e.printStackTrace(); return null; - } // end catch - finally - { - try - { + } finally { + try { bais.close(); - } catch (Exception e) - { // Abandonamos calladamente el stream + } catch (Exception e) { // Abandonamos calladamente el stream } - try - { + + try { ois.close(); - } catch (Exception e) - { // Abandonamos calladamente el stream + } catch (Exception e) { // Abandonamos calladamente el stream } } // end finally } // end decodeObject @@ -778,8 +535,7 @@ public static Object decodeToObject(String encodedObject) * @return decoded data * @since 1.3 */ - public static byte[] decode(byte[] source, int off, int len) - { + public static byte[] decode(byte[] source, int off, int len) { int len34 = len * 3 / 4; byte[] outBuff = new byte[len34]; // Upper limit on size of output int outBuffPosn = 0; @@ -789,34 +545,27 @@ public static byte[] decode(byte[] source, int off, int len) int i = 0; byte sbiCrop = 0; byte sbiDecode = 0; - for (i = 0; i < len; i++) - { + for (i = 0; i < len; i++) { sbiCrop = (byte) (source[i] & 0x7f); // Only the low seven bits sbiDecode = DECODABET[sbiCrop]; if (sbiDecode >= WHITE_SPACE_ENC) // White space, Equals sign or better { - if (sbiDecode >= EQUALS_SIGN_ENC) - { + if (sbiDecode >= EQUALS_SIGN_ENC) { b4[b4Posn++] = sbiCrop; - if (b4Posn > 3) - { + if (b4Posn > 3) { outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn); b4Posn = 0; // If that was the equals sign, break out of 'for' loop - if (sbiCrop == EQUALS_SIGN) - { + if (sbiCrop == EQUALS_SIGN) { break; } } // end if: quartet built - } // end if: equals sign or better - } // end if: white space, equals sign or better - else - { - System.err.println("Bad Base64 input character at " + i + ": " + source[i] + "(decimal)"); + else { + LOG.error("Bad Base64 input character at " + i + ": " + source[i] + "(decimal)"); return null; } // end else: } // each input character @@ -828,8 +577,8 @@ public static byte[] decode(byte[] source, int off, int len) /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */ /** - * A {@link Base64#InputStream} will read data from another. - * + * A {@link org.semanticwb.base.util.SFBase64.InputStream} will read data from another. + * * {@link java.io.InputStream}, given in the constructor, * and encode/decode to/from Base64 notation on the fly. * @see Base64 @@ -837,41 +586,39 @@ public static byte[] decode(byte[] source, int off, int len) * @since 1.3 */ public static class InputStream extends java.io.FilterInputStream { - /** The encode. */ private boolean encode; // Encoding or decoding - + /** The position. */ private int position; // Current position in the buffer - + /** The buffer. */ private byte[] buffer; // Small buffer holding converted data - + /** The buffer length. */ private int bufferLength; // Length of buffer (3 or 4) - + /** The num sig bytes. */ private int numSigBytes; // Number of meaningful bytes in the buffer - + /** The line length. */ private int lineLength; - + /** The break lines. */ private boolean breakLines; // Break lines at less than 80 characters /** - * Constructs a {@link Base64#InputStream} in DECODE mode. + * Constructs a {@link org.semanticwb.base.util.SFBase64.InputStream} in DECODE mode. * * @param in the {@link java.io.InputStream} from which to read data. * @since 1.3 */ - public InputStream(java.io.InputStream in) - { + public InputStream(java.io.InputStream in) { this(in, SFBase64.DECODE); } // end constructor /** - * Constructs a {@link Base64#InputStream} in + * Constructs a {@link org.semanticwb.base.util.SFBase64.InputStream} in * either ENCODE or DECODE mode. * * @param in the {@link java.io.InputStream} from which to read data. @@ -880,13 +627,12 @@ public InputStream(java.io.InputStream in) * @see Base64#DECODE * @since 1.3 */ - public InputStream(java.io.InputStream in, boolean encode) - { + public InputStream(java.io.InputStream in, boolean encode) { this(in, encode, true); } // end constructor /** - * Constructs a {@link Base64#InputStream} in + * Constructs a {@link org.semanticwb.base.util.SFBase64.InputStream} in * either ENCODE or DECODE mode. * * @param in the {@link java.io.InputStream} from which to read data. @@ -896,8 +642,7 @@ public InputStream(java.io.InputStream in, boolean encode) * @see Base64#DECODE * @since 1.3 */ - public InputStream(java.io.InputStream in, boolean encode, boolean breakLines) - { + public InputStream(java.io.InputStream in, boolean encode, boolean breakLines) { super(in); this.breakLines = breakLines; this.encode = encode; @@ -910,119 +655,92 @@ public InputStream(java.io.InputStream in, boolean encode, boolean breakLines) /** * Reads enough of the input stream to convert * to/from Base64 and returns the next byte. - * + * * @return next byte * @throws IOException Signals that an I/O exception has occurred. * @since 1.3 */ - public int read() throws java.io.IOException - { + public int read() throws java.io.IOException { // Do we need to get data? - if (position < 0) - { - if (encode) - { + if (position < 0) { + if (encode) { byte[] b3 = new byte[3]; int numBinaryBytes = 0; - for (int i = 0; i < 3; i++) - { - try - { + for (int i = 0; i < 3; i++) { + try { int b = in.read(); // If end of stream, b is -1. - if (b >= 0) - { + if (b >= 0) { b3[i] = (byte) b; numBinaryBytes++; } // end if: not end of stream - } // end try: read - catch (java.io.IOException e) - { + } catch (java.io.IOException e) { // Only a problem if we got no data at all. - if (i == 0) - { + if (i == 0) { throw e; } - } // end catch } // end for: each needed input byte - if (numBinaryBytes > 0) - { + if (numBinaryBytes > 0) { encode3to4(b3, 0, numBinaryBytes, buffer, 0); position = 0; numSigBytes = 4; - } // end if: got data - else - { + } else { return -1; } // end else } // end if: encoding // Else decoding - else - { + else { byte[] b4 = new byte[4]; int i = 0; - for (i = 0; i < 4; i++) - { + for (i = 0; i < 4; i++) { // Read four "meaningful" bytes: int b = 0; - do - { + do { b = in.read(); } while (b >= 0 && DECODABET[b & 0x7f] <= WHITE_SPACE_ENC); - if (b < 0) - { + if (b < 0) { break; // Reads a -1 if end of stream } b4[i] = (byte) b; } // end for: each needed input byte - if (i == 4) - { + if (i == 4) { numSigBytes = decode4to3(b4, 0, buffer, 0); position = 0; } // end if: got four characters - else if (i == 0) - { + else if (i == 0) { return -1; } // end else if: also padded correctly - else - { + else { // Must have broken out from above. throw new java.io.IOException("Improperly padded Base64 input."); } // end - } // end else: decode } // end else: get data // Got data? - if (position >= 0) - { + if (position >= 0) { // End of relevant data? - if (/*!encode &&*/position >= numSigBytes) - { + if (/*!encode &&*/position >= numSigBytes) { return -1; } - if (encode && breakLines && lineLength >= MAX_LINE_LENGTH) - { + if (encode && breakLines && lineLength >= MAX_LINE_LENGTH) { lineLength = 0; return '\n'; - } // end if - else - { + } else { lineLength++; // This isn't important when decoding // but throwing an extra "if" seems // just as wasteful. int b = buffer[position++]; - if (position >= bufferLength) - { + if (position >= bufferLength) { position = -1; } @@ -1031,8 +749,7 @@ else if (i == 0) } // end else } // end if: position >= 0 // Else error - else - { + else { // When JDK1.4 is more accepted, use an assertion here. throw new java.io.IOException("Error in Base64 code reading stream."); } // end else @@ -1043,7 +760,7 @@ else if (i == 0) * is reached or len bytes are read. * Returns number of bytes read into array or -1 if * end of stream is encountered. - * + * * @param dest array to hold values * @param off offset for array * @param len max number of bytes to read into array @@ -1051,25 +768,17 @@ else if (i == 0) * @throws IOException Signals that an I/O exception has occurred. * @since 1.3 */ - public int read(byte[] dest, int off, int len) throws java.io.IOException - { + public int read(byte[] dest, int off, int len) throws java.io.IOException { int i; int b; - for (i = 0; i < len; i++) - { + for (i = 0; i < len; i++) { b = read(); - //if( b < 0 && i == 0 ) - // return -1; - - if (b >= 0) - { + if (b >= 0) { dest[off + i] = (byte) b; - } else if (i == 0) - { + } else if (i == 0) { return -1; - } else - { + } else { break; // Out of 'for' loop } } // end for: each byte read @@ -1079,8 +788,8 @@ public int read(byte[] dest, int off, int len) throws java.io.IOException /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */ /** - * A {@link Base64#OutputStream} will write data to another. - * + * A {@link org.semanticwb.base.util.SFBase64.OutputStream} will write data to another. + * * {@link java.io.OutputStream}, given in the constructor, * and encode/decode to/from Base64 notation on the fly. * @see Base64 @@ -1091,35 +800,34 @@ public static class OutputStream extends java.io.FilterOutputStream { /** The encode. */ private boolean encode; - + /** The position. */ private int position; - + /** The buffer. */ private byte[] buffer; - + /** The buffer length. */ private int bufferLength; - + /** The line length. */ private int lineLength; - + /** The break lines. */ private boolean breakLines; /** - * Constructs a {@link Base64#OutputStream} in ENCODE mode. + * Constructs a {@link org.semanticwb.base.util.SFBase64.OutputStream} in ENCODE mode. * * @param out the {@link java.io.OutputStream} to which data will be written. * @since 1.3 */ - public OutputStream(java.io.OutputStream out) - { + public OutputStream(java.io.OutputStream out) { this(out, SFBase64.ENCODE); } // end constructor /** - * Constructs a {@link Base64#OutputStream} in + * Constructs a {@link org.semanticwb.base.util.SFBase64.OutputStream} in * either ENCODE or DECODE mode. * * @param out the {@link java.io.OutputStream} to which data will be written. @@ -1128,13 +836,12 @@ public OutputStream(java.io.OutputStream out) * @see Base64#DECODE * @since 1.3 */ - public OutputStream(java.io.OutputStream out, boolean encode) - { + public OutputStream(java.io.OutputStream out, boolean encode) { this(out, encode, true); } // end constructor /** - * Constructs a {@link Base64#OutputStream} in + * Constructs a {@link org.semanticwb.base.util.SFBase64.OutputStream} in * either ENCODE or DECODE mode. * * @param out the {@link java.io.OutputStream} to which data will be written. @@ -1144,8 +851,7 @@ public OutputStream(java.io.OutputStream out, boolean encode) * @see Base64#DECODE * @since 1.3 */ - public OutputStream(java.io.OutputStream out, boolean encode, boolean breakLines) - { + public OutputStream(java.io.OutputStream out, boolean encode, boolean breakLines) { super(out); this.breakLines = breakLines; this.encode = encode; @@ -1163,23 +869,20 @@ public OutputStream(java.io.OutputStream out, boolean encode, boolean breakLines * gets a write() call. * When decoding, bytes are buffered four * at a time. - * + * * @param theByte the byte to write * @throws IOException Signals that an I/O exception has occurred. * @since 1.3 */ - public void write(int theByte) throws java.io.IOException - { - if (encode) - { + public void write(int theByte) throws java.io.IOException { + if (encode) { buffer[position++] = (byte) theByte; if (position >= bufferLength) // Enough to encode. { out.write(SFBase64.encode3to4(buffer, bufferLength)); lineLength += 4; - if (breakLines && lineLength >= MAX_LINE_LENGTH) - { + if (breakLines && lineLength >= MAX_LINE_LENGTH) { out.write(NEW_LINE); lineLength = 0; } // end if: end of line @@ -1188,11 +891,9 @@ public void write(int theByte) throws java.io.IOException } // end if: enough to output } // end if: encoding // Else, Decoding - else - { + else { // Meaningful Base64 character? - if (DECODABET[theByte & 0x7f] > WHITE_SPACE_ENC) - { + if (DECODABET[theByte & 0x7f] > WHITE_SPACE_ENC) { buffer[position++] = (byte) theByte; if (position >= bufferLength) // Enough to output. { @@ -1200,8 +901,7 @@ public void write(int theByte) throws java.io.IOException position = 0; } // end if: enough to output } // end if: meaningful base64 character - else if (DECODABET[theByte & 0x7f] != WHITE_SPACE_ENC) - { + else if (DECODABET[theByte & 0x7f] != WHITE_SPACE_ENC) { throw new java.io.IOException("Invalid character in Base64 data."); } // end else: not white space either } // end else: decoding @@ -1210,43 +910,35 @@ else if (DECODABET[theByte & 0x7f] != WHITE_SPACE_ENC) /** * Calls {@link #write} repeatedly until len * bytes are written. - * + * * @param theBytes array from which to read bytes * @param off offset for array * @param len max number of bytes to read into array * @throws IOException Signals that an I/O exception has occurred. * @since 1.3 */ - public void write(byte[] theBytes, int off, int len) throws java.io.IOException - { - for (int i = 0; i < len; i++) - { + public void write(byte[] theBytes, int off, int len) throws java.io.IOException { + for (int i = 0; i < len; i++) { write(theBytes[off + i]); } // end for: each byte written - } // end write /** * Appropriately pads Base64 notation when encoding * or throws an exception if Base64 input is not * properly padded when decoding. - * + * * @throws IOException Signals that an I/O exception has occurred. * @since 1.3 */ - public void flush() throws java.io.IOException - { + public void flush() throws java.io.IOException { super.flush(); - if (position > 0) - { - if (encode) - { + if (position > 0) { + if (encode) { out.write(SFBase64.encode3to4(buffer, position)); position = 0; - } // end if: encoding - else - { + } else { throw new java.io.IOException("Base64 input not properly padded."); } // end else: decoding } // end if: buffer partially full @@ -1256,20 +948,16 @@ public void flush() throws java.io.IOException /** * Flushes and closes (I think, in the superclass) the stream. - * + * * @throws IOException Signals that an I/O exception has occurred. * @since 1.3 */ - public void close() throws java.io.IOException - { + public void close() throws java.io.IOException { super.close(); - //this.flush(); - out.close(); buffer = null; out = null; } // end close } // end inner class OutputStream -} // end class Base64 - +} // end class Base64 \ No newline at end of file diff --git a/src/main/java/org/semanticwb/base/util/SWBMail.java b/src/main/java/org/semanticwb/base/util/SWBMail.java index 787b93e..d100fda 100644 --- a/src/main/java/org/semanticwb/base/util/SWBMail.java +++ b/src/main/java/org/semanticwb/base/util/SWBMail.java @@ -22,265 +22,371 @@ */ package org.semanticwb.base.util; -/** - * - * @author jorge.jimenez - */ -import java.util.ArrayList; -import java.util.Collection; +import org.apache.commons.mail.EmailAttachment; import javax.mail.internet.InternetAddress; - -import org.apache.commons.mail.EmailAttachment; +import javax.validation.constraints.NotNull; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; /** - * The Class SWBMail. + * Wrapper class to hold e-mail message information. + * @author jorge.jimenez */ -public class SWBMail -{ - /** The from email. */ - private String fromEmail = null; - - /** The from name. */ - private String fromName = null; - - /** The to email. */ +public class SWBMail { + private String senderEmail = null; + private String senderName = null; private Collection toEmail = null; - - /** The cc email. */ private Collection ccEmail = null; - - /** The bcc email. */ private Collection bccEmail = null; - - /** The attachments. */ - private ArrayList attachments = new ArrayList<>(); - - /** The addresses. */ - private ArrayList addresses = new ArrayList<>(); - - /** The login. */ + private List attachments = new ArrayList<>(); + private List addresses = new ArrayList<>(); private String login; - - /** The password. */ private String password; - - /** The subject. */ private String subject = null; - - /** The data. */ - private String data = null; - - /** The content type. */ + private String message = null; private String contentType = null; - - /** The smtpserver. */ private String smtpserver = null; /** - * Creates a new instance of AFMailData. + * Constructor. Creates a new instance of {@link SWBMail}. */ - public SWBMail() { - } + public SWBMail() { } /** - * Creates a new instance of AFMailData. + * Constructor. Creates a new instance of {@link SWBMail}. * - * @param toEmail the to email - * @param subject the subject - * @param description the description + * @param recipients List of {@link InternetAddress} objects holding destination addresses. + * @param subject E-mail subject. + * @param body E-mail body. */ - public SWBMail(Collection toEmail, String subject, String description) { - this.fromEmail = "webmail.infotec.com.mx"; - this.toEmail = toEmail; + public SWBMail(@NotNull Collection recipients, @NotNull String subject, @NotNull String body) { + this.senderEmail = "webmail.infotec.com.mx"; + this.toEmail = recipients; this.subject = subject; - this.data = description; + this.message = body; } /** - * Instantiates a new sWB mail. + * Constructor. Creates a new instance of {@link SWBMail}. * - * @param fromEmail the from email - * @param toEmail the to email - * @param ccEmail the cc email - * @param bccEmail the bcc email - * @param subject the subject - * @param data the data - */ - public SWBMail(String fromEmail, Collection toEmail, Collection ccEmail, Collection bccEmail, - String subject, String data) { - this.fromEmail = fromEmail; - this.toEmail = toEmail; - this.ccEmail = ccEmail; - this.bccEmail = bccEmail; + * @param sender Sender e-mail address. + * @param recipients List of {@link InternetAddress} objects holding destination addresses. + * @param ccRecipients List of {@link InternetAddress} objects holding copy addresses. + * @param bccRecipients List of {@link InternetAddress} objects holding carbon copy addresses. + * @param subject E-mail subject. + * @param body E-mail boody. + */ + public SWBMail(@NotNull String sender, @NotNull Collection recipients, + Collection ccRecipients, + Collection bccRecipients, @NotNull String subject, @NotNull String body) { + this.senderEmail = sender; + this.toEmail = recipients; + this.ccEmail = ccRecipients; + this.bccEmail = bccRecipients; this.subject = subject; - this.data = data; + this.message = body; } /** - * Setter for property addresses. - * - * @param addresses the new address + * @deprecated Use {@link #setAddresses(List)} method instead. + * Sets addresses. + * @param addresses the new addresses list. */ + @Deprecated public void setAddress(ArrayList addresses) { this.addresses = addresses; } - /** Getter for property addresses. + /** + * Sets recipient addresses for the e-mail. + * @param addresses List of {@link InternetAddress} objects. + */ + public void setAddresses(@NotNull List addresses) { + this.addresses = addresses; + } + + /** + * Gets the addresses list. * @return Value of property addresses. - * */ - public ArrayList getAddresses() { + public List getAddresses() { return addresses; } /** - * Adds the address. - * - * @param address the address + * Adds an address to the list as an {@link InternetAddress} object. + * @param address the address. */ - public void addAddress(InternetAddress address) { + public void addAddress(@NotNull InternetAddress address) { addresses.add(address); } /** - * Adds the address. - * + * Adds an address to the list as a String. * @param address the address */ public void addAddress(String address) { - InternetAddress inetAddress = new InternetAddress(); - inetAddress.setAddress(address); - addresses.add(inetAddress); + if (null != address && !address.isEmpty()) { + InternetAddress inetAddress = new InternetAddress(); + inetAddress.setAddress(address); + addresses.add(inetAddress); + } } /** - * Setter for property attachments. - * + * @deprecated Use {@link #setAddresses(List)} instead. + * Sets e-mail attachments. * @param attachments the new attachments */ + @Deprecated public void setAttachments(ArrayList attachments) { this.attachments = attachments; } - /** Getter for property attachments. - * @return Value of property attachments. - * + /** + * Sets e-mail attachments. + * @param attachments List of {@link EmailAttachment} objects. */ - public ArrayList getAttachments() { + public void setAttachments(@NotNull List attachments) { + this.attachments = attachments; + } + + /** Gets the list of attachments. + * @return List of attachments. + */ + public List getAttachments() { return attachments; } /** - * Adds the attachment. - * + * Adds an attachment. * @param attachment the attachment */ - public void addAttachment(EmailAttachment attachment) { + public void addAttachment(@NotNull EmailAttachment attachment) { attachments.add(attachment); } - /** Getter for property fromEmail. - * @return Value of property fromEmail. - * + /** + * @deprecated Use getSenderEmail instead for naming consistency. + * Gets e-mail sender. + * @return E-mail address of sender. */ + @Deprecated public String getFromEmail() { - return fromEmail; + return senderEmail; + } + + /** + * Gets the sender e-mail. + * @return E-mail address of sender. + */ + public String getSenderEmail() { + return senderEmail; + } + + /** + * @deprecated use {@link #setSenderEmail(String)} method instead. + * Sets the sender e-mail. + * @param senderMail sender e-mail. + */ + @Deprecated + public void setFromEmail(String senderMail) { + this.senderEmail = senderMail; } - /** Setter for property fromEmail. - * @param fromEmail New value of property fromEmail. - * + /** + * Sets the sender e-mail. + * @param senderMail Sender e-mail. */ - public void setFromEmail(String fromEmail) { - this.fromEmail = fromEmail; + public void setSenderEmail(@NotNull String senderMail) { + this.senderEmail = senderMail; } - /** Getter for property fromName. - * @return Value of property fromName. - * + /** + * @deprecated Use {@link #getSenderName()} method instead. + * Gets sender name. + * @return Sender name. */ + @Deprecated public String getFromName() { - return fromName; + return senderName; } /** - * Setter for property fromName. - * - * @param fromName the new from name + * Gets the sender name. + * @return Sender name. + */ + public String getSenderName() { + return senderName; + } + + /** + * @deprecated Use {@link #setSenderName(String)} method instead. + * Sets the sender name. + * @param senderName sender name. */ - public void setFromName(String fromName) { - this.fromName = fromName; + @Deprecated + public void setFromName(String senderName) { + this.senderName = senderName; + } + + /** + * Sets the sender name. + * @param senderName Sender name. + */ + public void setSenderName(@NotNull String senderName) { + this.senderName = senderName; } - /** Getter for property toEmail. - * @return Value of property toEmail. - * + /** + * @deprecated Use {@link #getRecipients()} method instead. + * Gets recipient e-mail list. + * @return List of {@link InternetAddress} objects of recipients. */ + @Deprecated public Collection getToEmail() { return toEmail; } - /** Setter for property toEmail. - * @param toEmail New value of property toEmail. - * + /** + * Gets recipients list. + * @return Recipients list. + */ + public Collection getRecipients() { + return toEmail; + } + + /** + * @deprecated Use {@link #setRecipients(Collection)} method instead. + * Sets recipient e-mail list + * @param recipients List of {@link InternetAddress} objects of recipients. + */ + @Deprecated + public void setToEmail(Collection recipients) { + this.toEmail = recipients; + } + + /** + * Sets recipient e-mail list + * @param recipients List of {@link InternetAddress} objects of recipients. */ - public void setToEmail(Collection toEmail) { - this.toEmail = toEmail; + public void setRecipients(@NotNull Collection recipients) { + this.toEmail = recipients; } - /** Getter for property ccEmail. - * @return Value of property ccEmail. - * + /** + * @deprecated Use {@link #getCcRecipients()} method instead. + * Gets list of copy recipients. + * @return List of copy recipients.. */ + @Deprecated public Collection getCcEmail() { return ccEmail; } - /** Setter for property ccEmail. - * @param ccEmail New value of property ccEmail. - * + /** + * Gets list of copy recipients. + * @return List of copy recipients.. + */ + public Collection getCcRecipients() { + return ccEmail; + } + + /** + * @deprecated Use {@link #setCcRecipients(Collection)} + * Sets list of copy recipients. + * @param copyRecipients List of {@link InternetAddress} objects of copy recipients. + */ + @Deprecated + public void setCcEmail(Collection copyRecipients) { + this.ccEmail = copyRecipients; + } + + /** + * Sets list of copy recipients. + * @param copyRecipients List of {@link InternetAddress} objects of copy recipients. */ - public void setCcEmail(Collection ccEmail) { - this.ccEmail = ccEmail; + public void setCcRecipients(@NotNull Collection copyRecipients) { + this.ccEmail = copyRecipients; } - /** Getter for property bccEmail. - * @return Value of property bccEmail. - * + /** + * @deprecated Use {@link #getBccRecipients()} method instead. + * Gets list of copy recipients. + * @return List of copy recipients. */ + @Deprecated public Collection getBccEmail() { return bccEmail; } - /** Setter for property bccEmail. - * @param bccEmail New value of property bccEmail. - * + /** + * Gets list of copy recipients. + * @return List of copy recipients. + */ + public Collection getBccRecipients() { + return bccEmail; + } + + /** + * @deprecated Use {@link #setBccRecipients(Collection)} method instead. + * Sets list of carbon copy recipients. + * @param carbonCopyRecipients New value of property bccEmail. + */ + @Deprecated + public void setBccEmail(Collection carbonCopyRecipients) { + this.bccEmail = carbonCopyRecipients; + } + + /** + * Sets list of carbon copy recipients. + * @param carbonCopyRecipients New value of property bccEmail. */ - public void setBccEmail(Collection bccEmail) { - this.bccEmail = bccEmail; + public void setBccRecipients(@NotNull Collection carbonCopyRecipients) { + this.bccEmail = carbonCopyRecipients; } - /** Getter for property data. - * @return Value of property data. - * + /** + * @deprecated Use {@link #getMessage()} method instead. + * Gets e-mail body. + * @return e-mail body */ + @Deprecated public String getData() { - return data; + return message; + } + + /*** + * Gets e-mail body. + * @return e-mail body + */ + public String getMessage() { + return message; } - /** Setter for property data. + /** + * @deprecated Use {@link #setMessage(String)} method instead. + * Setter for property data. * @param data New value of property data. - * */ + @Deprecated public void setData(String data) { - this.data = data; + this.message = data; + } + + /** + * Sets e-mail boy. + * @param message Message String + */ + public void setMessage(@NotNull String message) { + this.message = message; } /** Getter for property login. * @return Value of property login. - * */ public String getLogin() { return login; @@ -288,16 +394,14 @@ public String getLogin() { /** * Setter for property login. - * * @param login the new login */ - public void setLogin(String login) { + public void setLogin(@NotNull String login) { this.login = login; } /** Getter for property password. * @return Value of property password. - * */ public String getPassword() { return password; @@ -305,33 +409,29 @@ public String getPassword() { /** * Setter for property password. - * * @param password the new password */ - public void setPassword(String password) { + public void setPassword(@NotNull String password) { this.password = password; } /** Getter for property contentType. * @return Value of property contentType. - * */ public String getContentType() { return contentType; } /** - * Setter for property data. - * + * Setter for property contentType. * @param contentType the new content type */ - public void setContentType(String contentType) { + public void setContentType(@NotNull String contentType) { this.contentType = contentType; } /** Getter for property subject. * @return Value of property subject. - * */ public String getSubject() { return subject; @@ -339,26 +439,27 @@ public String getSubject() { /** Setter for property subject. * @param subject New value of property subject. - * */ - public void setSubject(String subject) { + public void setSubject(@NotNull String subject) { this.subject = subject; } /** + * @deprecated Not intended to be used anymore. * Setter for property smtpserver. - * * @param smtpserver the new host name */ + @Deprecated public void setHostName(String smtpserver) { this.smtpserver = smtpserver; } /** - * Setter for property smtpserver. - * + * @deprecated Not intended to be used anymore. + * Getter for property smtpserver. * @return the host name */ + @Deprecated public String getHostName() { return smtpserver; } diff --git a/src/main/java/org/semanticwb/base/util/SWBMailSender.java b/src/main/java/org/semanticwb/base/util/SWBMailSender.java index 0aa3da9..b17380c 100644 --- a/src/main/java/org/semanticwb/base/util/SWBMailSender.java +++ b/src/main/java/org/semanticwb/base/util/SWBMailSender.java @@ -22,32 +22,23 @@ */ package org.semanticwb.base.util; -import java.net.SocketException; -import java.util.LinkedList; - import org.semanticwb.Logger; import org.semanticwb.SWBUtils; +import java.util.LinkedList; + /** - * objecto: encargado de procesar y enviar correos electronicos. - * + * Tread responsible for sending queued e-mails. * @author Javier Solís */ public class SWBMailSender extends java.lang.Thread { - - /** The log. */ - private static Logger log = SWBUtils.getLogger(SWBMailSender.class); - - /** The emails. */ - LinkedList emails = null; + private static Logger LOG = SWBUtils.getLogger(SWBMailSender.class); + LinkedList emails; /** - * Creates a new instance of WBMessageServer. - * - * @throws SocketException - * the socket exception + * Constructor. Creates a new instance of {@link SWBMailSender}. */ - public SWBMailSender() throws java.net.SocketException { + public SWBMailSender() { emails = new LinkedList<>(); } @@ -61,20 +52,18 @@ public void run() { try { while (!emails.isEmpty()) { SWBMail email = emails.removeLast(); - SWBUtils.EMAIL.sendMail(email.getFromEmail(), email.getFromName(), email.getAddresses(), - email.getCcEmail(), email.getBccEmail(), email.getSubject(), email.getContentType(), - email.getData(), email.getLogin(), email.getPassword(), email.getAttachments()); + SWBUtils.EMAIL.sendMail(email.getSenderEmail(), email.getSenderName(), email.getAddresses(), + email.getCcRecipients(), email.getBccRecipients(), email.getSubject(), email.getContentType(), + email.getMessage(), email.getLogin(), email.getPassword(), email.getAttachments()); } } catch (Exception e) { - log.error(e); + LOG.error(e); } } /** - * Adds the e mail. - * - * @param email - * the email + * Adds a {@link SWBMail} to the queue. + * @param email {@link SWBMail}. */ public void addEMail(SWBMail email) { emails.addFirst(email); diff --git a/src/main/java/org/semanticwb/base/util/SWBProperties.java b/src/main/java/org/semanticwb/base/util/SWBProperties.java index ecbb5de..560e52b 100644 --- a/src/main/java/org/semanticwb/base/util/SWBProperties.java +++ b/src/main/java/org/semanticwb/base/util/SWBProperties.java @@ -22,111 +22,67 @@ */ package org.semanticwb.base.util; -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.Properties; - import org.semanticwb.Logger; import org.semanticwb.SWBUtils; +import javax.validation.constraints.NotNull; +import javax.ws.rs.DELETE; +import java.io.*; +import java.util.*; + /** - * Objeto: para el manejo de archivos de propiedades. - * + * Class to manage SWBPortal configuration properties. * @author Javier Solis Gonzalez */ public class SWBProperties extends Properties { - - /** The log. */ - static final Logger log = SWBUtils.getLogger(SWBProperties.class); - - /** The read only. */ + static final Logger LOG = SWBUtils.getLogger(SWBProperties.class); private boolean readOnly = false; - - /** The Constant PREFIX. */ private static final String PREFIX = "_comm_"; - - /** The Constant keyValueSeparators. */ private static final String KEYVALUESEPARATORS = "=: \t\r\n\f"; - - /** The Constant strictKeyValueSeparators. */ private static final String STRICTKEYVALUESEPARATORS = "=:"; - - /** The Constant specialSaveChars. */ private static final String SPECIALSAVECHARS = "=: \t\r\n\f#!"; - - /** The Constant whiteSpaceChars. */ private static final String WHITESPACECHARS = " \t\r\n\f"; - - /** The arr. */ private ArrayList arr = new ArrayList<>(); - - /** The change. */ - private boolean change = false; + private boolean changed = false; + /** A table of hex digits. */ + private static final char[] hexDigit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', + 'F' }; /** - * Creates an empty property list with no default values. + * Constructor. Creates an empty property list with no default values. */ public SWBProperties() { this(null); } /** - * Creates an empty property list with the specified defaults. - * - * @param defaults - * the defaults + * Constructor. Creates an empty property list with the specified defaults. + * @param defaults the default properties. */ public SWBProperties(Properties defaults) { super(defaults); } /** - * Copia el contenido de properties ejemplo: System.getProperties - * - * @param source - * the source + * Clones properties from a {@link Properties} object. + * @param source source {@link Properties} */ public void copy(Properties source) { - Iterator it = source.keySet().iterator(); - while (it.hasNext()) { - String key = (String) it.next(); - setProperty(key, source.getProperty(key)); - if (!arr.contains(key)) { - arr.add(key); + if (null != source) { + Iterator it = source.keySet().iterator(); + while (it.hasNext()) { + String key = (String) it.next(); + setProperty(key, source.getProperty(key)); + if (!arr.contains(key)) { + arr.add(key); + } } } } - /** - * Calls the Hashtable method put. Provided for - * parallelism with the getProperty method. Enforces use of strings for - * property keys and values. The value returned is the result of the - * Hashtable call to put. - * - * @param key - * the key to be placed into this property list. - * @param value - * the value corresponding to key. - * @return the previous value of the specified key in this property list, or if - * it did not have one. - * @see #getProperty - * @since 1.2 - */ @Override public synchronized Object setProperty(String key, String value) { - setChange(true); + setChanged(true); return super.setProperty(key, value); } @@ -148,7 +104,7 @@ public synchronized Object setProperty(String key, String value) { * @since 1.2 */ public synchronized Object setProperty(String key, String value, String comment) { - setChange(true); + setChanged(true); StringBuilder com = new StringBuilder(); if (!arr.contains(key)) { arr.add(key); @@ -156,7 +112,7 @@ public synchronized Object setProperty(String key, String value, String comment) if (comment != null) { InputStream inb = new ByteArrayInputStream(comment.getBytes()); try (BufferedReader in = new BufferedReader(new InputStreamReader(inb, "8859_1"))) { - String line = null; + String line; while ((line = in.readLine()) != null) { if (line.length() > 0) { if (line.charAt(0) != '#') { @@ -169,7 +125,7 @@ public synchronized Object setProperty(String key, String value, String comment) } } } catch (Exception e) { - log.error(e); + LOG.error(e); } put(PREFIX + key, com.toString()); } @@ -177,166 +133,17 @@ public synchronized Object setProperty(String key, String value, String comment) } /** + * @deprecated Use {@link #isChanged()}. * Checks for change it. - * * @return true, if successful - * @return */ public boolean hasChangeIt() { return isChange(); } - /** - * Reads a property list (key and element pairs) from the input stream. The - * stream is assumed to be using the ISO 8859-1 character encoding; that is each - * byte is one Latin1 character. Characters not in Latin1, and certain special - * characters, can be represented in keys and elements using escape sequences - * similar to those used for character and string literals (see §3.3 - * and §3.10.6 - * of the Java Language Specification). - * - * The differences from the character escape sequences used for characters and - * strings are: - * - *

    - *
  • Octal escapes are not recognized. - * - *
  • The character sequence \b does not represent a - * backspace character. - * - *
  • The method does not treat a backslash character, \, before a - * non-valid escape character as an error; the backslash is silently dropped. - * For example, in a Java string the sequence "\z" would cause a - * compile time error. In contrast, this method silently drops the backslash. - * Therefore, this method treats the two character sequence "\b" as - * equivalent to the single character 'b'. - * - *
  • Escapes are not necessary for single and double quotes; however, by the - * rule above, single and double quote characters preceded by a backslash still - * yield single and double quote characters, respectively. - * - *
- * - * An IllegalArgumentException is thrown if a malformed Unicode - * escape appears in the input. - * - *

- * This method processes input in terms of lines. A natural line of input is - * terminated either by a set of line terminator characters (\n or - * \r or \r\n) or by the end of the file. A natural - * line may be either a blank line, a comment line, or hold some part of a - * key-element pair. The logical line holding all the data for a key-element - * pair may be spread out across several adjacent natural lines by escaping the - * line terminator sequence with a backslash character, \. Note - * that a comment line cannot be extended in this manner; every natural line - * that is a comment must have its own comment indicator, as described below. If - * a logical line is continued over several natural lines, the continuation - * lines receive further processing, also described below. Lines are read from - * the input stream until end of file is reached. - * - *

- * A natural line that contains only white space characters is considered blank - * and is ignored. A comment line has an ASCII '#' or - * '!' as its first non-white space character; comment lines are - * also ignored and do not encode key-element information. In addition to line - * terminators, this method considers the characters space (' ', - * '\u0020'), tab ('\t', - * '\u0009'), and form feed ('\f', - * '\u000C') to be white space. - * - *

- * If a logical line is spread across several natural lines, the backslash - * escaping the line terminator sequence, the line terminator sequence, and any - * white space at the start the following line have no affect on the key or - * element values. The remainder of the discussion of key and element parsing - * will assume all the characters constituting the key and element appear on a - * single natural line after line continuation characters have been removed. - * Note that it is not sufficient to only examine the character preceding - * a line terminator sequence to to see if the line terminator is escaped; there - * must be an odd number of contiguous backslashes for the line terminator to be - * escaped. Since the input is processed from left to right, a non-zero even - * number of 2n contiguous backslashes before a line terminator (or - * elsewhere) encodes n backslashes after escape processing. - * - *

- * The key contains all of the characters in the line starting with the first - * non-white space character and up to, but not including, the first unescaped - * '=', ':', or white space character other than a - * line terminator. All of these key termination characters may be included in - * the key by escaping them with a preceding backslash character; for example, - *

- * - * \:\= - *

- * - * would be the two-character key ":=". Line terminator characters - * can be included using \r and \n escape sequences. - * Any white space after the key is skipped; if the first non-white space - * character after the key is '=' or ':', then it is - * ignored and any white space characters after it are also skipped. All - * remaining characters on the line become part of the associated element - * string; if there are no remaining characters, the element is the empty string - * "". Once the raw character sequences constituting the - * key and element are identified, escape processing is performed as described - * above. - * - *

- * As an example, each of the following three lines specifies the key - * "Truth" and the associated element value "Beauty": - *

- * - *

-	 * Truth = Beauty
-	 * Truth:Beauty
-	 * Truth			:Beauty
-	 * 
- * - * As another example, the following three lines specify a single property: - *

- * - *

-	 * fruits                           apple, banana, pear, \
-	 * cantaloupe, watermelon, \
-	 * kiwi, mango
-	 * 
- * - * The key is "fruits" and the associated element is: - *

- * - *

-	 * "apple, banana, pear, cantaloupe, watermelon, kiwi, mango"
-	 * 
- * - * Note that a space appears before each \ so that a space will - * appear after each comma in the final result; the \, line - * terminator, and leading white space on the continuation line are merely - * discarded and are not replaced by one or more other characters. - *

- * As a third example, the line: - *

- * - *

-	 * cheeses
-	 * 
- * - * specifies that the key is "cheeses" and the associated element - * is the empty string "". - *

- * - * @param inStream - * the in stream - * @throws IOException - * Signals that an I/O exception has occurred. - * @exception IOException - * if an error occurred when reading from the input stream. - * @throws IllegalArgumentException - * if the input stream contains a malformed Unicode escape sequence. - */ @Override public synchronized void load(InputStream inStream) throws IOException { - setChange(false); + setChanged(false); arr.clear(); clear(); StringBuilder buf = new StringBuilder(); @@ -439,9 +246,7 @@ public synchronized void load(InputStream inStream) throws IOException { /** * Load convert. - * - * @param theString - * the the string + * @param theString the the string * @return the string */ private String loadConvert(String theString) { @@ -511,16 +316,6 @@ private String loadConvert(String theString) { return outBuffer.toString(); } - /** - * Returns an enumeration of all the keys in this property list, including - * distinct keys in the default property list if a key of the same name has not - * already been found from the main properties list. - * - * @return an enumeration of all the keys in this property list, including the - * keys in the default property list. - * @see java.util.Enumeration - * @see java.util.Properties#defaults - */ @Override public Enumeration propertyNames() { Hashtable h = new Hashtable(); @@ -530,9 +325,7 @@ public Enumeration propertyNames() { /** * Property ordered names. - * - * @return the enumeration - * @return + * @return the enumeration. */ public Enumeration propertyOrderedNames() { if (arr.isEmpty()) { @@ -542,10 +335,8 @@ public Enumeration propertyOrderedNames() { } /** - * Enumerates all key/value pairs in the specified hastable. - * - * @param h - * the hashtable + * Enumerates all key/value pairs in the specified hashtable. + * @param h the hashtable */ private synchronized void toEnumeration(Hashtable h) { if (defaults != null) { @@ -570,11 +361,8 @@ private synchronized void toEnumeration(Hashtable h) { * its defaults, recursively, are then checked. The method returns * null if the property is not found. * - * @param key - * the key + * @param key the key * @return the value in this property list with the specified key value. - * @see #setProperty - * @see #defaults */ public String getComment(String key) { key = PREFIX + key; @@ -583,17 +371,13 @@ public String getComment(String key) { return ((sval == null) && (defaults != null)) ? defaults.getProperty(key) : sval; } - /* - * Converts unicodes to encoded \uxxxx and writes out any of the characters - * in specialSaveChars with a preceding slash - */ + /** - * Save convert. + * Converts unicodes to encoded \uxxxx and writes out any of the characters + * in specialSaveChars with a preceding slash. * - * @param theString - * the the string - * @param escapeSpace - * the escape space + * @param theString the the string + * @param escapeSpace the escape space * @return the string */ private String saveConvert(String theString, boolean escapeSpace) { @@ -649,15 +433,10 @@ private String saveConvert(String theString, boolean escapeSpace) { return outBuffer.toString(); } - /* - * Returns true if the given line is a line that must be appended to the next - * line - */ + /** - * Continue line. - * - * @param line - * the line + * Returns true if the given line is a line that must be appended to the next line. + * @param line the line * @return true, if successful */ private boolean continueLine(String line) { @@ -696,77 +475,15 @@ public synchronized boolean equals(Object o) { */ @Override public Object remove(Object key) { - setChange(true); + setChanged(true); arr.remove(key); super.remove(PREFIX + key); return super.remove(key); } - /** - * Writes this property list (key and element pairs) in this - * Properties table to the output stream in a format suitable for - * loading into a Properties table using the. - * - * @param out - * the out - * @param header - * the header - * @throws IOException - * Signals that an I/O exception has occurred. - * {@link #load(InputStream) load} method. The stream is written - * using the ISO 8859-1 character encoding. - *

- * Properties from the defaults table of this - * Properties table (if any) are not written out - * by this method. - *

- * If the header argument is not null, then an ASCII # - * character, the header string, and a line separator are first - * written to the output stream. Thus, the header can - * serve as an identifying comment. - *

- * Next, a comment line is always written, consisting of an ASCII - * # character, the current date and time (as if - * produced by the toString method of Date - * for the current time), and a line separator as generated by the - * Writer. - *

- * Then every entry in this Properties table is written - * out, one per line. For each entry the key string is written, then - * an ASCII =, then the associated element string. Each - * character of the key and element strings is examined to see - * whether it should be rendered as an escape sequence. The ASCII - * characters \, tab, form feed, newline, and carriage - * return are written as \\, \t, - * \f \n, and \r, - * respectively. Characters less than \u0020 and - * characters greater than \u007E are written as - * \uxxxx for the appropriate hexadecimal - * value xxxx. For the key, all space characters are written - * with a preceding \ character. For the element, - * leading space characters, but not embedded or trailing space - * characters, are written with a preceding \ - * character. The key and element characters #, - * !, =, and : are written - * with a preceding backslash to ensure that they are properly - * loaded. - *

- * After the entries have been written, the output stream is - * flushed. The output stream remains open after this method - * returns. - * @exception IOException - * if writing this property list to the specified output stream - * throws an IOException. - * @exception ClassCastException - * if this Properties object contains any keys or - * values that are not Strings. - * @exception NullPointerException - * if out is null. - * @since 1.2 - */ @Override public synchronized void store(OutputStream out, String header) throws IOException { - setChange(false); + setChanged(false); BufferedWriter awriter; awriter = new BufferedWriter(new OutputStreamWriter(out, "8859_1")); if (header != null) { @@ -795,14 +512,10 @@ public synchronized void store(OutputStream out, String header) throws IOExcepti } /** - * Writeln. - * - * @param bw - * the bw - * @param s - * the s - * @throws IOException - * Signals that an I/O exception has occurred. + * Writes a new line to the given {@link BufferedWriter} after the provided String. + * @param bw the {@link BufferedWriter} + * @param s the String to write. + * @throws IOException Signals that an I/O exception has occurred. */ private static void writeln(BufferedWriter bw, String s) throws IOException { bw.write(s); @@ -810,13 +523,9 @@ private static void writeln(BufferedWriter bw, String s) throws IOException { } /** - * Convert a nibble to a hex character. - * - * @param nibble - * the nibble - * @return the char - * @param nibble - * the nibble to convert. + * Converts a nibble to a hex character. + * @param nibble the nibble + * @return the hex character */ private static char toHex(int nibble) { return hexDigit[(nibble & 0xF)]; @@ -824,7 +533,6 @@ private static char toHex(int nibble) { /** * Getter for property readOnly. - * * @return Value of property readOnly. */ public boolean isReadOnly() { @@ -833,34 +541,45 @@ public boolean isReadOnly() { /** * Setter for property readOnly. - * - * @param readOnly - * New value of property readOnly. + * @param readOnly New value of property readOnly. */ public void setReadOnly(boolean readOnly) { this.readOnly = readOnly; } - /** A table of hex digits. */ - private static final char[] hexDigit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', - 'F' }; - /** + * @deprecated Use {@link #isChanged()}. * Checks if is change. - * * @return true, if is change */ + @Deprecated public boolean isChange() { - return change; + return changed; + } + + /*** + * Gets the changed property. + * @return Changed property; + */ + public boolean isChanged() { + return changed; } /** + * @deprecated Use {@link #setChanged(boolean)}. * Sets the change. - * - * @param change - * the new change + * @param changed New value. + */ + @Deprecated + public synchronized void setChange(boolean changed) { + this.changed = changed; + } + + /*** + * Sets the changed property. + * @param changed New value. */ - public synchronized void setChange(boolean change) { - this.change = change; + public synchronized void setChanged(boolean changed) { + this.changed = changed; } } diff --git a/src/main/java/org/semanticwb/base/util/SWBSoftkHashMap.java b/src/main/java/org/semanticwb/base/util/SWBSoftkHashMap.java index 7eb9aee..4dd1eb6 100644 --- a/src/main/java/org/semanticwb/base/util/SWBSoftkHashMap.java +++ b/src/main/java/org/semanticwb/base/util/SWBSoftkHashMap.java @@ -24,11 +24,7 @@ import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; -import java.util.AbstractMap; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.Map; -import java.util.Set; +import java.util.*; /** * The Class SWBSoftkHashMap. diff --git a/src/main/java/org/semanticwb/base/util/SimpleDateFormatTS.java b/src/main/java/org/semanticwb/base/util/SimpleDateFormatTS.java index a8d1120..ebce7f6 100644 --- a/src/main/java/org/semanticwb/base/util/SimpleDateFormatTS.java +++ b/src/main/java/org/semanticwb/base/util/SimpleDateFormatTS.java @@ -4,32 +4,45 @@ import java.util.Date; /** - * + * @deprecated Use {@link java.time.format.DateTimeFormatter} instead. + * Implementation of thread safe SimpleDateFormat wrapper. * @author javier.solis.g */ -public class SimpleDateFormatTS -{ +//TODO: Remove this class and refactor SWBUtils to use java 8 DateTimeFormatter class +@Deprecated +public class SimpleDateFormatTS { private final ThreadLocal sd; - - public SimpleDateFormatTS(final String patern) - { - sd = new ThreadLocal() - { + + /** + * Creates a new thread safe {@link SimpleDateFormatTS} object. + * @param patern DateTime pattern. + */ + public SimpleDateFormatTS(final String patern) { + sd = new ThreadLocal() { @Override protected java.text.SimpleDateFormat initialValue() { return new java.text.SimpleDateFormat(patern); } }; - } - - public Date parse(String txt) throws ParseException - { + } + + /** + * Parses a date string. + * @param txt Date string. + * @return Parsed {@link Date} object. + * @throws ParseException if the provided date string does not match pattern. + */ + public Date parse(String txt) throws ParseException { return sd.get().parse(txt); } - - public String format(Date date) - { + + /** + * Formats a date-time object. + * @param date {@link Date} object to format. + * @return String representation of date object matching pattern. + */ + public String format(Date date) { return sd.get().format(date); } } diff --git a/src/main/java/org/semanticwb/base/util/StringSearch.java b/src/main/java/org/semanticwb/base/util/StringSearch.java new file mode 100644 index 0000000..fb510cc --- /dev/null +++ b/src/main/java/org/semanticwb/base/util/StringSearch.java @@ -0,0 +1,244 @@ +/* + * SemanticWebBuilder es una plataforma para el desarrollo de portales y aplicaciones de integración, + * colaboración y conocimiento, que gracias al uso de tecnología semántica puede generar contextos de + * información alrededor de algún tema de interés o bien integrar información y aplicaciones de diferentes + * fuentes, donde a la información se le asigna un significado, de forma que pueda ser interpretada y + * procesada por personas y/o sistemas, es una creación original del Fondo de Información y Documentación + * para la Industria INFOTEC, cuyo registro se encuentra actualmente en trámite. + * + * INFOTEC pone a su disposición la herramienta SemanticWebBuilder a través de su licenciamiento abierto al público (‘open source’), + * en virtud del cual, usted podrá usarlo en las mismas condiciones con que INFOTEC lo ha diseñado y puesto a su disposición; + * aprender de él; distribuirlo a terceros; acceder a su código fuente y modificarlo, y combinarlo o enlazarlo con otro software, + * todo ello de conformidad con los términos y condiciones de la LICENCIA ABIERTA AL PÚBLICO que otorga INFOTEC para la utilización + * del SemanticWebBuilder 4.0. + * + * INFOTEC no otorga garantía sobre SemanticWebBuilder, de ninguna especie y naturaleza, ni implícita ni explícita, + * siendo usted completamente responsable de la utilización que le dé y asumiendo la totalidad de los riesgos que puedan derivar + * de la misma. + * + * Si usted tiene cualquier duda o comentario sobre SemanticWebBuilder, INFOTEC pone a su disposición la siguiente + * dirección electrónica: + * http://www.semanticwebbuilder.org + */ +package org.semanticwb.base.util; + +import java.text.CollationElementIterator; +import java.text.Collator; +import java.text.RuleBasedCollator; + +/** + * Busca una cadena en un string no importando caracteres especiales. + * @author Javier Solis Gonzalez + * @version 1.0 + */ +public class StringSearch { + + // Member variables for storing precomputed pattern data + /** + * The weight. + */ + int weight = Collator.PRIMARY; + /** + * The pat len. + */ + private int patLen; + /** + * The pat elem. + */ + private int[] patElem; + /** + * The shifts. + */ + private int[] shifts; + + /** + * Creates new {@link StringSearch}. + */ + public StringSearch() { + + } + + /** + * Compare. + * + * @param text the text + * @param pattern the pattern + * @return true, if successful + */ + public boolean compare(String text, String pattern) { + RuleBasedCollator c = (RuleBasedCollator) Collator.getInstance(); + CollationElementIterator patIter = c.getCollationElementIterator(pattern); + CollationElementIterator targIter = c.getCollationElementIterator(text); + + for (int i = 0; i < text.length(); i++) { + targIter.setOffset(i); + patIter.reset(); // Or setOffset(0) + if (match(targIter, patIter)) { + return true; + } + } + return false; + } + + // Map a collation element to an array index + + /** + * Hash. + * + * @param order the order + * @return the int + */ + int hash(int order) { + return CollationElementIterator.primaryOrder(order) % 256; + } + + // Initialize the Boyer-Moore shift tables + + /** + * Initialize. + * + * @param c the c + * @param pat the pat + */ + void initialize(RuleBasedCollator c, String pat) { + // First find out how many elements we're dealing with + patLen = 0; + CollationElementIterator iter = c.getCollationElementIterator(pat); + while (iter.next() != CollationElementIterator.NULLORDER) { + patLen++; + } + + // Allocate space to store the pattern elements and the shift tables + patElem = new int[patLen]; + shifts = new int[256]; + + // Elements not found in the pattern get the maximum shift distance + for (int i = 0; i < 256; i++) { + shifts[i] = patLen; + } + + // Now compute the shift distances for the elements in the pattern. + // While we're at it, save the elements themselves for quick access. + // The "-1" is in the calculation because Java indices are 0-based. + iter.reset(); + for (int i = 0; i < patLen; i++) { + patElem[i] = iter.next(); + int index = hash(patElem[i]); + shifts[index] = Math.min(shifts[index], patLen - i - 1); + } + } + + /** + * Find. + * + * @param text the text + * @param pattern the pattern + * @return the int + */ + public int find(String text, String pattern) { + RuleBasedCollator coll = (RuleBasedCollator) Collator.getInstance(); + CollationElementIterator targIter = coll.getCollationElementIterator(text); + CollationElementIterator iter = coll.getCollationElementIterator(text); + + // build the shift table and the constants we need + initialize(coll, pattern); + int mask = getMask(Collator.PRIMARY); + int done = CollationElementIterator.NULLORDER & mask; + + // Start at the text position corresponding to the end of the pattern + int textIndex = pattern.length(); + + while (textIndex <= text.length()) { + boolean getPattern = true, getTarget = true; + int targetElement = 0, patternElement = 0; + + iter.setOffset(textIndex); + int patIndex = pattern.length(); + + // Iterate backward until we hit the beginning of the pattern + while (patIndex > 0) { + if (getTarget) { + targetElement = targIter.previous() & mask; + } + if (getPattern) { + patternElement = patElem[--patIndex] & mask; + } + getTarget = getPattern = true; + + if (targetElement == 0) { + getPattern = false; // skip targetElement + } else if (patternElement == 0) { + getTarget = false; // skip patternElement + } else if (targetElement != patternElement) { + // There is a mismatch at this position. Decide how far + // over to shift the pattern, then try again. + textIndex = iter.getOffset() + + shifts[hash(targetElement)]; + break; + } + } + if (patIndex == 0) { + // We made it back to the beginning of the pattern, + // which means we matched it all. Return the location. + return targIter.getOffset(); + } + // Otherwise, we're here because of a mismatch, so keep going.... + } + return -1; // No match. + } + + // Return a mask for the part of the order we're interested in + + /** + * Gets the mask. + * + * @param weight the weight + * @return the mask + */ + public int getMask(int weight) { + switch (weight) { + case Collator.PRIMARY: + return 0xFFFF0000; + case Collator.SECONDARY: + return 0xFFFFFF00; + default: + return 0xFFFFFFFF; + } + } + + /** + * Match. + * + * @param text the text + * @param pattern the pattern + * @return true, if successful + */ + public boolean match(CollationElementIterator text, CollationElementIterator pattern) { + int mask = getMask(weight); + int done = CollationElementIterator.NULLORDER & mask; + + boolean getPattern = true, getTarget = true; + int patternElement = 0, targetElement = 0; + + while (true) { + if (getPattern) { + patternElement = pattern.next() & mask; + } + if (getTarget) { + targetElement = text.next() & mask; + } + getTarget = getPattern = true; // By default get both + + if (patternElement == done) { + break; // End of pattern + } else if (targetElement == 0) { + getPattern = false; // skip targetElement + } else if (patternElement == 0) { + getTarget = false; // skip patternElement + } else if (targetElement != patternElement) { + return false; // Mismatch + } + } + return true; // No mismatches + } +} diff --git a/src/main/java/org/semanticwb/base/util/URLEncoder.java b/src/main/java/org/semanticwb/base/util/URLEncoder.java index a7c6108..b5293f6 100644 --- a/src/main/java/org/semanticwb/base/util/URLEncoder.java +++ b/src/main/java/org/semanticwb/base/util/URLEncoder.java @@ -47,22 +47,22 @@ *

*

    *
  • The alphanumeric characters "a" through - * "z", "A" through - * "Z" and "0" - * through "9" remain the same. + * "z", "A" through + * "Z" and "0" + * through "9" remain the same. *
  • The special characters ".", - * "-", "*", and - * "_" remain the same. + * "-", "*", and + * "_" remain the same. *
  • The space character " " is - * converted into a plus sign "+". + * converted into a plus sign "+". *
  • All other characters are unsafe and are first converted into - * one or more bytes using some encoding scheme. Then each byte is - * represented by the 3-character string - * "%xy", where xy is the - * two-digit hexadecimal representation of the byte. - * The recommended encoding scheme to use is UTF-8. However, - * for compatibility reasons, if an encoding is not specified, - * then the default encoding of the platform is used. + * one or more bytes using some encoding scheme. Then each byte is + * represented by the 3-character string + * "%xy", where xy is the + * two-digit hexadecimal representation of the byte. + * The recommended encoding scheme to use is UTF-8. However, + * for compatibility reasons, if an encoding is not specified, + * then the default encoding of the platform is used. *
* *

@@ -72,24 +72,28 @@ * ü is encoded as two bytes C3 (hex) and BC (hex), and the * character @ is encoded as one byte 40 (hex). * - * @author Herb Jellinek + * @author Herb Jellinek * @version 1.26, 04/15/02 - * @since JDK1.0 + * @since JDK1.0 */ -public class URLEncoder -{ - - /** The dont need encoding. */ +public class URLEncoder { + + /** + * The dont need encoding. + */ static BitSet dontNeedEncoding; - - /** The Constant caseDiff. */ + + /** + * The Constant caseDiff. + */ static final int caseDiff = ('a' - 'A'); - - /** The dflt enc name. */ + + /** + * The dflt enc name. + */ static String dfltEncName = null; - static - { + static { /* The list of characters that are not encoded has been * determined as follows: @@ -129,16 +133,13 @@ public class URLEncoder dontNeedEncoding = new BitSet(256); int i; - for (i = 'a'; i <= 'z'; i++) - { + for (i = 'a'; i <= 'z'; i++) { dontNeedEncoding.set(i); } - for (i = 'A'; i <= 'Z'; i++) - { + for (i = 'A'; i <= 'Z'; i++) { dontNeedEncoding.set(i); } - for (i = '0'; i <= '9'; i++) - { + for (i = '0'; i <= '9'; i++) { dontNeedEncoding.set(i); } //dontNeedEncoding.set(' '); /* encoding a space to a + is done @@ -148,43 +149,35 @@ public class URLEncoder dontNeedEncoding.set('.'); dontNeedEncoding.set('*'); - try - { + try { dfltEncName = (String) AccessController.doPrivileged( - new GetPropertyAction("file.encoding") + new GetPropertyAction("file.encoding") ); - }catch(Exception e) - { - dfltEncName=SWBUtils.TEXT.getDafaultEncoding(); + } catch (Exception e) { + dfltEncName = SWBUtils.TEXT.getDafaultEncoding(); } } /** * You can't call the constructor. */ - private URLEncoder() - { + private URLEncoder() { } /** * Translates a string into x-www-form-urlencoded * format. This method uses the platform's default encoding * as the encoding scheme to obtain the bytes for unsafe characters. - * + * * @param s the s - * @return the translated . + * @return the translated . */ - public static String encode(String s) - { - + public static String encode(String s) { String str = null; - if (s != null) { - try - { + try { str = encode(s, dfltEncName); - } catch (UnsupportedEncodingException e) - { + } catch (UnsupportedEncodingException e) { // The system should always have the platform default } } @@ -203,48 +196,37 @@ public static String encode(String s) * World Wide Web Consortium Recommendation states that * UTF-8 should be used. Not doing so may introduce * incompatibilites. - * - * @param s the s + * + * @param s the s * @param enc the enc - * @return the translated . + * @return the translated . * @throws UnsupportedEncodingException the unsupported encoding exception - * @exception UnsupportedEncodingException - * If the named encoding is not supported + * @throws UnsupportedEncodingException If the named encoding is not supported * @see URLDecoder#decode(java.lang.String, java.lang.String) * @since 1.4 */ - public static String encode(String s, String enc) - throws UnsupportedEncodingException - { - + public static String encode(String s, String enc) throws UnsupportedEncodingException { boolean needToChange = false; boolean wroteUnencodedChar = false; int maxBytesPerChar = 10; // rather arbitrary limit, but safe for now StringBuilder out = new StringBuilder(s.length()); ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar); - BufferedWriter writer = - new BufferedWriter(new OutputStreamWriter(buf, enc)); + BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(buf, enc)); - for (int i = 0; i < s.length(); i++) - { + for (int i = 0; i < s.length(); i++) { int c = (int) s.charAt(i); - if (dontNeedEncoding.get(c)) - { - if (c == ' ') - { + if (dontNeedEncoding.get(c)) { + if (c == ' ') { c = '+'; needToChange = true; } out.append((char) c); wroteUnencodedChar = true; - } else - { + } else { // convert to external encoding before hex conversion - try - { - if (wroteUnencodedChar) - { // Fix for 4407610 + try { + if (wroteUnencodedChar) { // Fix for 4407610 writer = new BufferedWriter(new OutputStreamWriter(buf, enc)); wroteUnencodedChar = false; } @@ -257,39 +239,32 @@ public static String encode(String s, String enc) * surrogate pair. For now, just treat it as if it were * any other character. */ - if (c >= 0xD800 && c <= 0xDBFF) - { - if ((i + 1) < s.length()) - { + if (c >= 0xD800 && c <= 0xDBFF) { + if ((i + 1) < s.length()) { int d = (int) s.charAt(i + 1); - if (d >= 0xDC00 && d <= 0xDFFF) - { + if (d >= 0xDC00 && d <= 0xDFFF) { writer.write(d); i++; } } } writer.flush(); - } catch (IOException e) - { + } catch (IOException e) { buf.reset(); continue; } byte[] ba = buf.toByteArray(); - for (int j = 0; j < ba.length; j++) - { + for (int j = 0; j < ba.length; j++) { out.append('%'); char ch = Character.forDigit((ba[j] >> 4) & 0xF, 16); // converting to use uppercase letter as part of // the hex value if ch is a letter. - if (Character.isLetter(ch)) - { + if (Character.isLetter(ch)) { ch -= caseDiff; } out.append(ch); ch = Character.forDigit(ba[j] & 0xF, 16); - if (Character.isLetter(ch)) - { + if (Character.isLetter(ch)) { ch -= caseDiff; } out.append(ch); diff --git a/src/main/java/org/semanticwb/base/util/imp/Logger4jImpl.java b/src/main/java/org/semanticwb/base/util/imp/Logger4jImpl.java index c82eefe..24182ea 100644 --- a/src/main/java/org/semanticwb/base/util/imp/Logger4jImpl.java +++ b/src/main/java/org/semanticwb/base/util/imp/Logger4jImpl.java @@ -26,362 +26,356 @@ import org.semanticwb.Logger; import org.semanticwb.SWBUtils; -/* Se eliminan los comentarios de documentación de esta clase, para que - * se hereden los de la clase padre. */ /** * The Class Logger4jImpl. - * + * * @author Javier Solís */ public class Logger4jImpl implements Logger { - - // Definir objetos para ambos Loggers - /** - * Instance of a Logger. - *

- * Instancia de un logger. - *

- */ - private org.apache.log4j.Logger log = null; - - // Definir objetos para ambos Loggers - /** - * Reference to the object class from which the logger will be used. - *

- * Referencia a la clase (tipo) del objeto desde la que se usará el - * logger. - *

- */ - private Class cls = null; - - /** - * Identifier for the - * TRACE kind of message in the log. This kind of message must provide - * the information needed to trace an error or exceptional condition. - *

- * Identificador para el tipo de mensaje - * TRACE en la bitácora. Este tipo de mensaje debe proveer la - * información necesaria para rastrear un error o condición - * excepcional. - *

- */ - private static final String TRACE = "trace"; - - /** - * Identifier for the - * DEBUG kind of message in the log. This kind of message must provide - * information for bug identification and resolution. - *

- * Identificador para el tipo de mensaje - * DEBUG en la bitácora. Este tipo de mensaje debe mostrar - * información para identificación y resolución de bugs. - *

- */ - private static final String DEBUG = "debug"; - - /** - * Identifier for the - * INFO kind of message in the log. This kind of message provides - * information in a general manner. - *

- * Identificador para el tipo de mensaje - * INFO en la bitácora. Este tipo de mensaje muestra - * información de manera general. - *

- */ - private static final String INFO = "info"; - - /** - * Identifier for the - * WARN kind of message in the log. This kind of message provides a - * warning about a certain situation. - *

- * Identificador para el tipo de mensaje - * WARN en la bitácora. Este tipo de mensaje provee una - * advertencia sobre cierta situació. - *

- */ - private static final String WARN = "warn"; - - /** - * Identifier for the - * ERROR kind of message in the log. This kind of message provides notice - * of an error and information related to that error. - *

- * Identificador para el tipo de mensaje - * ERROR en la bitácora. Este tipo de mensaje provee - * notificación sobre un error e información relacionada a ese - * error. - *

- */ - private static final String ERROR = "error"; - - /** - * Identifier for the - * FATAL kind of message in the log. This kind of message provides notice - * of a situation from which the application cannot recover. - *

- * Identificador para el tipo de mensaje - * FATAL en la bitácora. Este tipo de mensaje provee - * notificación de una situación de la que la aplicación no - * se puede recuperar. - *

- */ - private static final String FATAL = "fatal"; - - /** - * Identifier for the - * EVENT kind of message in the log. This kind of message provides notice - * of the happening of a specific event. - *

- * Identificador para el tipo de mensaje - * EVENT en la bitácora. Este tipo de mensaje provee - * notificación de la ocurrencia de un evento específico. - *

- */ - private static final String EVENT = "event"; - - /** - * Creates an instance of this logger associating the class that will use it. - *

- * Crea una instancia de este logger asociando la clase que lo usará. - *

- * - * @param cls - * the object class from which the logger will be used - */ - public Logger4jImpl(Class cls) { - this.log = org.apache.log4j.Logger.getLogger(cls); - this.cls = cls; - } - - /* - * (non-Javadoc) - * - * @see org.semanticwb.Logger#trace(java.lang.String, java.lang.Throwable) - */ - public void trace(String txt, Throwable t) { - log.trace(txt, t); - SWBUtils.ERROR.addError(txt, t, cls, Logger4jImpl.TRACE); - } - - /* - * (non-Javadoc) - * - * @see org.semanticwb.Logger#trace(java.lang.String) - */ - public void trace(String txt) { - log.trace(txt); - } - - /* - * (non-Javadoc) - * - * @see org.semanticwb.Logger#trace(java.lang.Throwable) - */ - public void trace(Throwable t) { - log.trace(null, t); - SWBUtils.ERROR.addError(null, t, cls, Logger4jImpl.TRACE); - } - - /* - * Usado para debugueos - */ - /* - * (non-Javadoc) - * - * @see org.semanticwb.Logger#debug(java.lang.String, java.lang.Throwable) - */ - public void debug(String txt, Throwable t) { - log.debug(txt, t); - SWBUtils.ERROR.addError(txt, t, cls, Logger4jImpl.DEBUG); - } - - /* - * (non-Javadoc) - * - * @see org.semanticwb.Logger#debug(java.lang.String) - */ - public void debug(String txt) { - log.debug(txt); - } - - /* - * (non-Javadoc) - * - * @see org.semanticwb.Logger#debug(java.lang.Throwable) - */ - public void debug(Throwable t) { - log.debug(null, t); - SWBUtils.ERROR.addError(null, t, cls, Logger4jImpl.DEBUG); - } - - /* - * Usado para Informacion del Sistema - */ - /* - * (non-Javadoc) - * - * @see org.semanticwb.Logger#info(java.lang.String, java.lang.Throwable) - */ - public void info(String txt, Throwable t) { - log.info(txt, t); - SWBUtils.ERROR.addError(txt, t, cls, Logger4jImpl.INFO); - } - - /* - * (non-Javadoc) - * - * @see org.semanticwb.Logger#info(java.lang.String) - */ - public void info(String txt) { - log.info(txt); - } - - /* - * (non-Javadoc) - * - * @see org.semanticwb.Logger#info(java.lang.Throwable) - */ - public void info(Throwable t) { - log.info(null, t); - SWBUtils.ERROR.addError(null, t, cls, Logger4jImpl.INFO); - } - - /* - * (non-Javadoc) - * - * @see org.semanticwb.Logger#warn(java.lang.String, java.lang.Throwable) - */ - public void warn(String txt, Throwable t) { - log.warn(txt, t); - SWBUtils.ERROR.addError(txt, t, cls, Logger4jImpl.WARN); - } - - /* - * (non-Javadoc) - * - * @see org.semanticwb.Logger#warn(java.lang.String) - */ - public void warn(String txt) { - log.warn(txt); - } - - /* - * (non-Javadoc) - * - * @see org.semanticwb.Logger#warn(java.lang.Throwable) - */ - public void warn(Throwable t) { - log.warn(null, t); - SWBUtils.ERROR.addError(null, t, cls, Logger4jImpl.WARN); - } - - /* - * Usado para Errores - */ - /* - * (non-Javadoc) - * - * @see org.semanticwb.Logger#error(java.lang.String, java.lang.Throwable) - */ - public void error(String txt, Throwable t) { - log.error(txt, t); - SWBUtils.ERROR.addError(txt, t, cls, Logger4jImpl.ERROR); - } - - /* - * (non-Javadoc) - * - * @see org.semanticwb.Logger#error(java.lang.String) - */ - public void error(String txt) { - log.error(txt); - } - - /* - * (non-Javadoc) - * - * @see org.semanticwb.Logger#error(java.lang.Throwable) - */ - public void error(Throwable t) { - log.error(null, t); - SWBUtils.ERROR.addError(null, t, cls, Logger4jImpl.ERROR); - } - - /* - * Usado para Errores RunTime Exceptions - */ - /* - * (non-Javadoc) - * - * @see org.semanticwb.Logger#fatal(java.lang.String, java.lang.Throwable) - */ - public void fatal(String txt, Throwable t) { - log.fatal(txt, t); - SWBUtils.ERROR.addError(txt, t, cls, Logger4jImpl.FATAL); - } - - /* - * (non-Javadoc) - * - * @see org.semanticwb.Logger#fatal(java.lang.String) - */ - public void fatal(String txt) { - log.fatal(txt); - } - - /* - * (non-Javadoc) - * - * @see org.semanticwb.Logger#fatal(java.lang.Throwable) - */ - public void fatal(Throwable t) { - log.fatal(null, t); - SWBUtils.ERROR.addError(null, t, cls, Logger4jImpl.FATAL); - } - - /* - * Usado para notificacion de eventos - */ - /* - * (non-Javadoc) - * - * @see org.semanticwb.Logger#event(java.lang.String, java.lang.Throwable) - */ - public void event(String txt, Throwable t) { - log.log(Level.OFF, txt, t); - SWBUtils.ERROR.addError(txt, t, cls, Logger4jImpl.EVENT); - } - - /* - * (non-Javadoc) - * - * @see org.semanticwb.Logger#event(java.lang.String) - */ - public void event(String txt) { - log.log(Level.OFF, txt); - } - - /* - * (non-Javadoc) - * - * @see org.semanticwb.Logger#event(java.lang.Throwable) - */ - public void event(Throwable t) { - log.log(Level.OFF, null, t); - SWBUtils.ERROR.addError(null, t, cls, Logger4jImpl.EVENT); - } - - public boolean isDebugEnabled() { - return log.isDebugEnabled(); - } - - public boolean isTraceEnabled() { - return log.isTraceEnabled(); - } - - public boolean isInfoEnabled() { - return log.isInfoEnabled(); - } + /** + * Instance of a Logger. + *

+ * Instancia de un logger. + *

+ */ + private org.apache.log4j.Logger log = null; + + /** + * Reference to the object class from which the logger will be used. + *

+ * Referencia a la clase (tipo) del objeto desde la que se usará el + * logger. + *

+ */ + private Class cls; + + /** + * Identifier for the + * TRACE kind of message in the log. This kind of message must provide + * the information needed to trace an error or exceptional condition. + *

+ * Identificador para el tipo de mensaje + * TRACE en la bitácora. Este tipo de mensaje debe proveer la + * información necesaria para rastrear un error o condición + * excepcional. + *

+ */ + private static final String TRACE = "trace"; + + /** + * Identifier for the + * DEBUG kind of message in the log. This kind of message must provide + * information for bug identification and resolution. + *

+ * Identificador para el tipo de mensaje + * DEBUG en la bitácora. Este tipo de mensaje debe mostrar + * información para identificación y resolución de bugs. + *

+ */ + private static final String DEBUG = "debug"; + + /** + * Identifier for the + * INFO kind of message in the log. This kind of message provides + * information in a general manner. + *

+ * Identificador para el tipo de mensaje + * INFO en la bitácora. Este tipo de mensaje muestra + * información de manera general. + *

+ */ + private static final String INFO = "info"; + + /** + * Identifier for the + * WARN kind of message in the log. This kind of message provides a + * warning about a certain situation. + *

+ * Identificador para el tipo de mensaje + * WARN en la bitácora. Este tipo de mensaje provee una + * advertencia sobre cierta situació. + *

+ */ + private static final String WARN = "warn"; + + /** + * Identifier for the + * ERROR kind of message in the log. This kind of message provides notice + * of an error and information related to that error. + *

+ * Identificador para el tipo de mensaje + * ERROR en la bitácora. Este tipo de mensaje provee + * notificación sobre un error e información relacionada a ese + * error. + *

+ */ + private static final String ERROR = "error"; + + /** + * Identifier for the + * FATAL kind of message in the log. This kind of message provides notice + * of a situation from which the application cannot recover. + *

+ * Identificador para el tipo de mensaje + * FATAL en la bitácora. Este tipo de mensaje provee + * notificación de una situación de la que la aplicación no + * se puede recuperar. + *

+ */ + private static final String FATAL = "fatal"; + + /** + * Identifier for the + * EVENT kind of message in the log. This kind of message provides notice + * of the happening of a specific event. + *

+ * Identificador para el tipo de mensaje + * EVENT en la bitácora. Este tipo de mensaje provee + * notificación de la ocurrencia de un evento específico. + *

+ */ + private static final String EVENT = "event"; + + /** + * Creates an instance of this logger associating the class that will use it. + *

+ * Crea una instancia de este logger asociando la clase que lo usará. + *

+ * + * @param cls the object class from which the logger will be used + */ + public Logger4jImpl(Class cls) { + this.log = org.apache.log4j.Logger.getLogger(cls); + this.cls = cls; + } + + /* + * (non-Javadoc) + * + * @see org.semanticwb.Logger#trace(java.lang.String, java.lang.Throwable) + */ + public void trace(String txt, Throwable t) { + log.trace(txt, t); + SWBUtils.ERROR.addError(txt, t, cls, Logger4jImpl.TRACE); + } + + /* + * (non-Javadoc) + * + * @see org.semanticwb.Logger#trace(java.lang.String) + */ + public void trace(String txt) { + log.trace(txt); + } + + /* + * (non-Javadoc) + * + * @see org.semanticwb.Logger#trace(java.lang.Throwable) + */ + public void trace(Throwable t) { + log.trace(null, t); + SWBUtils.ERROR.addError(null, t, cls, Logger4jImpl.TRACE); + } + + /* + * Usado para debugueos + */ + /* + * (non-Javadoc) + * + * @see org.semanticwb.Logger#debug(java.lang.String, java.lang.Throwable) + */ + public void debug(String txt, Throwable t) { + log.debug(txt, t); + SWBUtils.ERROR.addError(txt, t, cls, Logger4jImpl.DEBUG); + } + + /* + * (non-Javadoc) + * + * @see org.semanticwb.Logger#debug(java.lang.String) + */ + public void debug(String txt) { + log.debug(txt); + } + + /* + * (non-Javadoc) + * + * @see org.semanticwb.Logger#debug(java.lang.Throwable) + */ + public void debug(Throwable t) { + log.debug(null, t); + SWBUtils.ERROR.addError(null, t, cls, Logger4jImpl.DEBUG); + } + + /* + * Usado para Informacion del Sistema + */ + /* + * (non-Javadoc) + * + * @see org.semanticwb.Logger#info(java.lang.String, java.lang.Throwable) + */ + public void info(String txt, Throwable t) { + log.info(txt, t); + SWBUtils.ERROR.addError(txt, t, cls, Logger4jImpl.INFO); + } + + /* + * (non-Javadoc) + * + * @see org.semanticwb.Logger#info(java.lang.String) + */ + public void info(String txt) { + log.info(txt); + } + + /* + * (non-Javadoc) + * + * @see org.semanticwb.Logger#info(java.lang.Throwable) + */ + public void info(Throwable t) { + log.info(null, t); + SWBUtils.ERROR.addError(null, t, cls, Logger4jImpl.INFO); + } + + /* + * (non-Javadoc) + * + * @see org.semanticwb.Logger#warn(java.lang.String, java.lang.Throwable) + */ + public void warn(String txt, Throwable t) { + log.warn(txt, t); + SWBUtils.ERROR.addError(txt, t, cls, Logger4jImpl.WARN); + } + + /* + * (non-Javadoc) + * + * @see org.semanticwb.Logger#warn(java.lang.String) + */ + public void warn(String txt) { + log.warn(txt); + } + + /* + * (non-Javadoc) + * + * @see org.semanticwb.Logger#warn(java.lang.Throwable) + */ + public void warn(Throwable t) { + log.warn(null, t); + SWBUtils.ERROR.addError(null, t, cls, Logger4jImpl.WARN); + } + + /* + * Usado para Errores + */ + /* + * (non-Javadoc) + * + * @see org.semanticwb.Logger#error(java.lang.String, java.lang.Throwable) + */ + public void error(String txt, Throwable t) { + log.error(txt, t); + SWBUtils.ERROR.addError(txt, t, cls, Logger4jImpl.ERROR); + } + + /* + * (non-Javadoc) + * + * @see org.semanticwb.Logger#error(java.lang.String) + */ + public void error(String txt) { + log.error(txt); + } + + /* + * (non-Javadoc) + * + * @see org.semanticwb.Logger#error(java.lang.Throwable) + */ + public void error(Throwable t) { + log.error(null, t); + SWBUtils.ERROR.addError(null, t, cls, Logger4jImpl.ERROR); + } + + /* + * Usado para Errores RunTime Exceptions + */ + /* + * (non-Javadoc) + * + * @see org.semanticwb.Logger#fatal(java.lang.String, java.lang.Throwable) + */ + public void fatal(String txt, Throwable t) { + log.fatal(txt, t); + SWBUtils.ERROR.addError(txt, t, cls, Logger4jImpl.FATAL); + } + + /* + * (non-Javadoc) + * + * @see org.semanticwb.Logger#fatal(java.lang.String) + */ + public void fatal(String txt) { + log.fatal(txt); + } + + /* + * (non-Javadoc) + * + * @see org.semanticwb.Logger#fatal(java.lang.Throwable) + */ + public void fatal(Throwable t) { + log.fatal(null, t); + SWBUtils.ERROR.addError(null, t, cls, Logger4jImpl.FATAL); + } + + /* + * Usado para notificacion de eventos + */ + /* + * (non-Javadoc) + * + * @see org.semanticwb.Logger#event(java.lang.String, java.lang.Throwable) + */ + public void event(String txt, Throwable t) { + log.log(Level.OFF, txt, t); + SWBUtils.ERROR.addError(txt, t, cls, Logger4jImpl.EVENT); + } + + /* + * (non-Javadoc) + * + * @see org.semanticwb.Logger#event(java.lang.String) + */ + public void event(String txt) { + log.log(Level.OFF, txt); + } + + /* + * (non-Javadoc) + * + * @see org.semanticwb.Logger#event(java.lang.Throwable) + */ + public void event(Throwable t) { + log.log(Level.OFF, null, t); + SWBUtils.ERROR.addError(null, t, cls, Logger4jImpl.EVENT); + } + + public boolean isDebugEnabled() { + return log.isDebugEnabled(); + } + + public boolean isTraceEnabled() { + return log.isTraceEnabled(); + } + + public boolean isInfoEnabled() { + return log.isInfoEnabled(); + } } diff --git a/src/main/java/org/semanticwb/css/parser/Attribute.java b/src/main/java/org/semanticwb/css/parser/Attribute.java index 0e1aa99..1bb0247 100644 --- a/src/main/java/org/semanticwb/css/parser/Attribute.java +++ b/src/main/java/org/semanticwb/css/parser/Attribute.java @@ -23,55 +23,44 @@ package org.semanticwb.css.parser; import java.util.ArrayList; +import java.util.Objects; import java.util.StringTokenizer; /** - * The Class Attribute. - * + * Class to encapsulate information about a CSS attribute. Used in a {@link CSSParser}. * @author victor.lorenzana */ public class Attribute { - - /** The name. */ private String name; - - /** The values. */ - private ArrayList values=new ArrayList<>(); - + private ArrayList values = new ArrayList<>(); + /** - * Instantiates a new attribute. - * - * @param name the name - * @param value the value + * Constructor. Creates a new instance of {@link Attribute}. + * @param name css attribute name + * @param value css attribute value */ - public Attribute(String name,String value) - { - this.name=name; - StringTokenizer st=new StringTokenizer(value," "); - while(st.hasMoreTokens()) - { - String nvalue=st.nextToken().trim(); + public Attribute(String name, String value) { + this.name = name; + StringTokenizer st = new StringTokenizer(value," "); + while(st.hasMoreTokens()) { + String nvalue = st.nextToken().trim(); values.add(nvalue); } } - + /** - * Gets the name. - * - * @return the name + * Gets the attribute name. + * @return attribute name. */ - public String getName() - { + public String getName() { return name; } - + /** - * Gets the values. - * - * @return the values + * Gets an array with the values for an attribute. + * @return the values array. */ - public String[] getValues() - { + public String[] getValues() { return values.toArray(new String[values.size()]); } @@ -79,8 +68,7 @@ public String[] getValues() * @see java.lang.Object#toString() */ @Override - public String toString() - { + public String toString() { return name; } @@ -88,28 +76,21 @@ public String toString() * @see java.lang.Object#equals(java.lang.Object) */ @Override - public boolean equals(Object obj) - { - if (obj == null) - return false; - if (getClass() != obj.getClass()) + public boolean equals(Object obj) { + if (obj == null || getClass() != obj.getClass()) { return false; - final Attribute other = (Attribute) obj; - if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) - return false; - return true; + } + + return Objects.equals(this, (Attribute)obj); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override - public int hashCode() - { + public int hashCode() { int hash = 3; hash = 37 * hash + (this.name != null ? this.name.hashCode() : 0); return hash; } - - } diff --git a/src/main/java/org/semanticwb/css/parser/CSSParser.java b/src/main/java/org/semanticwb/css/parser/CSSParser.java index b26c988..37b78a1 100644 --- a/src/main/java/org/semanticwb/css/parser/CSSParser.java +++ b/src/main/java/org/semanticwb/css/parser/CSSParser.java @@ -22,104 +22,82 @@ */ package org.semanticwb.css.parser; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; import java.util.ArrayList; import java.util.HashSet; import java.util.StringTokenizer; /** - * The Class CSSParser. - * + * CSS Parser utility class. * @author victor.lorenzana */ -public class CSSParser -{ - - /** The selectors. */ +//TODO: Migrate to use a maintained library instead of custom parsing because CSS grammar evolves +public class CSSParser { private ArrayList selectors = new ArrayList<>(); /** - * Instantiates a new cSS parser. - * - * @param data the data + * Constructor. Creates a new instance of a {@link CSSParser}. + * Provided css string is parsed immediately. + * @param css CSS string. */ - public CSSParser(String data) - { - data = cleanComments(data); - if (data.startsWith("@")) - { - data = data.substring(1); - int pos = data.indexOf(';'); - if (pos != -1) - { - data = data.substring(pos + 1); + public CSSParser(String css) { + css = cleanComments(css); + if (css.startsWith("@")) { + css = css.substring(1); + int pos = css.indexOf(';'); + if (pos != -1) { + css = css.substring(pos + 1); } } - data = removeNewLines(data); - int pos = data.indexOf('{'); - while (pos != -1) - { - String selectorrow = data.substring(0, pos).trim(); + + css = css.replace("\r", " ").replace("\n", " "); + int pos = css.indexOf('{'); + while (pos != -1) { + String selectorrow = css.substring(0, pos).trim(); HashSet atts = new HashSet<>(); - data = data.substring(pos + 1); - int pos2 = data.indexOf('}'); - if (pos2 != -1) - { - String values = data.substring(0, pos2).trim(); - data = data.substring(pos2 + 1); + css = css.substring(pos + 1); + int pos2 = css.indexOf('}'); + if (pos2 != -1) { + String values = css.substring(0, pos2).trim(); + css = css.substring(pos2 + 1); StringTokenizer st = new StringTokenizer(values, ";"); - while (st.hasMoreTokens()) - { + while (st.hasMoreTokens()) { String attribute = st.nextToken(); - pos=attribute.indexOf(':'); - if(pos!=-1) - { - String name=attribute.substring(0,pos); - String value=attribute.substring(pos+1); + pos = attribute.indexOf(':'); + if(pos != -1) { + String name = attribute.substring(0,pos); + String value = attribute.substring(pos + 1); Attribute att = new Attribute(name, value); atts.add(att); - } - else - { + } else { String name = attribute; String value = ""; Attribute att = new Attribute(name, value); atts.add(att); } } - } - else - { + } else { throw new IllegalArgumentException("The css is invalid"); } - for(String selector : getSelectors(selectorrow)) - { + for(String selector : getSelectors(selectorrow)) { selectors.add(new Selector(selector, atts)); } - - pos = data.indexOf('{'); + pos = css.indexOf('{'); } } /** - * Gets the selectors. - * - * @param selector the selector - * @return the selectors + * Gets the selectors of the CSS parsed string. + * @param selector the selector. + * @return the selectors. */ - private String[] getSelectors(String selector) - { - HashSet getSelectors=new HashSet<>(); - selector=selector.replace(' ',','); - StringTokenizer st=new StringTokenizer(selector,","); - while(st.hasMoreTokens()) - { - String nselector= st.nextToken().trim(); - if(!nselector.equals("")) - { + private String[] getSelectors(String selector) { + HashSet getSelectors = new HashSet<>(); + selector = selector.replace(' ',','); + StringTokenizer st = new StringTokenizer(selector,","); + while(st.hasMoreTokens()) { + String nselector = st.nextToken().trim(); + if(!nselector.equals("")) { getSelectors.add(nselector); } } @@ -129,118 +107,30 @@ private String[] getSelectors(String selector) /** * Gets the selectors. - * - * @return the selectors + * @return the selectors. */ - public Selector[] getSelectors() - { + public Selector[] getSelectors() { return selectors.toArray(new Selector[selectors.size()]); } /** - * Clean comments. - * - * @param data the data - * @return the string + * Strips block comments from a CSS string. + * @param css the css string. + * @return css string without block comments. */ - private String cleanComments(String data) - { + private String cleanComments(String css) { StringBuilder cssclean = new StringBuilder(); - int pos = data.indexOf("/*"); - while (pos != -1) - { - cssclean.append(data.substring(0, pos)); - data = data.substring(pos + 2); - int pos2 = data.indexOf("*/"); - if (pos2 != -1) - { - data = data.substring(pos2 + 2); + int pos = css.indexOf("/*"); + while (pos != -1) { + cssclean.append(css.substring(0, pos)); + css = css.substring(pos + 2); + int pos2 = css.indexOf("*/"); + if (pos2 != -1) { + css = css.substring(pos2 + 2); } - pos = data.indexOf("/*"); + pos = css.indexOf("/*"); } - cssclean.append(data); + cssclean.append(css); return cssclean.toString().trim(); } - - /** - * Removes the new lines. - * - * @param data the data - * @return the string - */ - private String removeNewLines(String data) - { - StringBuilder cs = new StringBuilder(); - char[] values = data.toCharArray(); - for (char value : values) - { - if (!(value == '\r' || value == '\n')) - { - cs.append(value); - } - } - return cs.toString(); - } - - /** - * The main method. - * - * @param args the arguments - */ - //TODO: Revisar este código y verificar si es necesario aquí o moverlo a una clase de prueba - public static void main(String[] args) - { - String path = "C:\\Documents and Settings\\victor.lorenzana\\Escritorio\\SEGOB XHTML Strict\\images\\estilos.css"; - File file = new File(path); - StringBuilder css = new StringBuilder(); - try - { - FileReader fr = new FileReader(file); - BufferedReader bf = new BufferedReader(fr); - String line = bf.readLine(); - while (line != null) - { - css.append(line); - css.append("\r\n"); - line = bf.readLine(); - } - CSSParser p = new CSSParser(css.toString()); - for (Selector selector : p.getSelectors()) - { - for (Attribute att : selector.getAttributes()) - { - if (att.getName().equals("background-image") || att.getName().equals("background") || att.getName().equals("list-style")) - { - for (String value : att.getValues()) - { - if (value.startsWith("url(")) - { - value = value.substring(4); - int pos = value.indexOf(")"); - if (pos != -1) - { - value = value.substring(0, pos).trim(); - - if (value.indexOf(".") != -1 && !value.startsWith("http://") && !value.toLowerCase().startsWith("wbrelpath://") && !value.startsWith("https://") && !value.startsWith("mailto:") && !value.startsWith("javascript:") && !value.startsWith("ftp:") && !value.startsWith("rtsp:") && !value.startsWith("telnet:") && !value.startsWith("#") && !value.startsWith("/") && !value.startsWith("../")) - { - if(value.startsWith("\"") && value.endsWith("\"")) - { - value=value.substring(1,value.length()-1); - } - System.out.println(value); - } - - } - - } - } - } - } - } - } - catch (Exception e) - { - e.printStackTrace(); - } - } } diff --git a/src/main/java/org/semanticwb/css/parser/Selector.java b/src/main/java/org/semanticwb/css/parser/Selector.java index 4ff6d90..113870b 100644 --- a/src/main/java/org/semanticwb/css/parser/Selector.java +++ b/src/main/java/org/semanticwb/css/parser/Selector.java @@ -22,51 +22,40 @@ */ package org.semanticwb.css.parser; -import java.util.HashSet; +import java.util.Objects; import java.util.Set; /** - * The Class Selector. - * + * Class to encapsulate properties of a CSS Selector. Used in {@link CSSParser}. * @author victor.lorenzana */ public class Selector { - - /** The name. */ private String name; - - /** The atts. */ - private Set atts=new HashSet<>(); - + private Set attributes; + /** - * Instantiates a new selector. - * - * @param name the name - * @param atts the atts + * Constructor. Creates a new instance of a {@link Selector}. + * @param name selector name. + * @param atts selector attributes. */ - Selector(String name,Set atts) - { - this.name=name; - this.atts=atts; + Selector(String name, Set atts) { + this.name = name; + this.attributes = atts; } - + /** - * Gets the attributes. - * - * @return the attributes + * Gets the selector attributes. + * @return the attributes. */ - public Attribute[] getAttributes() - { - return atts.toArray(new Attribute[atts.size()]); + public Attribute[] getAttributes() { + return attributes.toArray(new Attribute[attributes.size()]); } - + /** - * Gets the name. - * - * @return the name + * Gets the selector name. + * @return the selector name. */ - public String getName() - { + public String getName() { return name; } @@ -74,8 +63,7 @@ public String getName() * @see java.lang.Object#toString() */ @Override - public String toString() - { + public String toString() { return name; } @@ -83,28 +71,20 @@ public String toString() * @see java.lang.Object#equals(java.lang.Object) */ @Override - public boolean equals(Object obj) - { - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final Selector other = (Selector) obj; - if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) + public boolean equals(Object obj) { + if (obj == null || getClass() != obj.getClass()) { return false; - return true; + } + return Objects.equals(this, (Selector) obj); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override - public int hashCode() - { + public int hashCode() { int hash = 7; hash = 89 * hash + (this.name != null ? this.name.hashCode() : 0); return hash; } - - } diff --git a/src/main/java/org/semanticwb/io/SWBFile.java b/src/main/java/org/semanticwb/io/SWBFile.java index 00901e0..ed54e25 100644 --- a/src/main/java/org/semanticwb/io/SWBFile.java +++ b/src/main/java/org/semanticwb/io/SWBFile.java @@ -29,6 +29,8 @@ * * @author jorge.jimenez */ +//TODO: Delete this wrapper class because only calls parent methods. + @Deprecated public class SWBFile extends java.io.File { public SWBFile(String pathName) { diff --git a/src/main/java/org/semanticwb/io/SWBFileInputStream.java b/src/main/java/org/semanticwb/io/SWBFileInputStream.java index 91ef0e3..a5930dc 100644 --- a/src/main/java/org/semanticwb/io/SWBFileInputStream.java +++ b/src/main/java/org/semanticwb/io/SWBFileInputStream.java @@ -31,6 +31,8 @@ * * @author jorge.jimenez */ +//TODO: Delete this wrapper class because only calls parent methods. +@Deprecated public class SWBFileInputStream extends FileInputStream { public SWBFileInputStream(String name) throws FileNotFoundException { diff --git a/src/main/java/org/semanticwb/io/SWBFileOutputStream.java b/src/main/java/org/semanticwb/io/SWBFileOutputStream.java index 189ce97..71502b5 100644 --- a/src/main/java/org/semanticwb/io/SWBFileOutputStream.java +++ b/src/main/java/org/semanticwb/io/SWBFileOutputStream.java @@ -31,6 +31,8 @@ * * @author jorge.jimenez */ +//TODO: Delete this wrapper class because only calls parent methods. +@Deprecated public class SWBFileOutputStream extends FileOutputStream { public SWBFileOutputStream(String name) throws FileNotFoundException {