From 0011e5427fd180aeb4e5e8d1dfae4eeb3ffae7f8 Mon Sep 17 00:00:00 2001
From: JRedentor
Date: Fri, 10 Nov 2017 17:34:29 -0600
Subject: [PATCH 01/18] Changed pom to generate jar with source code
---
pom.xml | 35 +++++++++++++++++++++++++++++++++++
1 file changed, 35 insertions(+)
diff --git a/pom.xml b/pom.xml
index 69363b5..9e8062c 100644
--- a/pom.xml
+++ b/pom.xml
@@ -21,6 +21,41 @@
+
+
+ org.apache.maven.plugins
+ maven-javadoc-plugin
+ 2.10.4
+
+ false
+
+
+
+ attach-javadocs
+
+ jar
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-source-plugin
+ 3.0.1
+
+ false
+ true
+
+
+
+ attach-sources
+
+ jar-no-fork
+
+
+
+
+ src/main/java
From 663292361d33150273a7f0c87798fd18d7ff9ce7 Mon Sep 17 00:00:00 2001
From: Hasdai Pacheco
Date: Mon, 14 Jan 2019 13:17:23 -0600
Subject: [PATCH 02/18] Code reformat
---
.../semanticwb/base/db/AutoConnection.java | 287 +++++++++---------
1 file changed, 137 insertions(+), 150 deletions(-)
diff --git a/src/main/java/org/semanticwb/base/db/AutoConnection.java b/src/main/java/org/semanticwb/base/db/AutoConnection.java
index 340615b..81c7d75 100644
--- a/src/main/java/org/semanticwb/base/db/AutoConnection.java
+++ b/src/main/java/org/semanticwb/base/db/AutoConnection.java
@@ -22,29 +22,16 @@
*/
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.
- *
+ *
* @author javier.solis
*/
public class AutoConnection implements Connection {
@@ -53,7 +40,7 @@ public class AutoConnection implements Connection {
private static final Logger log = SWBUtils.getLogger(AutoConnection.class);
/** The con. */
- private java.sql.Connection con = null;
+ private java.sql.Connection con;
/** The pool. */
private DBConnectionPool pool;
@@ -72,7 +59,7 @@ public class AutoConnection implements Connection {
/**
* Instantiates a new auto connection.
- *
+ *
* @param con
* the con
* @param pool
@@ -86,7 +73,7 @@ public AutoConnection(Connection con, DBConnectionPool pool) {
/**
* Check connection.
- *
+ *
* @return true, if successful
*/
public boolean checkConnection() {
@@ -127,7 +114,7 @@ public void changeConnection() {
/**
* Getter for property id.
- *
+ *
* @return Value of property id.
*
*/
@@ -137,7 +124,7 @@ public long getId() {
/**
* Setter for property id.
- *
+ *
* @param id
* New value of property id.
*
@@ -148,7 +135,7 @@ public void setId(long id) {
/**
* Gets the native connection.
- *
+ *
* @return the native connection
* @return
*/
@@ -158,7 +145,7 @@ public java.sql.Connection getNativeConnection() {
/**
* Getter for property pool.
- *
+ *
* @return Value of property pool.
*
*/
@@ -168,7 +155,7 @@ public DBConnectionPool getPool() {
/**
* Getter for property description.
- *
+ *
* @return Value of property description.
*
*/
@@ -178,7 +165,7 @@ public java.lang.String getDescription() {
/**
* Setter for property description.
- *
+ *
* @param description
* New value of property description.
*
@@ -191,7 +178,7 @@ public void setDescription(java.lang.String 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
@@ -206,34 +193,9 @@ public void close() throws SQLException {
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 {
@@ -246,7 +208,7 @@ public SQLWarning getWarnings() throws SQLException {
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#getCatalog()
*/
public String getCatalog() throws SQLException {
@@ -259,20 +221,20 @@ public String getCatalog() throws SQLException {
/*
* (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 {
+ public void setCatalog(String str) throws SQLException {
if (debug) {
- log.debug("setTypeMap");
+ log.debug("setCatalog");
}
checkConnection();
- con.setTypeMap(map);
+ con.setCatalog(str);
}
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#getTypeMap()
*/
public java.util.Map getTypeMap() throws SQLException {
@@ -285,124 +247,124 @@ public java.util.Map getTypeMap() throws SQLException {
/*
* (non-Javadoc)
- *
- * @see java.sql.Connection#getTransactionIsolation()
+ *
+ * @see java.sql.Connection#setTypeMap(java.util.Map)
*/
- public int getTransactionIsolation() throws SQLException {
+ public void setTypeMap(java.util.Map map) throws SQLException {
if (debug) {
- log.debug("getTransactionIsolation");
+ log.debug("setTypeMap");
}
checkConnection();
- return con.getTransactionIsolation();
+ con.setTypeMap(map);
}
/*
* (non-Javadoc)
- *
- * @see java.sql.Connection#isReadOnly()
+ *
+ * @see java.sql.Connection#getTransactionIsolation()
*/
- public boolean isReadOnly() throws SQLException {
+ public int getTransactionIsolation() throws SQLException {
if (debug) {
- log.debug("isReadOnly");
+ log.debug("getTransactionIsolation");
}
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 {
+ public void setTransactionIsolation(int param) throws SQLException {
if (debug) {
- log.debug("getMetaData");
+ log.debug("setTransactionIsolation");
}
checkConnection();
- return con.getMetaData();
+ con.setTransactionIsolation(param);
}
/*
* (non-Javadoc)
- *
- * @see java.sql.Connection#clearWarnings()
+ *
+ * @see java.sql.Connection#isReadOnly()
*/
- public void clearWarnings() throws SQLException {
+ public boolean isReadOnly() throws SQLException {
if (debug) {
- log.debug("clearWarnings");
+ log.debug("isReadOnly");
}
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 {
+ public void setReadOnly(boolean param) throws SQLException {
if (debug) {
- log.debug("nativeSQL");
+ log.debug("setReadOnly");
}
checkConnection();
- return con.nativeSQL(str);
+ con.setReadOnly(param);
}
/*
* (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 {
+ public DatabaseMetaData getMetaData() throws SQLException {
if (debug) {
- log.debug("prepareStatement");
+ log.debug("getMetaData");
}
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 {
+ public void clearWarnings() throws SQLException {
if (debug) {
- log.debug("setTransactionIsolation");
+ log.debug("clearWarnings");
}
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 {
+ public String nativeSQL(String str) throws SQLException {
if (debug) {
- log.debug("setReadOnly");
+ log.debug("nativeSQL");
}
checkConnection();
- con.setReadOnly(param);
+ return con.nativeSQL(str);
}
/*
* (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 {
+ public PreparedStatement prepareStatement(String str, int param, int param2) throws SQLException {
if (debug) {
- log.debug("setCatalog");
+ log.debug("prepareStatement");
}
checkConnection();
- con.setCatalog(str);
+ return con.prepareStatement(str, param, param2);
}
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#isClosed()
*/
public boolean isClosed() throws SQLException {
@@ -415,7 +377,7 @@ public boolean isClosed() throws SQLException {
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#createStatement()
*/
public Statement createStatement() throws SQLException {
@@ -428,7 +390,7 @@ public Statement createStatement() throws SQLException {
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#createStatement(int, int)
*/
public Statement createStatement(int param, int param1) throws SQLException {
@@ -441,7 +403,7 @@ public Statement createStatement(int param, int param1) throws SQLException {
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#prepareStatement(java.lang.String)
*/
public PreparedStatement prepareStatement(String str) throws SQLException {
@@ -454,7 +416,7 @@ public PreparedStatement prepareStatement(String str) throws SQLException {
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#getAutoCommit()
*/
public boolean getAutoCommit() throws SQLException {
@@ -465,9 +427,34 @@ public boolean getAutoCommit() throws SQLException {
return con.getAutoCommit();
}
+ /**
+ * 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#prepareCall(java.lang.String)
*/
public CallableStatement prepareCall(String str) throws SQLException {
@@ -480,7 +467,7 @@ public CallableStatement prepareCall(String str) throws SQLException {
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#commit()
*/
public void commit() throws SQLException {
@@ -493,7 +480,7 @@ public void commit() throws SQLException {
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#prepareCall(java.lang.String, int, int)
*/
public CallableStatement prepareCall(String str, int param, int param2) throws SQLException {
@@ -506,7 +493,7 @@ public CallableStatement prepareCall(String str, int param, int param2) throws S
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#rollback()
*/
public void rollback() throws SQLException {
@@ -519,7 +506,7 @@ public void rollback() throws SQLException {
/*
* (non-Javadoc)
- *
+ *
* @see java.lang.Object#finalize()
*/
@Override
@@ -534,7 +521,7 @@ protected void finalize() throws Throwable {
// *****************************************************************
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#setSavepoint()
*/
public java.sql.Savepoint setSavepoint() throws java.sql.SQLException {
@@ -547,20 +534,7 @@ public java.sql.Savepoint setSavepoint() throws java.sql.SQLException {
/*
* (non-Javadoc)
- *
- * @see java.sql.Connection#setHoldability(int)
- */
- public void setHoldability(int param) throws java.sql.SQLException {
- if (debug) {
- log.debug("setHoldability");
- }
- checkConnection();
- con.setHoldability(param);
- }
-
- /*
- * (non-Javadoc)
- *
+ *
* @see java.sql.Connection#prepareStatement(java.lang.String, int)
*/
public java.sql.PreparedStatement prepareStatement(java.lang.String str, int param) throws java.sql.SQLException {
@@ -573,7 +547,7 @@ public java.sql.PreparedStatement prepareStatement(java.lang.String str, int par
/*
* (non-Javadoc)
- *
+ *
* @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)
@@ -587,7 +561,7 @@ public java.sql.PreparedStatement prepareStatement(java.lang.String str, int par
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#prepareStatement(java.lang.String, int[])
*/
public java.sql.PreparedStatement prepareStatement(java.lang.String str, int[] values)
@@ -601,7 +575,7 @@ public java.sql.PreparedStatement prepareStatement(java.lang.String str, int[] v
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#getHoldability()
*/
public int getHoldability() throws java.sql.SQLException {
@@ -614,7 +588,20 @@ public int getHoldability() throws java.sql.SQLException {
/*
* (non-Javadoc)
- *
+ *
+ * @see java.sql.Connection#setHoldability(int)
+ */
+ public void setHoldability(int param) throws java.sql.SQLException {
+ if (debug) {
+ log.debug("setHoldability");
+ }
+ checkConnection();
+ con.setHoldability(param);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
* @see java.sql.Connection#setSavepoint(java.lang.String)
*/
public java.sql.Savepoint setSavepoint(java.lang.String str) throws java.sql.SQLException {
@@ -627,7 +614,7 @@ public java.sql.Savepoint setSavepoint(java.lang.String str) throws java.sql.SQL
/*
* (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 {
@@ -640,7 +627,7 @@ public java.sql.Statement createStatement(int param, int param1, int param2) thr
/*
* (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)
@@ -654,7 +641,7 @@ public java.sql.CallableStatement prepareCall(java.lang.String str, int param, i
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#releaseSavepoint(java.sql.Savepoint)
*/
public void releaseSavepoint(java.sql.Savepoint savepoint) throws java.sql.SQLException {
@@ -667,7 +654,7 @@ public void releaseSavepoint(java.sql.Savepoint savepoint) throws java.sql.SQLEx
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#prepareStatement(java.lang.String,
* java.lang.String[])
*/
@@ -682,7 +669,7 @@ public java.sql.PreparedStatement prepareStatement(java.lang.String str, java.la
/*
* (non-Javadoc)
- *
+ *
* @see java.sql.Connection#rollback(java.sql.Savepoint)
*/
public void rollback(java.sql.Savepoint savepoint) throws java.sql.SQLException {
@@ -724,11 +711,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 +721,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 +746,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
From 89930e6f92e54898938aa50368ec239e740dae88 Mon Sep 17 00:00:00 2001
From: Hasdai Pacheco
Date: Mon, 14 Jan 2019 21:09:34 -0600
Subject: [PATCH 03/18] Code refactor on db package
---
.../semanticwb/base/db/AutoConnection.java | 315 +++-------
.../base/db/AutoPreparedStatement.java | 300 +++-------
.../org/semanticwb/base/db/AutoStatement.java | 6 +-
.../base/db/DBConnectionManager.java | 416 +++++--------
.../semanticwb/base/db/DBConnectionPool.java | 289 ++++-----
.../semanticwb/base/db/PoolConnection.java | 335 ++++-------
.../base/db/PoolConnectionTimeLock.java | 49 +-
.../base/db/PoolPreparedStatement.java | 561 +++++-------------
.../org/semanticwb/base/db/PoolStatement.java | 132 ++---
9 files changed, 769 insertions(+), 1634 deletions(-)
diff --git a/src/main/java/org/semanticwb/base/db/AutoConnection.java b/src/main/java/org/semanticwb/base/db/AutoConnection.java
index 81c7d75..84418f4 100644
--- a/src/main/java/org/semanticwb/base/db/AutoConnection.java
+++ b/src/main/java/org/semanticwb/base/db/AutoConnection.java
@@ -30,40 +30,23 @@
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;
-
- /** The pool. */
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;
@@ -72,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;
}
@@ -102,93 +80,67 @@ 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);
}
@@ -199,9 +151,6 @@ public void close() throws SQLException {
* @see java.sql.Connection#getWarnings()
*/
public SQLWarning getWarnings() throws SQLException {
- if (debug) {
- log.debug("getWarnings");
- }
checkConnection();
return con.getWarnings();
}
@@ -212,9 +161,6 @@ public SQLWarning getWarnings() throws SQLException {
* @see java.sql.Connection#getCatalog()
*/
public String getCatalog() throws SQLException {
- if (debug) {
- log.debug("getCatalog");
- }
checkConnection();
return con.getCatalog();
}
@@ -224,12 +170,9 @@ public String getCatalog() throws SQLException {
*
* @see java.sql.Connection#setCatalog(java.lang.String)
*/
- public void setCatalog(String str) throws SQLException {
- if (debug) {
- log.debug("setCatalog");
- }
+ public void setCatalog(String catalog) throws SQLException {
checkConnection();
- con.setCatalog(str);
+ con.setCatalog(catalog);
}
/*
@@ -238,9 +181,6 @@ public void setCatalog(String str) throws SQLException {
* @see java.sql.Connection#getTypeMap()
*/
public java.util.Map getTypeMap() throws SQLException {
- if (debug) {
- log.debug("getTypeMap");
- }
checkConnection();
return con.getTypeMap();
}
@@ -251,9 +191,6 @@ public java.util.Map getTypeMap() throws SQLException {
* @see java.sql.Connection#setTypeMap(java.util.Map)
*/
public void setTypeMap(java.util.Map map) throws SQLException {
- if (debug) {
- log.debug("setTypeMap");
- }
checkConnection();
con.setTypeMap(map);
}
@@ -264,9 +201,6 @@ public void setTypeMap(java.util.Map map) throws SQLException {
* @see java.sql.Connection#getTransactionIsolation()
*/
public int getTransactionIsolation() throws SQLException {
- if (debug) {
- log.debug("getTransactionIsolation");
- }
checkConnection();
return con.getTransactionIsolation();
}
@@ -276,12 +210,9 @@ public int getTransactionIsolation() throws SQLException {
*
* @see java.sql.Connection#setTransactionIsolation(int)
*/
- public void setTransactionIsolation(int param) throws SQLException {
- if (debug) {
- log.debug("setTransactionIsolation");
- }
+ public void setTransactionIsolation(int level) throws SQLException {
checkConnection();
- con.setTransactionIsolation(param);
+ con.setTransactionIsolation(level);
}
/*
@@ -290,9 +221,6 @@ public void setTransactionIsolation(int param) throws SQLException {
* @see java.sql.Connection#isReadOnly()
*/
public boolean isReadOnly() throws SQLException {
- if (debug) {
- log.debug("isReadOnly");
- }
checkConnection();
return con.isReadOnly();
}
@@ -302,12 +230,9 @@ public boolean isReadOnly() throws SQLException {
*
* @see java.sql.Connection#setReadOnly(boolean)
*/
- public void setReadOnly(boolean param) throws SQLException {
- if (debug) {
- log.debug("setReadOnly");
- }
+ public void setReadOnly(boolean readOnly) throws SQLException {
checkConnection();
- con.setReadOnly(param);
+ con.setReadOnly(readOnly);
}
/*
@@ -316,9 +241,6 @@ public void setReadOnly(boolean param) throws SQLException {
* @see java.sql.Connection#getMetaData()
*/
public DatabaseMetaData getMetaData() throws SQLException {
- if (debug) {
- log.debug("getMetaData");
- }
checkConnection();
return con.getMetaData();
}
@@ -329,9 +251,6 @@ public DatabaseMetaData getMetaData() throws SQLException {
* @see java.sql.Connection#clearWarnings()
*/
public void clearWarnings() throws SQLException {
- if (debug) {
- log.debug("clearWarnings");
- }
checkConnection();
con.clearWarnings();
}
@@ -341,12 +260,9 @@ public void clearWarnings() throws SQLException {
*
* @see java.sql.Connection#nativeSQL(java.lang.String)
*/
- public String nativeSQL(String str) throws SQLException {
- if (debug) {
- log.debug("nativeSQL");
- }
+ public String nativeSQL(String sql) throws SQLException {
checkConnection();
- return con.nativeSQL(str);
+ return con.nativeSQL(sql);
}
/*
@@ -354,12 +270,9 @@ 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 {
- if (debug) {
- log.debug("prepareStatement");
- }
+ public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
checkConnection();
- return con.prepareStatement(str, param, param2);
+ return con.prepareStatement(sql, resultSetType, resultSetConcurrency);
}
/*
@@ -368,9 +281,6 @@ public PreparedStatement prepareStatement(String str, int param, int param2) thr
* @see java.sql.Connection#isClosed()
*/
public boolean isClosed() throws SQLException {
- if (debug) {
- log.debug("isClosed");
- }
checkConnection();
return con.isClosed();
}
@@ -381,9 +291,6 @@ public boolean isClosed() throws SQLException {
* @see java.sql.Connection#createStatement()
*/
public Statement createStatement() throws SQLException {
- if (debug) {
- log.debug("createStatement");
- }
checkConnection();
return new AutoStatement(this);
}
@@ -394,9 +301,6 @@ public Statement createStatement() throws SQLException {
* @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);
}
@@ -407,9 +311,6 @@ public Statement createStatement(int param, int param1) throws SQLException {
* @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);
}
@@ -420,36 +321,23 @@ public PreparedStatement prepareStatement(String str) throws SQLException {
* @see java.sql.Connection#getAutoCommit()
*/
public boolean getAutoCommit() throws SQLException {
- if (debug) {
- log.debug("getAutoCommit");
- }
checkConnection();
return con.getAutoCommit();
}
/**
- * 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");
- }
+ * 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(param);
+ con.setAutoCommit(enable);
}
/*
@@ -457,12 +345,9 @@ public void setAutoCommit(boolean param) throws SQLException {
*
* @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);
}
/*
@@ -471,9 +356,6 @@ public CallableStatement prepareCall(String str) throws SQLException {
* @see java.sql.Connection#commit()
*/
public void commit() throws SQLException {
- if (debug) {
- log.debug("commit");
- }
checkConnection();
con.commit();
}
@@ -483,12 +365,9 @@ 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 {
- 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);
}
/*
@@ -497,9 +376,6 @@ public CallableStatement prepareCall(String str, int param, int param2) throws S
* @see java.sql.Connection#rollback()
*/
public void rollback() throws SQLException {
- if (debug) {
- log.debug("rollback");
- }
checkConnection();
con.rollback();
}
@@ -511,9 +387,6 @@ public void rollback() throws SQLException {
*/
@Override
protected void finalize() throws Throwable {
- if (debug) {
- log.debug("finalize");
- }
log.warn("finalize()..., connection was not closed, " + description);
}
@@ -524,10 +397,7 @@ protected void finalize() throws Throwable {
*
* @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();
}
@@ -537,12 +407,9 @@ public java.sql.Savepoint setSavepoint() 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 {
- if (debug) {
- log.debug("prepareStatement");
- }
+ public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
checkConnection();
- return con.prepareStatement(str, param);
+ return con.prepareStatement(sql, autoGeneratedKeys);
}
/*
@@ -550,13 +417,9 @@ 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 {
- if (debug) {
- log.debug("prepareStatement");
- }
+ public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
checkConnection();
- return con.prepareStatement(str, param, param2, param3);
+ return con.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
}
/*
@@ -564,13 +427,9 @@ 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 {
- if (debug) {
- log.debug("prepareStatement");
- }
+ public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
checkConnection();
- return con.prepareStatement(str, values);
+ return con.prepareStatement(sql, columnIndexes);
}
/*
@@ -578,10 +437,7 @@ public java.sql.PreparedStatement prepareStatement(java.lang.String str, int[] v
*
* @see java.sql.Connection#getHoldability()
*/
- public int getHoldability() throws java.sql.SQLException {
- if (debug) {
- log.debug("getHoldability");
- }
+ public int getHoldability() throws SQLException {
checkConnection();
return con.getHoldability();
}
@@ -591,12 +447,9 @@ public int getHoldability() throws java.sql.SQLException {
*
* @see java.sql.Connection#setHoldability(int)
*/
- public void setHoldability(int param) throws java.sql.SQLException {
- if (debug) {
- log.debug("setHoldability");
- }
+ public void setHoldability(int holdability) throws SQLException {
checkConnection();
- con.setHoldability(param);
+ con.setHoldability(holdability);
}
/*
@@ -604,10 +457,7 @@ public void setHoldability(int param) 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 {
- if (debug) {
- log.debug("setSavepoint");
- }
+ public Savepoint setSavepoint(java.lang.String str) throws SQLException {
checkConnection();
return con.setSavepoint(str);
}
@@ -617,12 +467,9 @@ 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 {
- 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);
}
/*
@@ -630,13 +477,9 @@ 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 {
- 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);
}
/*
@@ -644,10 +487,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 {
- if (debug) {
- log.debug("releaseSavepoint");
- }
+ public void releaseSavepoint(Savepoint savepoint) throws SQLException {
checkConnection();
con.releaseSavepoint(savepoint);
}
@@ -658,13 +498,9 @@ 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 {
- 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);
}
/*
@@ -672,10 +508,7 @@ 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 {
- if (debug) {
- log.debug("rollback");
- }
+ public void rollback(java.sql.Savepoint savepoint) throws SQLException {
checkConnection();
con.rollback(savepoint);
}
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
*/
- 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.
@@ -176,17 +178,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());
}
/**
@@ -200,23 +199,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.
*/
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"
@@ -261,9 +255,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;
}
/**
@@ -280,29 +274,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");
- }
- if (file.exists()) {
- FileInputStream in = new FileInputStream(file);
- logConf = IO.readInputStream(in);
+ file = new File(applicationPath + "/logging.properties");
}
- 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;
}
/**
@@ -317,7 +310,7 @@ 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);
@@ -332,18 +325,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
@@ -356,24 +349,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();
}
/**
@@ -385,7 +377,7 @@ public static Iterator getErrorElements() {
* @return the value of the class member {@code SWBUtils.errorElementSize}.
*/
public static int getErrorElementSize() {
- return SWBUtils.errorElementSize;
+ return errorElementSize;
}
/**
@@ -394,12 +386,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;
}
}
@@ -416,13 +408,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
@@ -430,6 +423,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.
@@ -439,12 +433,11 @@ private TEXT() {}
*/
private static String defencoding = null;
- 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
@@ -478,69 +471,87 @@ 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;
}
/**
+ * @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;
}
/**
@@ -573,7 +584,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);
@@ -599,12 +610,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;
}
/**
@@ -628,7 +638,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;
}
@@ -636,6 +646,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;
@@ -671,13 +682,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();
@@ -708,7 +719,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;
}
@@ -721,6 +732,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}.
*
@@ -735,11 +747,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.
*
*/
+ @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.
*
@@ -791,10 +807,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) {
@@ -832,9 +846,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);
@@ -872,17 +884,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();
@@ -958,38 +967,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');
@@ -1060,7 +1045,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 == '_'
@@ -1072,82 +1095,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;
@@ -1207,11 +1175,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("\"", """);
}
/**
@@ -1239,7 +1204,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
@@ -1248,7 +1213,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);
}
/**
@@ -1259,7 +1224,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
@@ -1282,7 +1247,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
@@ -1296,7 +1261,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) {
@@ -1305,8 +1269,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;
}
@@ -1324,7 +1287,7 @@ public static String getLocaleString(String bundle, String key, Locale locale, C
* @return the locale
*/
public static Locale getLocale() {
- return SWBUtils.locale;
+ return locale;
}
/**
@@ -1348,9 +1311,9 @@ public static Locale getLocale() {
* y todas las subcadenas que cumplen con {@code regexp}.
*/
// version 1.4
- public static ArrayList regExpSplit(String txt, String regexp) {
+ public static List regExpSplit(String txt, String regexp) {
int index = 0;
- ArrayList matchList = new ArrayList<>();
+ List matchList = new ArrayList<>();
java.util.regex.Matcher m = java.util.regex.Pattern.compile(regexp).matcher(txt);
while (m.find()) {
@@ -1390,7 +1353,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);
@@ -1399,6 +1362,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}.
@@ -1425,8 +1389,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();
@@ -1442,8 +1437,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.
@@ -1474,7 +1469,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.
@@ -1539,7 +1534,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) {
@@ -1550,7 +1545,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);
@@ -1588,7 +1583,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);
@@ -1599,7 +1594,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());
@@ -1628,7 +1623,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
@@ -1654,9 +1649,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
@@ -1666,6 +1661,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;
@@ -1780,6 +1776,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) {
@@ -1813,29 +1810,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
@@ -1872,6 +1846,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}.
*
*/
+ @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;
@@ -1979,13 +1977,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.
*
@@ -2002,7 +2000,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));
@@ -2012,12 +2009,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;
@@ -2026,12 +2025,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;
@@ -2040,6 +2041,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
*
@@ -2049,6 +2051,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++) {
@@ -2059,7 +2062,6 @@ public static String join(String concat, String[] arr) {
}
return ret.toString();
}
-
}
/**
@@ -2071,7 +2073,7 @@ public static String join(String concat, String[] arr) {
*
*/
public static class IO {
-
+
private IO () {}
/**
@@ -2084,7 +2086,7 @@ private IO () {}
*
*/
public static int getBufferSize() {
- return SWBUtils.bufferSize;
+ return bufferSize;
}
/**
@@ -2126,7 +2128,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);
}
/**
@@ -2152,11 +2154,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) {
@@ -2168,6 +2171,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
@@ -2185,7 +2190,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");
}
@@ -2201,6 +2229,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.
@@ -2217,7 +2246,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");
}
@@ -2233,6 +2284,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}.
*
@@ -2240,7 +2292,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
@@ -2263,26 +2315,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");
+ throw new UnsupportedEncodingException("Null Encoding");
}
- 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));
- }
- in.close();
- return ret.toString();
+ InputStreamReader reader = new InputStreamReader(in, enc);
+ return getStringFromReader(reader);
}
/**
@@ -2309,7 +2386,6 @@ public static String readInputStream(InputStream inp, String enc)
* anteriormente.
*/
public static String normalizePath(String path) {
-
if (path == null) {
return null;
}
@@ -2317,12 +2393,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) {
@@ -2366,34 +2445,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}.
@@ -2404,17 +2483,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;
@@ -2475,10 +2569,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;
@@ -2499,17 +2594,41 @@ 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.
+ *
+ * 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.
+ *
+ */
+ @Deprecated
+ public static boolean copyStructure(String source, String target) {
+ return copyDirectory(source, target);
}
/**
@@ -2531,15 +2650,50 @@ public static boolean createDirectory(String path) {
* succefully or not.
*
*/
- public static boolean copyStructure(String source, String target) {
- boolean ret = false;
- try {
- copyStructure(source, target, false, "", "");
- ret = true;
- } catch (Exception e) {
- SWBUtils.log.error(e);
- }
- return ret;
+ public static boolean copyDirectory(String source, String target) {
+ try {
+ copyDirectory(source, target, false, "", "");
+ return true;
+ } catch (Exception e) {
+ LOG.error(e);
+ }
+ 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);
}
/**
@@ -2559,7 +2713,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
@@ -2572,22 +2726,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);
}
}
@@ -2595,26 +2748,27 @@ 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
*
@@ -2646,29 +2800,60 @@ 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 {
+ @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
+ *
+ * @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}.
+ *
+ */
+ 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();
}
/**
@@ -2699,7 +2884,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;
}
@@ -2736,7 +2921,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) {
@@ -2746,49 +2931,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;
@@ -2812,36 +2984,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);
}
}
}
@@ -2890,8 +3063,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);
}
/**
@@ -2923,41 +3096,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;
@@ -2977,6 +3148,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.
@@ -2996,7 +3168,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());
@@ -3063,7 +3259,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.
@@ -3075,8 +3271,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);
}
/**
@@ -3109,17 +3305,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 {
@@ -3136,7 +3328,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);
}
@@ -3149,7 +3341,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);
}
}
}
@@ -3171,20 +3363,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();
}
@@ -3204,18 +3394,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;
}
@@ -3231,7 +3421,7 @@ public static final String readFileFromZipAsString(String zipName, String file2R
* @author Jorge Jiménez
*/
public static class EMAIL {
-
+
private EMAIL () {}
/**
@@ -3287,11 +3477,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;
}
/**
@@ -3300,7 +3490,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.
*
@@ -3308,8 +3498,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;
}
/**
@@ -3319,7 +3509,7 @@ public static void setSMTPServer(String smtpserver) {
* the new sMTP port
*/
public static void setSMTPPort(int port) {
- SWBUtils.EMAIL.smtpport = port;
+ smtpport = port;
}
/**
@@ -3329,7 +3519,7 @@ public static void setSMTPPort(int port) {
* the new sMTP tls
*/
public static void setSMTPTls(boolean tls) {
- SWBUtils.EMAIL.smtptls = tls;
+ smtptls = tls;
}
/**
@@ -3344,7 +3534,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;
}
/**
@@ -3353,23 +3543,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
@@ -3377,22 +3568,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
@@ -3404,7 +3595,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.
@@ -3416,68 +3607,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);
}
/**
@@ -3498,51 +3648,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;
}
/**
@@ -3553,7 +3710,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
@@ -3571,32 +3728,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;
}
@@ -3608,7 +3755,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.
@@ -3622,56 +3769,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
@@ -3683,7 +3820,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.
@@ -3702,64 +3839,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;
}
/**
@@ -3772,17 +3943,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();
@@ -3796,11 +3959,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;
}
/**
@@ -3811,12 +3974,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;
}
/**
@@ -3837,7 +4000,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
@@ -3845,6 +4008,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.
@@ -3864,10 +4028,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}.
@@ -3981,13 +4141,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);
}
}
@@ -4033,7 +4193,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;
}
@@ -4094,10 +4254,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;
}
@@ -4119,8 +4277,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();
@@ -4151,7 +4308,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;
}
@@ -4173,7 +4330,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;
}
@@ -4191,9 +4348,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) {
@@ -4205,7 +4363,7 @@ public static Document xmlToDom(InputSource xml) {
dom = copyDom(dom);
}
} catch (Exception e) {
- SWBUtils.log.error(e);
+ LOG.error(e);
}
return dom;
}
@@ -4221,7 +4379,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) {
@@ -4229,7 +4387,7 @@ public static Document getNewDocument() {
}
dom = db.newDocument();
} catch (Exception e) {
- SWBUtils.log.error(e);
+ LOG.error(e);
}
return dom;
}
@@ -4343,9 +4501,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;
}
@@ -4407,9 +4565,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;
}
@@ -4442,13 +4600,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;
}
@@ -4482,12 +4640,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;
}
@@ -4546,13 +4704,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
@@ -4625,7 +4776,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);
}
}
@@ -4636,33 +4787,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) {
+
}
};
@@ -4694,31 +4830,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);
}
@@ -4746,10 +4867,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);
@@ -5062,10 +5183,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;
}
/**
@@ -5113,7 +5234,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);
}
/**
@@ -5127,7 +5248,7 @@ public static DBConnectionPool getDefaultPool() {
* conexiones a base de datos por defecto.
*/
public static String getDefaultPoolName() {
- return SWBUtils.DB.defaultPoolName;
+ return defaultPoolName;
}
/**
@@ -5141,7 +5262,7 @@ public static String getDefaultPoolName() {
* connection pool. Must not be {@code null}.
*/
public static void setDefaultPool(String poolName) {
- SWBUtils.DB.defaultPoolName = poolName;
+ defaultPoolName = poolName;
}
/**
@@ -5177,7 +5298,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);
}
/**
@@ -5192,7 +5313,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);
}
/**
@@ -5246,7 +5367,7 @@ public static Connection getConnection(String name) {
* defecto.
*/
public static String getDatabaseName() {
- return getDatabaseName(SWBUtils.DB.defaultPoolName);
+ return getDatabaseName(defaultPoolName);
}
/**
@@ -5273,7 +5394,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;
}
@@ -5303,7 +5424,7 @@ public static String getDatabaseName(String poolName) {
*
*/
public static String getDatabaseType() {
- return getDatabaseType(SWBUtils.DB.defaultPoolName);
+ return getDatabaseType(defaultPoolName);
}
/**
@@ -5333,20 +5454,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;
}
@@ -5414,14 +5537,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);
}
}
@@ -5496,7 +5619,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 {
@@ -5527,11 +5650,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 {
@@ -5567,15 +5687,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);
@@ -5608,7 +5720,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;
@@ -5616,10 +5740,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);
}
/**
@@ -5645,7 +5766,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;
@@ -5662,7 +5783,7 @@ public static KeyPair genRSAKeyPair() {
keyGen.initialize(1024);
return keyGen.genKeyPair();
} catch (Exception e) {
- e.printStackTrace();
+ LOG.error(e);
assert (false);
}
return null;
@@ -5721,8 +5842,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)));
@@ -5747,7 +5867,7 @@ public static String genCryptoToken() {
*
*/
public static class Collections {
-
+
private Collections () {}
/**
@@ -5763,7 +5883,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);
diff --git a/src/main/java/org/semanticwb/base/SWBAppObject.java b/src/main/java/org/semanticwb/base/SWBAppObject.java
index 32e069e..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;
/**
- * Interface for an 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 5084218..f2e4199 100644
--- a/src/main/java/org/semanticwb/base/SWBObserver.java
+++ b/src/main/java/org/semanticwb/base/SWBObserver.java
@@ -33,5 +33,5 @@ public interface SWBObserver {
* @param message notification message.
* @param reference reference object.
*/
- public void sendDBNotify(String message, Object reference);
+ void sendDBNotify(String message, Object reference);
}
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:
- *
- *
- * 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/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á.
- *
+ */
+ 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();
+ }
}
From 30e8c05ffe7946697e0c909ae05fcd647799ad5b Mon Sep 17 00:00:00 2001
From: Hasdai Pacheco
Date: Sat, 9 Mar 2019 22:53:37 -0600
Subject: [PATCH 14/18] revert changes to regExpSplit method
---
src/main/java/org/semanticwb/SWBUtils.java | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/main/java/org/semanticwb/SWBUtils.java b/src/main/java/org/semanticwb/SWBUtils.java
index c09374e..52a849b 100644
--- a/src/main/java/org/semanticwb/SWBUtils.java
+++ b/src/main/java/org/semanticwb/SWBUtils.java
@@ -1311,9 +1311,9 @@ public static Locale getLocale() {
* y todas las subcadenas que cumplen con {@code regexp}.
*/
// version 1.4
- public static List regExpSplit(String txt, String regexp) {
+ public static ArrayList regExpSplit(String txt, String regexp) {
int index = 0;
- List matchList = new ArrayList<>();
+ ArrayList matchList = new ArrayList<>();
java.util.regex.Matcher m = java.util.regex.Pattern.compile(regexp).matcher(txt);
while (m.find()) {
From 659ef82b146479001ed255c5e119be70223920fc Mon Sep 17 00:00:00 2001
From: Hasdai Pacheco
Date: Sun, 10 Mar 2019 13:56:47 -0600
Subject: [PATCH 15/18] Added JarFile class from SWBPlatform
---
.../org/semanticwb/base/util/JarFile.java | 267 ++++++++++++++++++
1 file changed, 267 insertions(+)
create mode 100644 src/main/java/org/semanticwb/base/util/JarFile.java
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
From 93b70c377e399b1c1ea0440d538ed1725cb15895 Mon Sep 17 00:00:00 2001
From: Hasdai Pacheco
Date: Sun, 10 Mar 2019 14:41:09 -0600
Subject: [PATCH 16/18] Added class StringSearch
---
.../semanticwb/base/util/StringSearch.java | 244 ++++++++++++++++++
1 file changed, 244 insertions(+)
create mode 100644 src/main/java/org/semanticwb/base/util/StringSearch.java
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
+ }
+}
From d4901b89bcac5baa91a4649a7fd771fe5f1cc77b Mon Sep 17 00:00:00 2001
From: Hasdai Pacheco
Date: Fri, 21 Feb 2020 09:50:39 -0600
Subject: [PATCH 17/18] =?UTF-8?q?Agregado=20m=C3=A9todo=20loadJarManifestA?=
=?UTF-8?q?ttributes?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
src/main/java/org/semanticwb/SWBUtils.java | 29 ++++++++++++++++++++++
1 file changed, 29 insertions(+)
diff --git a/src/main/java/org/semanticwb/SWBUtils.java b/src/main/java/org/semanticwb/SWBUtils.java
index 52a849b..8f795c4 100644
--- a/src/main/java/org/semanticwb/SWBUtils.java
+++ b/src/main/java/org/semanticwb/SWBUtils.java
@@ -61,6 +61,7 @@
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.*;
@@ -69,6 +70,8 @@
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;
@@ -316,6 +319,32 @@ public static Logger getLogger(Class cls) {
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.
*
*/
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+=?";
//TODO: Refactor SimpleDateFormatTS attributes to use Java DateTimeFormatter class
public static final SimpleDateFormatTS formatter = new SimpleDateFormatTS("MMMM");
@@ -558,6 +568,27 @@ public static String getPlural(String name) {
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.