Fabio Dalle Ave 2 mesiacov pred
commit
e61601350f
100 zmenil súbory, kde vykonal 8284 pridanie a 0 odobranie
  1. 76 0
      .gitignore
  2. 3 0
      README.md
  3. 0 0
      identifier.sqlite
  4. 177 0
      pom.xml
  5. 50 0
      src/main/java/commons/bean/BeanUtente.java
  6. 33 0
      src/main/java/commons/bean/CambioPasswordBean.java
  7. 11 0
      src/main/java/commons/bean/IBaseExporter.java
  8. 5 0
      src/main/java/commons/bean/IExportFileProcessor.java
  9. 6 0
      src/main/java/commons/bean/IFileExporter.java
  10. 35 0
      src/main/java/commons/bean/LoginBean.java
  11. 13 0
      src/main/java/commons/common/App.java
  12. 23 0
      src/main/java/commons/common/CalendarJSonSerializer.java
  13. 18 0
      src/main/java/commons/common/CalendarObjectMapper.java
  14. 18 0
      src/main/java/commons/common/CustomObjectMapper.java
  15. 70 0
      src/main/java/commons/common/DatiUtente.java
  16. 17 0
      src/main/java/commons/common/ISODateTimeMapper.java
  17. 18 0
      src/main/java/commons/constant/Constant.java
  18. 44 0
      src/main/java/commons/constant/ConstantMVC.java
  19. 220 0
      src/main/java/commons/controller/BaseController.java
  20. 142 0
      src/main/java/commons/controller/grid/BaseGridController.java
  21. 128 0
      src/main/java/commons/controller/grid/DataTable.java
  22. 58 0
      src/main/java/commons/controller/grid/DataTablesWrapper.java
  23. 16 0
      src/main/java/commons/controller/grid/IGridController.java
  24. 64 0
      src/main/java/commons/enumerate/AllineamentoCampoSpool_e.java
  25. 173 0
      src/main/java/commons/enumerate/Enumerate.java
  26. 14 0
      src/main/java/commons/enumerate/InvalidEnumerateException.java
  27. 47 0
      src/main/java/commons/enumerate/Mese_e.java
  28. 46 0
      src/main/java/commons/enumerate/OrdinamentoRicercaComuni_e.java
  29. 39 0
      src/main/java/commons/enumerate/OrdinamentoRicercaFrazione_e.java
  30. 46 0
      src/main/java/commons/enumerate/OrdinamentoRicercaProvince_e.java
  31. 46 0
      src/main/java/commons/enumerate/OrdinamentoRicercaRegioni_e.java
  32. 40 0
      src/main/java/commons/enumerate/OrdinamentoRicercaStradario_e.java
  33. 48 0
      src/main/java/commons/enumerate/OrdinamentoRicercaTipologiaIndirizzo_e.java
  34. 38 0
      src/main/java/commons/enumerate/Sesso_e.java
  35. 47 0
      src/main/java/commons/enumerate/TipoOrdinamentoRicerca_e.java
  36. 39 0
      src/main/java/commons/enumerate/TipoPeriodoAbbonamento_e.java
  37. 47 0
      src/main/java/commons/enumerate/TipoResponseAJAX_e.java
  38. 49 0
      src/main/java/commons/enumerate/TipoRichiestaAJAX_e.java
  39. 12 0
      src/main/java/commons/exception/ExceptionUtils.java
  40. 35 0
      src/main/java/commons/exception/WebException.java
  41. 51 0
      src/main/java/commons/exception/WebValidateActionException.java
  42. 44 0
      src/main/java/commons/exception/ZApplicationException.java
  43. 29 0
      src/main/java/commons/exception/ZCompressException.java
  44. 19 0
      src/main/java/commons/exception/ZCryptoException.java
  45. 27 0
      src/main/java/commons/exception/ZDataBaseException.java
  46. 72 0
      src/main/java/commons/exception/ZDbUpdateException.java
  47. 25 0
      src/main/java/commons/exception/ZException.java
  48. 11 0
      src/main/java/commons/exception/ZHbmDuplicateIndexException.java
  49. 12 0
      src/main/java/commons/exception/ZHbmException.java
  50. 33 0
      src/main/java/commons/exception/ZMailException.java
  51. 28 0
      src/main/java/commons/exception/ZParseException.java
  52. 35 0
      src/main/java/commons/exception/ZSistemaException.java
  53. 32 0
      src/main/java/commons/exception/ZSystemException.java
  54. 34 0
      src/main/java/commons/exception/ZTransactionException.java
  55. 23 0
      src/main/java/commons/exception/ZWebException.java
  56. 23 0
      src/main/java/commons/exception/ZWebSessioneScadutaException.java
  57. 26 0
      src/main/java/commons/exception/ZXMLException.java
  58. 73 0
      src/main/java/commons/exporters/impl/BaseExporter.java
  59. 11 0
      src/main/java/commons/exporters/intf/IBaseExporter.java
  60. 5 0
      src/main/java/commons/exporters/intf/IExportFileProcessor.java
  61. 5 0
      src/main/java/commons/exporters/intf/IFileExporter.java
  62. 110 0
      src/main/java/commons/type/BaseField.java
  63. 5 0
      src/main/java/commons/type/IFieldModificator.java
  64. 6 0
      src/main/java/commons/type/IFieldTrasformer.java
  65. 8 0
      src/main/java/commons/type/IFieldValidator.java
  66. 13 0
      src/main/java/commons/type/ModifyException.java
  67. 11 0
      src/main/java/commons/type/NotNullModificator.java
  68. 13 0
      src/main/java/commons/type/TransformException.java
  69. 13 0
      src/main/java/commons/type/ValidateException.java
  70. 136 0
      src/main/java/commons/utility/BrowserVersion.java
  71. 401 0
      src/main/java/commons/utility/Compression.java
  72. 150 0
      src/main/java/commons/utility/CryptedCookie.java
  73. 190 0
      src/main/java/commons/utility/Crypto.java
  74. 628 0
      src/main/java/commons/utility/DateUtility.java
  75. 180 0
      src/main/java/commons/utility/FileUtility.java
  76. 356 0
      src/main/java/commons/utility/FormatUtility.java
  77. 76 0
      src/main/java/commons/utility/GeoCode.java
  78. 10 0
      src/main/java/commons/utility/IResetTransient.java
  79. 27 0
      src/main/java/commons/utility/JSon/CalendarSerializer.java
  80. 306 0
      src/main/java/commons/utility/JSon/GraphAdapterBuilder.java
  81. 98 0
      src/main/java/commons/utility/JSon/JSonBuilder.java
  82. 39 0
      src/main/java/commons/utility/JSon/JsonCalendarDeserializer.java
  83. 25 0
      src/main/java/commons/utility/JSon/JsonCalendarSerializer.java
  84. 121 0
      src/main/java/commons/utility/Mail.java
  85. 12 0
      src/main/java/commons/utility/MutableHolder.java
  86. 203 0
      src/main/java/commons/utility/NumberUtility.java
  87. 258 0
      src/main/java/commons/utility/OutputZipFile.java
  88. 24 0
      src/main/java/commons/utility/PasswordCypher.java
  89. 41 0
      src/main/java/commons/utility/ProxyInfo.java
  90. 205 0
      src/main/java/commons/utility/SeparatedText.java
  91. 190 0
      src/main/java/commons/utility/StringUtility.java
  92. 704 0
      src/main/java/commons/utility/UnproxyObject.java
  93. 290 0
      src/main/java/commons/utility/WebUtility.java
  94. 11 0
      src/main/java/commons/utility/bean/DatiAbilitazioni.java
  95. 164 0
      src/main/java/commons/utility/dao/AliasToBeanResultTransformerEnanced.java
  96. 328 0
      src/main/java/commons/utility/dao/GenericDAO.java
  97. 209 0
      src/main/java/commons/utility/dao/GenericHibernateDaoSupport.java
  98. 16 0
      src/main/java/commons/utility/dao/IDAO.java
  99. 48 0
      src/main/java/commons/utility/dao/IGenericHibernateDaoSupport.java
  100. 30 0
      src/main/java/commons/utility/dao/ZDAOException.java

+ 76 - 0
.gitignore

@@ -0,0 +1,76 @@
+### Maven ###
+target/
+pom.xml.tag
+pom.xml.releaseBackup
+pom.xml.versionsBackup
+pom.xml.next
+release.properties
+dependency-reduced-pom.xml
+buildNumber.properties
+.mvn/timing.properties
+.mvn/wrapper/maven-wrapper.jar
+
+### IDE - IntelliJ IDEA ###
+.idea/
+*.iws
+*.iml
+*.ipr
+out/
+.idea_modules/
+
+### IDE - Eclipse ###
+.project
+.classpath
+.settings/
+bin/
+*.launch
+.metadata/
+
+### IDE - NetBeans ###
+nbproject/private/
+build/
+nbbuild/
+dist/
+nbdist/
+.nb-gradle/
+
+### IDE - VS Code ###
+.vscode/
+*.code-workspace
+
+### Java ###
+*.class
+*.jar
+*.war
+*.nar
+*.ear
+*.zip
+*.tar.gz
+*.rar
+hs_err_pid*
+replay_pid*
+
+### OS ###
+.DS_Store
+.DS_Store?
+._*
+.Spotlight-V100
+.Trashes
+ehthumbs.db
+Thumbs.db
+Desktop.ini
+$RECYCLE.BIN/
+
+### Logs ###
+*.log
+log/
+logs/
+
+### Temp ###
+/tmp/
+temp/
+
+### Spring Boot specific ###
+*.pid
+heapdump*.hprof
+spring-boot-devtools.properties

+ 3 - 0
README.md

@@ -0,0 +1,3 @@
+# to deploy to production
+`mvn clean package -Pprod`
+`mvn clean package -Pprod -DskipTests`

+ 0 - 0
identifier.sqlite


+ 177 - 0
pom.xml

@@ -0,0 +1,177 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+
+    <parent>
+        <groupId>org.springframework.boot</groupId>
+        <artifactId>spring-boot-starter-parent</artifactId>
+        <version>3.2.5</version>
+        <relativePath/>
+    </parent>
+
+    <groupId>it.powerage</groupId>
+    <artifactId>laura-catering-server</artifactId>
+    <version>3.0.0</version>
+    <packaging>war</packaging>
+    <name>Laura Catering Server (Spring Boot 3)</name>
+
+    <properties>
+        <java.version>17</java.version>
+        <project.build.sourceEncoding>ISO-8859-1</project.build.sourceEncoding>
+        <jaybird.version>5.0.12.java11</jaybird.version>
+    </properties>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-web</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-jdbc</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.hibernate.orm</groupId>
+            <artifactId>hibernate-core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework</groupId>
+            <artifactId>spring-orm</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>org.apache.tomcat.embed</groupId>
+            <artifactId>tomcat-embed-jasper</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>jakarta.servlet.jsp.jstl</groupId>
+            <artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.glassfish.web</groupId>
+            <artifactId>jakarta.servlet.jsp.jstl</artifactId>
+            <version>3.0.1</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-tomcat</artifactId>
+            <scope>provided</scope>
+        </dependency>
+
+        <dependency>
+            <groupId>org.firebirdsql.jdbc</groupId>
+            <artifactId>jaybird</artifactId>
+            <version>${jaybird.version}</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-validation</artifactId>
+        </dependency>
+
+        <!-- Hibernate community dialects for Firebird -->
+        <dependency>
+            <groupId>org.hibernate.orm</groupId>
+            <artifactId>hibernate-community-dialects</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>commons-io</groupId>
+            <artifactId>commons-io</artifactId>
+            <version>2.11.0</version>
+        </dependency>
+        <dependency>
+            <groupId>commons-dbcp</groupId>
+            <artifactId>commons-dbcp</artifactId>
+            <version>1.4</version>
+        </dependency>
+        <dependency>
+            <groupId>commons-fileupload</groupId>
+            <artifactId>commons-fileupload</artifactId>
+            <version>1.5</version>
+        </dependency>
+        <dependency>
+            <groupId>commons-beanutils</groupId>
+            <artifactId>commons-beanutils</artifactId>
+            <version>1.9.4</version>
+        </dependency>
+
+        <dependency>
+            <groupId>com.lowagie</groupId>
+            <artifactId>itext</artifactId>
+            <version>2.0.7</version>
+        </dependency>
+
+        <dependency>
+            <groupId>com.google.code.gson</groupId>
+            <artifactId>gson</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>com.sun.mail</groupId>
+            <artifactId>jakarta.mail</artifactId>
+            <version>2.0.1</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.aspectj</groupId>
+            <artifactId>aspectjweaver</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>joda-time</groupId>
+            <artifactId>joda-time</artifactId>
+            <version>2.10.14</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.apache.commons</groupId>
+            <artifactId>commons-collections4</artifactId>
+            <version>4.4</version>
+        </dependency>
+
+        <dependency>
+            <groupId>net.sf.json-lib</groupId>
+            <artifactId>json-lib</artifactId>
+            <version>2.4</version>
+            <classifier>jdk15</classifier>
+        </dependency>
+
+        <!-- Log4j 1.x bridge to SLF4J -->
+        <dependency>
+            <groupId>org.slf4j</groupId>
+            <artifactId>log4j-over-slf4j</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.projectlombok</groupId>
+            <artifactId>lombok</artifactId>
+            <scope>provided</scope>
+        </dependency>
+
+        <!--
+        <dependency>
+            <groupId>xalan</groupId>
+            <artifactId>xalan</artifactId>
+            <version>2.7.3</version>
+        </dependency>
+        <dependency>
+            <groupId>xalan</groupId>
+            <artifactId>serializer</artifactId>
+            <version>2.7.3</version>
+        </dependency>
+        -->
+    </dependencies>
+
+    <build>
+        <finalName>powerage</finalName>
+        <plugins>
+            <plugin>
+                <groupId>org.springframework.boot</groupId>
+                <artifactId>spring-boot-maven-plugin</artifactId>
+            </plugin>
+        </plugins>
+    </build>
+</project>

+ 50 - 0
src/main/java/commons/bean/BeanUtente.java

@@ -0,0 +1,50 @@
+package commons.bean;
+
+public class BeanUtente {
+	private long idUtente;
+	private String login;
+	private String codAzienda;
+	private String cognome;
+	private String nome;
+	private int livello;
+	
+	public long getIdUtente() {
+		return idUtente;
+	}
+	public void setIdUtente(long idUtente) {
+		this.idUtente = idUtente;
+	}
+	public String getLogin() {
+		return login;
+	}
+	public void setLogin(String login) {
+		this.login = login;
+	}
+	public String getCodAzienda() {
+		return codAzienda;
+	}
+	public void setCodAzienda(String codAzienda) {
+		this.codAzienda = codAzienda;
+	}
+	
+	public String getCognome() {
+		return cognome;
+	}
+	public void setCognome(String cognome) {
+		this.cognome = cognome;
+	}
+	public String getNome() {
+		return nome;
+	}
+	public void setNome(String nome) {
+		this.nome = nome;
+	}
+	public int getLivello() {
+		return livello;
+	}
+	public void setLivello(int livello) {
+		this.livello = livello;
+	}
+	
+	
+}

+ 33 - 0
src/main/java/commons/bean/CambioPasswordBean.java

@@ -0,0 +1,33 @@
+package commons.bean;
+
+public class CambioPasswordBean {
+	private Long idOperatore;
+	private String oldPassword;
+	private String newPassword;
+	private String confirmPassword;
+	
+	public Long getIdOperatore() {
+		return idOperatore;
+	}
+	public void setIdOperatore(Long idOperatore) {
+		this.idOperatore = idOperatore;
+	}
+	public String getOldPassword() {
+		return oldPassword;
+	}
+	public void setOldPassword(String oldPassword) {
+		this.oldPassword = oldPassword;
+	}
+	public String getNewPassword() {
+		return newPassword;
+	}
+	public void setNewPassword(String newPassword) {
+		this.newPassword = newPassword;
+	}
+	public String getConfirmPassword() {
+		return confirmPassword;
+	}
+	public void setConfirmPassword(String confirmPassword) {
+		this.confirmPassword = confirmPassword;
+	}
+}

+ 11 - 0
src/main/java/commons/bean/IBaseExporter.java

@@ -0,0 +1,11 @@
+package commons.bean;
+
+public interface IBaseExporter {
+	public void setFile(String fileName);
+	public boolean openFile();
+	public boolean writeLine();
+	public boolean isFileEnd();
+	public void closeFile();	
+	public void processRecord();
+	public boolean runExport();
+}

+ 5 - 0
src/main/java/commons/bean/IExportFileProcessor.java

@@ -0,0 +1,5 @@
+package commons.bean;
+
+public interface IExportFileProcessor {
+		public boolean GenerateUpdateFile(String outputFolder, String outputFileName);
+}

+ 6 - 0
src/main/java/commons/bean/IFileExporter.java

@@ -0,0 +1,6 @@
+package commons.bean;
+
+public interface IFileExporter {
+	public boolean ExportZipFile(String zipFileName, String destinationFolder);
+	public boolean ExportFiles(String destinationFolder);
+}

+ 35 - 0
src/main/java/commons/bean/LoginBean.java

@@ -0,0 +1,35 @@
+package commons.bean;
+
+public class LoginBean {
+	
+	private String codSocieta;
+	private String username;
+	private String password;
+	private String impersonatedUser;
+
+
+	public String getCodSocieta() {
+		return codSocieta;
+	}
+	public void setCodSocieta(String codSocieta) {
+		this.codSocieta = codSocieta;
+	}
+	public String getUsername() {
+		return username;
+	}
+	public void setUsername(String login) {
+		this.username = login;
+	}
+	public String getPassword() {
+		return password;
+	}
+	public void setPassword(String password) {
+		this.password = password;
+	}
+	public String getImpersonatedUser() {
+		return impersonatedUser;
+	}
+	public void setImpersonatedUser(String impersonatedUser) {
+		this.impersonatedUser = impersonatedUser;
+	}
+}

+ 13 - 0
src/main/java/commons/common/App.java

@@ -0,0 +1,13 @@
+package commons.common;
+
+/**
+ * Hello world!
+ *
+ */
+public class App 
+{
+    public static void main( String[] args )
+    {
+        System.out.println( "Hello World!" );
+    }
+}

+ 23 - 0
src/main/java/commons/common/CalendarJSonSerializer.java

@@ -0,0 +1,23 @@
+package commons.common;
+
+import java.io.IOException;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.GregorianCalendar;
+
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonSerializer;
+import com.fasterxml.jackson.databind.SerializerProvider;
+
+public class CalendarJSonSerializer extends JsonSerializer<Calendar>
+{
+    @Override
+    public void serialize(Calendar aDate, JsonGenerator aJsonGenerator, SerializerProvider aSerializerProvider)
+            throws IOException, JsonProcessingException {
+
+        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
+        String dateString = dateFormat.format(aDate.getTime());
+        aJsonGenerator.writeString(dateString);
+    }
+}

+ 18 - 0
src/main/java/commons/common/CalendarObjectMapper.java

@@ -0,0 +1,18 @@
+package commons.common;
+
+import java.text.SimpleDateFormat;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializationFeature;
+
+public class CalendarObjectMapper extends ObjectMapper {
+
+	  public CalendarObjectMapper() {
+	        super();
+	        configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
+	        
+	        setDateFormat(new SimpleDateFormat("dd/MM/yyyy HH:mm"));
+	       
+	    }
+	  
+}

+ 18 - 0
src/main/java/commons/common/CustomObjectMapper.java

@@ -0,0 +1,18 @@
+package commons.common;
+
+import java.text.SimpleDateFormat;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializationFeature;
+
+public class CustomObjectMapper extends ObjectMapper {
+
+	  public CustomObjectMapper() {
+	        super();
+	        configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
+	        
+	        setDateFormat(new SimpleDateFormat("dd/MM/yyyy"));
+	       
+	    }
+	  
+}

+ 70 - 0
src/main/java/commons/common/DatiUtente.java

@@ -0,0 +1,70 @@
+package commons.common;
+
+public class DatiUtente {
+	private long idUtente;
+	private String login;
+	private String codAzienda;
+	private String cognome;
+	private String nome;
+	private int livello;
+	
+	public DatiUtente() {
+		idUtente = 0;
+		login = "";
+		codAzienda = "";
+		livello = 0;
+	}
+	
+	
+	public DatiUtente (Long idUtente, String login, String cognome, String nome, int livello){
+		this.idUtente = idUtente;
+		this.login = login;
+		this.cognome = cognome;
+		this.nome = nome;
+		this.livello = livello;	
+	}
+	
+	public long getIdUtente() {
+		return idUtente;
+	}
+	public void setIdUtente(long idUtente) {
+		this.idUtente = idUtente;
+	}
+	public String getLogin() {
+		return login;
+	}
+	public void setLogin(String login) {
+		this.login = login;
+	}
+	public String getCodAzienda() {
+		return codAzienda;
+	}
+	public void setCodAzienda(String codAzienda) {
+		this.codAzienda = codAzienda;
+	}
+	public String getCognome() {
+		return cognome;
+	}
+
+	public void setCognome(String cognome) {
+		this.cognome = cognome;
+	}
+
+	public String getNome() {
+		return nome;
+	}
+
+	public void setNome(String nome) {
+		this.nome = nome;
+	}
+	
+	public int getLivello() {
+		
+		return livello;
+	}
+	public void setLivello(int livello) {
+		this.livello = livello;
+	}
+	
+	
+}

+ 17 - 0
src/main/java/commons/common/ISODateTimeMapper.java

@@ -0,0 +1,17 @@
+package commons.common;
+
+import java.text.SimpleDateFormat;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializationFeature;
+
+public class ISODateTimeMapper extends ObjectMapper {
+	  public ISODateTimeMapper() {
+	        super();
+	        configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
+	        
+//	        setDateFormat(new SimpleDateFormat("dd/MM/yyyy"));
+	       
+	    }
+	
+}

+ 18 - 0
src/main/java/commons/constant/Constant.java

@@ -0,0 +1,18 @@
+package commons.constant;
+
+public class Constant
+{
+	public static final String SEARCH_TYPE = "tipRic";
+	
+	public static final String ORDINAMENTO_RICERCA = "orderSels";
+	public static final String DIREZIONE_RICERCA = "dirs";
+	public static final String MAX_ROWS = "maxRows";
+	
+	public static final String SOURCE = "src";
+	
+	public static final String BR_HTML = "<br/>";
+	public static final int MAX_ROWS_VALUE = 25;
+
+
+}
+

+ 44 - 0
src/main/java/commons/constant/ConstantMVC.java

@@ -0,0 +1,44 @@
+package commons.constant;
+
+public class ConstantMVC {
+
+	public static final String IS_SUBMIT = "isSubmit";
+	//	Gestione generica form
+    public static final String PARAM_ACTION = "act";
+    
+	/**	I dati devono essere cancellati (ci sar? l'id della cosa da cancellare)
+     * Comment for <code>ACTION_DELETE</code>
+     */
+    public static final String ACTION_DELETE = "DEL";
+    
+	/**	I dati devo essere salvati (crea/aggiorna) (ci sar? l'id della cosa da aggiornare)
+     * Comment for <code>ACTION_SAVE</code>
+     */
+    public static final String ACTION_SAVE = "SAVE";
+    
+	/**	I dati devono essere caricati (ci sar? l'id della cosa di cui mostrare i dati)
+     * Comment for <code>ACTION_LOAD</code>
+     */
+    public static final String ACTION_LOAD = "LOAD";
+    
+	/**	I dati devo essere inseriti (crea) (ci sar? l'id della cosa da aggiornare)
+     * Comment for <code>ACTION_SAVE</code>
+     */
+    public static final String JSESSIONID = "JSESSIONID";
+    public static final String NO_SESSION = "NO_SESSION";
+    
+    
+    public static final String ACTION_INSERT = "INS";
+	public static final String AUTH_STRING = "auth";
+	public static final String AUTH_RESULT = "auth_result";
+
+	//	Gestione generica ricerca	
+	public static final String PARAM_AUTO_SEARCH = "auto";
+	public static final String PARAM_ORDER_DESCENDING = "desc";
+	public static final String PARAM_OPEN_SEARCH = "open";
+	public static final String PARAM_WRITE_FUNCTION = "write";
+
+	public static final String PARAM_SEARCH_TYPE = "tipRic";
+	public static final String PARAM_ORDINAMENTO_RICERCA = "orderSel";
+	public static final String PARAM_DIREZIONE_RICERCA = "dir";
+}

+ 220 - 0
src/main/java/commons/controller/BaseController.java

@@ -0,0 +1,220 @@
+package commons.controller;
+
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+
+import org.springframework.beans.propertyeditors.CustomDateEditor;
+import org.springframework.beans.propertyeditors.CustomNumberEditor;
+import org.springframework.validation.BindException;
+import org.springframework.web.bind.ServletRequestDataBinder;
+import org.springframework.web.bind.WebDataBinder;
+import org.springframework.web.bind.annotation.InitBinder;
+import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
+
+import commons.bean.BeanUtente;
+import commons.common.DatiUtente;
+import commons.utility.formatter.CustomCalendarEditor;
+import commons.utility.formatter.CustomIntEditor;
+
+public class BaseController {
+
+	private HttpServletRequest request;
+	private HttpServletResponse response;
+	@SuppressWarnings("unused")
+	private DatiUtente datiUtente;
+
+	public BaseController() {
+
+	}
+
+	public BaseController(HttpServletRequest request, HttpServletResponse response) {
+		this.request = request;
+		this.response = response;
+		this.datiUtente = null;
+	}
+	
+	protected BeanUtente creaBeanUtente() {
+		BeanUtente bean = new BeanUtente();
+		DatiUtente datiUtente = getDatiUtente();
+		
+		bean.setIdUtente(datiUtente.getIdUtente());
+		bean.setLogin(datiUtente.getLogin());
+		bean.setCognome(datiUtente.getCognome());
+		bean.setNome(datiUtente.getNome());
+		bean.setLivello(datiUtente.getLivello());
+		
+		return bean;
+	}	
+
+	
+	public BaseController(HttpServletRequest request, HttpServletResponse response, DatiUtente datiUtente) {
+		this.request = request;
+		this.response = response;
+		this.datiUtente = datiUtente;
+	}
+	
+	public void setRequest(HttpServletRequest request) {
+		this.request = request;
+	}
+	
+	public void setResponse(HttpServletResponse response) {
+		this.response = response;
+	}
+	
+	public HttpServletRequest getRequest() {
+		return request;
+	}
+	
+	public HttpServletResponse getResponse() {
+		return response;
+	}
+	
+	public void setDatiUtente(DatiUtente datiUtente) {
+		setSessionAttribute("datiUtente",datiUtente);
+	}
+	
+	public DatiUtente getDatiUtente() {
+		return (DatiUtente)getSessionAttribute("datiUtente");
+	}
+	
+	public boolean isUserLogged() {
+		return getDatiUtente() != null && getDatiUtente().getIdUtente()!=0;
+	}
+
+
+	protected final Object getSessionAttribute(String name) {
+
+		Object retVal = request.getSession().getAttribute(name);
+		return retVal;
+	}
+
+	protected final void setSessionAttribute(String objectName, Object obj) {
+	/**
+	 * Setta in sessione un oggetto (<code>obj</code>) associandogli un nome (<code>objectName</code>)
+	 * @param objectName
+	 * @param obj
+	 */
+	                                        
+
+		request.getSession().setAttribute(objectName, obj);
+
+	}
+	
+	@InitBinder
+	public void binder(WebDataBinder binder) {
+		
+		SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
+		
+		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
+		
+		SimpleDateFormat calendarFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
+		
+		//binder.registerCustomEditor(Calendar.class,  new CustomDateEditor(calendarFormat, true, -1));
+		
+		binder.registerCustomEditor(Calendar.class,  new CustomCalendarEditor(calendarFormat, true, -1));
+		
+		/*
+		binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
+		    public void setAsText(String value) {
+		        try {
+		        	if (value==null || value == "")
+		        		 setValue(null);
+		        	else {
+			        	Date data = new SimpleDateFormat("dd/MM/yyyy").parse(value); 
+			            setValue(data);
+		        	}
+		        } catch(ParseException e) {
+		            setValue(null);
+		        }
+		    }
+
+		    public String getAsText() {
+		    	if (getValue()==null)
+		    		return "";
+		    	else 
+		    		return new SimpleDateFormat("dd/MM/yyyy").format((Date) getValue());
+		    }        
+		});
+
+		binder.registerCustomEditor(Calendar.class, new PropertyEditorSupport() {
+		    public void setAsText(String value) {
+		        try {
+		        	if (value==null || value == "")
+		        		 setValue(null);
+		        	else {
+			        	Date data = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").parse(value); 
+			            setValue(data);
+		        	}
+		        } catch(ParseException e) {
+		            setValue(null);
+		        }
+		    }
+
+		    public String getAsText() {
+		    	if (getValue()==null)
+		    		return "";
+		    	else 
+		    		return new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").format((Calendar) getValue());
+		    }        
+		});
+	
+		*/
+		
+		binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
+		
+		binder.registerCustomEditor(Integer.class, new CustomNumberEditor(Integer.class, true));
+	}
+
+	
+	
+	/**
+	 * Il metodo della classe madre (BaseController) chiama il metodo super
+	 * della sua classe madre (BaseCommandController) che � vuoto. Viene poi
+	 * invocato il metodo formBackingObject per mettere in request quei
+	 * parametri che non vengono trattati direttamente nel bean. Nelle altre procedure
+	 * era possibile che tali parametri venissero 'persi' quando a fronte
+	 * di una errata validazione si tornava della form della jsp. Ora 
+	 * i parametri vengono gestiti tutti nel bean della pagina e non abbiamo
+	 * bisogno di invocare il metodo formBackingObject nel controller.
+	 */
+	protected void onBindAndValidate(HttpServletRequest request,
+	                                 Object command,
+	                                 BindException errors) throws Exception 
+	                                 {
+	                                 }
+	protected void initBinder(HttpServletRequest request,
+	                          ServletRequestDataBinder binder) throws Exception 
+	{
+		//super.initBinder(request, binder);
+		
+		/*
+		 * MIMMO 10.11.2008 
+		 * gestiamo un nostro custom edito per gli interi
+		 * perch� nel caso in cui compilassimo un campo intero con gli zeri davanti (0012)
+		 * il bind di spring traduci il numero in numero ottale e non va bene.
+		 * Abbiamo riscontrato questo caso nella compilazione della tessera
+		 * che deve essera fillata a sx con gli zeri
+		 */
+		binder.registerCustomEditor(int.class, new CustomIntEditor());
+		
+		SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
+		
+		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
+		
+		SimpleDateFormat calendarFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm");
+		
+		binder.registerCustomEditor(Calendar.class, new CustomDateEditor(calendarFormat, true));
+
+
+		//binder.registerCustomEditor(Calendar.class, new CustomCalendarEditor(calendarFormat, true));
+
+		//binder.registerCustomEditor(String.class, new CustomSubCharEditor(false));
+
+	}
+	
+	
+}

+ 142 - 0
src/main/java/commons/controller/grid/BaseGridController.java

@@ -0,0 +1,142 @@
+package commons.controller.grid;
+
+
+import java.io.Serializable;
+import java.lang.reflect.InvocationTargetException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import jakarta.servlet.http.HttpServletRequest;
+import commons.utility.MutableHolder;
+
+import org.apache.commons.beanutils.BeanUtils;
+import org.apache.commons.beanutils.NestedNullException;
+
+import commons.common.DatiUtente;
+import commons.utility.formatter.DataFormatter;
+import commons.utility.dao.IDAO;
+
+import org.springframework.beans.BeanWrapper;
+import org.springframework.beans.BeanWrapperImpl;
+import org.springframework.beans.NullValueInNestedPathException;
+
+public abstract class BaseGridController<T, ID extends Serializable> implements IGridController<T> {
+
+	protected IDAO<T, ID> dao;
+	protected int sEcho=0, iDisplayStart, iDisplayLength,iSortCol_0;
+	protected String sSortDir_0 = "";
+	protected String filter="";
+	protected List<T> items;
+	protected MutableHolder<Integer> rowCount;
+	protected List<String> columns;
+	
+	public BaseGridController() {
+		rowCount = new MutableHolder<Integer>(0);
+		//columns = new ArrayList<String>();
+	}
+	
+	private Object getSessionAttribute(HttpServletRequest request, String name) {
+
+		Object retVal = request.getSession().getAttribute(name);
+		return retVal;
+	}
+
+	public DatiUtente getDatiUtente(HttpServletRequest request) {
+		return (DatiUtente)getSessionAttribute(request, "datiUtente");
+	}
+	
+	public void setsEcho(HttpServletRequest request) {
+		if(request.getParameter("sEcho")!=null) {
+			sEcho = DataFormatter.getInstance().parseIndice((String) request.getParameter("sEcho"));
+		}
+	}
+	
+	protected void extractGridPrams(HttpServletRequest request){
+		if(request.getParameter("sEcho")!=null) {
+			sEcho = DataFormatter.getInstance().parseIndice((String) request.getParameter("sEcho"));
+		}
+		if(request.getParameter("iDisplayStart")!=null) {
+			iDisplayStart = DataFormatter.getInstance().parseIndice((String) request.getParameter("iDisplayStart"));
+		}
+		if(request.getParameter("iDisplayLength")!=null) {
+			iDisplayLength = DataFormatter.getInstance().parseIndice((String) request.getParameter("iDisplayLength"));
+		}
+				
+		if (iDisplayLength==0)
+			iDisplayLength = 10;
+			
+		if(request.getParameter("iSortCol_0")!=null) {
+			iSortCol_0 = DataFormatter.getInstance().parseIndice((String) request.getParameter("iSortCol_0"));
+		}
+		
+		if(request.getParameter("sSortDir_0")!=null) {
+			sSortDir_0 =request.getParameter("sSortDir_0");
+		}
+		
+		extractGridColumns(request);
+	}
+	
+	private void extractGridColumns(HttpServletRequest request) {
+		//columns.clear();// = null;
+		//columns = new ArrayList<String>();
+		String sColumns=request.getParameter("sColumns");
+		columns = Arrays.asList(sColumns.split("\\s*,\\s*"));
+	}
+
+	public boolean resolveParameters(HttpServletRequest request){
+		setsEcho(request);
+		extractGridPrams(request);
+		rowCount = new MutableHolder<Integer>(0);
+		if (items!=null)
+			items.clear();
+
+		return true;
+	}
+
+	public abstract List<T> generateData(MutableHolder<Integer> rowCount);
+	
+	public DataTable renderData() {
+		DataTable res = new DataTable();
+		res.setsEcho(sEcho);
+		res.setiTotalDisplayRecords(rowCount.value);
+		res.setiTotalRecords(rowCount.value);
+		
+		for(T t: items) {
+			res.createNewRow();
+			for(String column:columns) {
+				Object colValue = resolve(t, column);
+				if (colValue != null)
+					res.addToRow(colValue);
+				else
+					res.addToRow("");
+			}
+			res.commitRow();
+		}
+		return res;
+	};
+	
+	@SuppressWarnings("unchecked")
+	private Object resolve(T t, String column) {
+		
+		BeanWrapper tWrapper = new BeanWrapperImpl(t);
+  
+		try {
+			return tWrapper.convertIfNecessary(tWrapper.getPropertyValue(column), tWrapper.getPropertyType(column));
+		} catch (NullValueInNestedPathException e) {
+			return "";
+		}
+
+	}
+
+	public DataTable sendDataToClient(HttpServletRequest request) {
+		DataTable res = null;
+		if (resolveParameters(request)) {
+			generateData(rowCount);
+			res = renderData();
+		}
+		return res;
+	}
+	
+}
+

+ 128 - 0
src/main/java/commons/controller/grid/DataTable.java

@@ -0,0 +1,128 @@
+package commons.controller.grid;
+
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.List;
+
+public class DataTable {
+
+	
+	private int sEcho;
+	private int iTotalRecords;
+	private int iTotalDisplayRecords;
+
+	private List<List<String>> aaData;
+
+	private List<String> row;
+	
+	public DataTable() {
+		aaData = new ArrayList<List<String>>();
+	}
+	
+	public int getsEcho() {
+		return sEcho;
+	}
+
+	public void setsEcho(int sEcho) {
+		this.sEcho = sEcho;
+	}
+
+	public int getiTotalRecords() {
+		return iTotalRecords;
+	}
+
+	public void setiTotalRecords(int iTotalRecords) {
+		this.iTotalRecords = iTotalRecords;
+	}
+
+	public int getiTotalDisplayRecords() {
+		return iTotalDisplayRecords;
+	}
+
+	public void setiTotalDisplayRecords(int iTotalDisplayRecords) {
+		this.iTotalDisplayRecords = iTotalDisplayRecords;
+	}
+
+	public List<List<String>> getAaData() {
+		return aaData;
+	}
+
+	public void setAaData(List<List<String>> aaData) {
+		this.aaData = aaData;
+	}
+	
+	public void clearData() {
+		aaData.clear();
+	}
+	
+	public void addToData(List<String> dataToAdd) {
+		aaData.add(dataToAdd);
+	}
+	
+	public void createNewRow(){
+		row = new ArrayList<String>();
+	}
+	
+	public void addToRow(Object colValue) {
+		if (Integer.class.isAssignableFrom(colValue.getClass()))
+			addToRow((Integer)colValue);
+		else if (Long.class.isAssignableFrom(colValue.getClass()))
+			addToRow((Long)colValue);
+		else if (String.class.isAssignableFrom(colValue.getClass()))
+			addToRow((String)colValue);
+		else if (Date.class.isAssignableFrom(colValue.getClass()))
+			addToRow((Date)colValue);
+		else if (Calendar.class.isAssignableFrom(colValue.getClass()))
+			addToRow((Calendar)colValue);
+		else addToRow((String)colValue.toString());
+	}
+
+	public void addToRow(Integer value) {
+		row.add(value.toString());
+	}
+
+	public void addToRow(Long value) {
+		row.add(value.toString());
+	}
+
+	public void addToRow(Date value) {
+		row.add(DataTable.formatDate(value));
+	}
+
+	public void addToRow(Calendar value) {
+		row.add(DataTable.formatDate(value));
+	}
+
+	public void addToRow(String value) {
+		row.add(value);
+	}
+
+	public void commitRow() {
+		aaData.add(row);
+	}
+	
+	public static String formatDate(Calendar date) {
+		SimpleDateFormat dtFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
+		String res ="";
+		if (date!=null)
+			res = dtFormat.format(date.getTime());
+		return res;
+	}
+
+	public static String formatDate(Date date) {
+		SimpleDateFormat dtFormat = new SimpleDateFormat("dd/MM/yyyy");
+		String res ="";
+		if (date!=null)
+			res = dtFormat.format(date.getTime());
+		return res;
+	}
+	
+	public static String formatString(String str) {
+		if (str==null)
+			return "";
+		else
+			return str;
+	}
+}

+ 58 - 0
src/main/java/commons/controller/grid/DataTablesWrapper.java

@@ -0,0 +1,58 @@
+package commons.controller.grid;
+
+import java.io.IOException;
+import java.util.List;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+public class DataTablesWrapper<T> {
+    private List<T> aaData;
+    private int iTotalRecords;
+    private int iTotalDisplayRecords;
+    private int sEcho;
+    private  Boolean success;
+
+    public List<T> getAaData() {
+	  return aaData;
+	 }
+	 public void setAaData(List<T> aaData) {
+	  this.aaData = aaData;
+	 }
+	 public int getiTotalRecords() {
+	  return iTotalRecords;
+	 }
+	 public void setiTotalRecords(int iTotalRecords) {
+	  this.iTotalRecords = iTotalRecords;
+	 }
+	 public int getiTotalDisplayRecords() {
+	  return iTotalDisplayRecords;
+	 }
+	 public void setiTotalDisplayRecords(int iTotalDisplayRecords) {
+	  this.iTotalDisplayRecords = iTotalDisplayRecords;
+	 }
+	 public Boolean getSuccess() {
+	  return success;
+	 }
+	 public void setSuccess(Boolean success) {
+	  this.success = success;
+	 }
+	public int getsEcho() {
+		return sEcho;
+	}
+	public void setsEcho(int sEcho) {
+		this.sEcho = sEcho;
+	}   
+	
+	public String toJson() throws IOException{
+		  ObjectMapper mapper = new ObjectMapper();
+		  try {
+		   return mapper.writeValueAsString(this);
+		  } catch (JsonProcessingException e) {
+		   // TODO Auto-generated catch block
+		   e.printStackTrace();
+		   return null;
+		  }
+		 }
+
+}

+ 16 - 0
src/main/java/commons/controller/grid/IGridController.java

@@ -0,0 +1,16 @@
+package commons.controller.grid;
+
+import java.util.List;
+
+import jakarta.servlet.http.HttpServletRequest;
+import commons.utility.MutableHolder;
+
+import org.springframework.web.bind.annotation.ResponseBody;
+
+public interface IGridController<T> {
+	void setsEcho(HttpServletRequest request);
+	boolean resolveParameters(HttpServletRequest request);
+	List<T> generateData(MutableHolder<Integer> rowCount);
+	DataTable renderData();
+	@ResponseBody DataTable sendDataToClient(HttpServletRequest request);
+}

+ 64 - 0
src/main/java/commons/enumerate/AllineamentoCampoSpool_e.java

@@ -0,0 +1,64 @@
+/*
+ * Creato il 15-nov-04
+ */
+package commons.enumerate;
+
+
+public class AllineamentoCampoSpool_e extends Enumerate
+{
+	/**
+     * Comment for <code>serialVersionUID</code>
+     */
+    private static final long serialVersionUID = 1L;
+    
+    public final static class Values
+	{
+		public static final byte NULLO = 0;
+		public static final byte DESTRA = 1;
+		public static final byte SINISTRA = 2;
+		public static final byte CENTRATO = 3;
+	}
+
+	public final static AllineamentoCampoSpool_e NULLO;
+	public final static AllineamentoCampoSpool_e DESTRA;
+	public final static AllineamentoCampoSpool_e SINISTRA;
+	public final static AllineamentoCampoSpool_e CENTRATO;
+
+	private static final AllineamentoCampoSpool_e[] m_values;
+	static
+	{
+		NULLO = new AllineamentoCampoSpool_e("Nullo", Values.NULLO);
+		DESTRA = new AllineamentoCampoSpool_e("Destra", Values.DESTRA);
+		SINISTRA = new AllineamentoCampoSpool_e("Sinistra", Values.SINISTRA);
+		CENTRATO = new AllineamentoCampoSpool_e("Centrato", Values.CENTRATO);
+				
+		m_values = new AllineamentoCampoSpool_e[]
+		{
+			NULLO,
+			DESTRA,
+			SINISTRA,
+			CENTRATO,
+		};
+	}
+	AllineamentoCampoSpool_e(String name, int value)
+	{
+		super(name, value);
+	}
+	public static AllineamentoCampoSpool_e getValue(int value)
+	{
+		return (AllineamentoCampoSpool_e)Enumerate.getValue(AllineamentoCampoSpool_e.class, value);
+	}
+	public static AllineamentoCampoSpool_e getValue(String value)
+	{
+		return (AllineamentoCampoSpool_e)Enumerate.getValue(AllineamentoCampoSpool_e.class, value);
+	}
+	public static final Enumerate[] values()
+	{
+		Enumerate[] arrayEnum = new Enumerate[m_values.length];
+		for (int i = 0; i < m_values.length; i++)
+		{
+			arrayEnum[i] = m_values[i];
+		}
+		return arrayEnum;
+	}
+}

+ 173 - 0
src/main/java/commons/enumerate/Enumerate.java

@@ -0,0 +1,173 @@
+package commons.enumerate;
+
+import java.io.Serializable;
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+
+
+public class Enumerate implements Comparable,Serializable {
+
+	private static final long serialVersionUID = 1L;
+	private int m_ordinal;
+	private String m_name;
+
+	public Enumerate(){
+	}
+
+	protected Enumerate(String name, int ordinal) {
+		m_ordinal = ordinal;
+		m_name = name;
+	}
+
+	private void checkClass(Class other)
+	{
+		if(!other.equals(getClass()))
+		{
+			throw new ClassCastException("Couldn't compare a " + other.getClass() + " to " + this.getClass());
+		}
+	}
+
+	public int compareTo(Object o) {
+		checkClass(o.getClass());
+		return ((Enumerate) o).getOrdinal() - getOrdinal();
+	}
+
+    @Override
+	public boolean equals(Object o) {
+		if(null == o){
+			return false;
+		}
+		if(o instanceof String)
+			return getName().equals(o);
+
+		if(o.getClass().equals(getClass()))
+			return equals(((Enumerate)o).getOrdinal());
+
+		return super.equals(o);
+	}
+
+	public boolean equals(int value) {
+		return getOrdinal() == value;
+	}
+
+	public String getName() {
+		return m_name;
+	}
+
+	public byte getOrdinal() {
+		return (byte)m_ordinal;
+	}
+
+	private static Enumerate getNullValue(Class theClass) throws NullPointerException
+	{
+		//	Cerca il campo marcato con il nome di NULLO
+		Field fields[] = theClass.getFields();
+		for (int i = 0; i < fields.length; i++)
+		{
+			Field field = fields[i];
+			if(field.getName().equalsIgnoreCase("NULLO"))
+			{
+				try
+				{
+					return (Enumerate)field.get(null);
+				}
+				catch (IllegalArgumentException e)	{}
+				catch (IllegalAccessException e)	{}
+			}
+		}
+		throw new NullPointerException("Object NULLO not found in class " + theClass.getName());
+	}
+
+	/**
+	 * @param nclass La classe enumerata su cui fare la ricerca
+	 * @param b Il valore dell'ordinale da ricercare
+	 * @return Il valore dell'enumerato,null se non esiste
+	 */
+	public static Enumerate getValue(Class nclass, int b)
+	{
+		try {
+			Method metodo = nclass.getMethod("values", (Class[])null);
+			Enumerate[] enums = (Enumerate[]) metodo.invoke(null, (Object[])null);
+
+			for (int i = 0; i < enums.length; i++) {
+				if (enums[i].getOrdinal() == b) {
+					return enums[i];
+				}
+			}
+
+
+			return getNullValue(nclass);
+
+		} catch (SecurityException e) {
+			throw new InvalidEnumerateException(nclass);
+		} catch (IllegalArgumentException e) {
+			throw new InvalidEnumerateException(nclass);
+		} catch (NoSuchMethodException e) {
+			throw new InvalidEnumerateException(nclass);
+		} catch (IllegalAccessException e) {
+			throw new InvalidEnumerateException(nclass);
+		} catch (InvocationTargetException e) {
+			throw new InvalidEnumerateException(nclass);
+		}
+	}
+
+	/**
+	 * @param nclass La classe enumerata su cui fare la ricerca
+	 * @param b Il valore testuale su cui fare la ricerca;se ? un valore numerico in formato
+	 * 			stringa allora viene usata la versione di ricerca sull'ordinale,altrimenti quella
+	 * 			di ricerca sul nome
+	 * @return Il valore dell'enumerato,null se non esiste
+	 */
+	public static Enumerate getValue(Class theClass,String value)
+	{
+		try
+		{
+			//	Se la stringa ? un numero allora utilizza la versione che ricerca l'ordinale
+			return getValue(theClass,Integer.parseInt(value));
+		}
+		catch(NumberFormatException nfe)
+		{
+		}
+
+		try
+		{
+			Method metodo = theClass.getMethod("values", (Class[])null);
+			Enumerate[] enums = (Enumerate[]) metodo.invoke(null, (Object[])null);
+
+			for (int i = 0; i < enums.length; i++) {
+				if (enums[i].getName().equals(value)) {
+					return enums[i];
+				}
+			}
+
+			return getNullValue(theClass);
+
+		} catch (SecurityException e) {
+			throw new InvalidEnumerateException(theClass);
+		} catch (IllegalArgumentException e) {
+			throw new InvalidEnumerateException(theClass);
+		} catch (NoSuchMethodException e) {
+			throw new InvalidEnumerateException(theClass);
+		} catch (IllegalAccessException e) {
+			throw new InvalidEnumerateException(theClass);
+		} catch (InvocationTargetException e) {
+			throw new InvalidEnumerateException(theClass);
+		}
+	}
+
+    @Override
+	public String toString(){
+		return String.valueOf(getOrdinal());
+	}
+
+	@Override
+	public int hashCode()
+	{
+		final int PRIME = 31;
+		int result = 1;
+		result = PRIME * result + new Integer(m_ordinal).hashCode();
+
+		return result;
+	}
+}

+ 14 - 0
src/main/java/commons/enumerate/InvalidEnumerateException.java

@@ -0,0 +1,14 @@
+package commons.enumerate;
+
+
+public class InvalidEnumerateException extends RuntimeException {
+	
+	/**
+     * Comment for <code>serialVersionUID</code>
+     */
+    private static final long serialVersionUID = 1L;
+
+    public InvalidEnumerateException(Class classe){
+		super(classe.toString() + "is not a valid enumerate. lacks values() method");
+	}
+}

+ 47 - 0
src/main/java/commons/enumerate/Mese_e.java

@@ -0,0 +1,47 @@
+package commons.enumerate;
+
+import java.util.EnumMap;
+
+public enum Mese_e
+{
+	NULLO(""),
+	GENNAIO("Gennaio"),
+	FEBBRAIO("Febbraio"),
+	MARZO("Marzo"),
+	APRILE("Aprile"),
+	MAGGIO("Maggio"),
+	GIUGNO("Giugno"),
+	LUGLIO("Luglio"),
+	AGOSTO("Agosto"),
+	SETTEMBRE("Settembre"),
+	OTTOBRE("Ottobre"),
+	NOVEMBRE("Novembre"),
+	DICEMBRE("Dicembre");
+	
+	public static EnumMap<Mese_e, String> descriptions = new 
+	EnumMap<Mese_e, String>(
+			Mese_e.class);
+
+	static
+	{
+		for(Mese_e e : Mese_e.values())
+			descriptions.put(e,e.description);
+	}
+	
+	private String description;
+	private Integer drOrdinal;
+	
+	private Mese_e(String dsc)
+	{
+		this(dsc,null);
+	}
+	
+	private Mese_e(String dsc,Integer drOrdinal)
+	{
+		this.description = dsc;
+		this.drOrdinal = drOrdinal;
+	}
+	
+	public final String getDescription()	{	return description;	}
+	public final int getDrOrdinal()		{	return null == drOrdinal ? ordinal() : drOrdinal;	}
+}

+ 46 - 0
src/main/java/commons/enumerate/OrdinamentoRicercaComuni_e.java

@@ -0,0 +1,46 @@
+package commons.enumerate;
+
+import java.util.EnumMap;
+
+public enum OrdinamentoRicercaComuni_e {
+	
+	NULLO(""),
+	DESCRIZIONE("Descrizione");
+	
+	public static EnumMap<OrdinamentoRicercaComuni_e, String> descriptions = new 
+	EnumMap<OrdinamentoRicercaComuni_e, String>(
+			OrdinamentoRicercaComuni_e.class);
+
+	static
+	{
+		for(OrdinamentoRicercaComuni_e e : OrdinamentoRicercaComuni_e.values())
+			descriptions.put(e,e.description);
+	}
+	
+	private String description;
+	private Integer drOrdinal;
+	
+	private OrdinamentoRicercaComuni_e(String dsc)
+	{
+		this(dsc,null);
+	}
+	
+	private OrdinamentoRicercaComuni_e(String dsc,Integer drOrdinal)
+	{
+		this.description = dsc;
+		this.drOrdinal = drOrdinal;
+	}
+	
+	public final String getDescription()	{	return description;	}
+	public final int getDrOrdinal()		{	return null == drOrdinal ? ordinal() : drOrdinal;	}
+	
+	public static final OrdinamentoRicercaComuni_e getValue(int ordinal)
+	{
+		for (OrdinamentoRicercaComuni_e stato : OrdinamentoRicercaComuni_e.values()) {
+			if (stato.ordinal() == ordinal)
+				return stato;
+		} 
+		return OrdinamentoRicercaComuni_e.DESCRIZIONE;
+	}
+
+}

+ 39 - 0
src/main/java/commons/enumerate/OrdinamentoRicercaFrazione_e.java

@@ -0,0 +1,39 @@
+package commons.enumerate;
+
+import java.util.EnumMap;
+
+public enum OrdinamentoRicercaFrazione_e {
+
+    NULLO(""),
+	DESCRIZIONE("Descrizione"),
+	CAP("Cap");
+	
+	public static EnumMap<OrdinamentoRicercaFrazione_e, String> descriptions = new 
+	EnumMap<OrdinamentoRicercaFrazione_e, String>(
+			OrdinamentoRicercaFrazione_e.class);
+
+	static
+	{
+		for(OrdinamentoRicercaFrazione_e e : OrdinamentoRicercaFrazione_e.values())
+			descriptions.put(e,e.description);
+	}
+	
+	private String description;
+	private Integer drOrdinal;
+	
+	private OrdinamentoRicercaFrazione_e(String dsc)
+	{
+		this(dsc,null);
+	}
+	
+	private OrdinamentoRicercaFrazione_e(String dsc,Integer drOrdinal)
+	{
+		this.description = dsc;
+		this.drOrdinal = drOrdinal;
+	}
+	
+	public final String getDescription()	{	return description;	}
+	public final int getDrOrdinal()		{	return null == drOrdinal ? ordinal() : drOrdinal;	}
+	
+	
+}

+ 46 - 0
src/main/java/commons/enumerate/OrdinamentoRicercaProvince_e.java

@@ -0,0 +1,46 @@
+package commons.enumerate;
+
+import java.util.EnumMap;
+
+public enum OrdinamentoRicercaProvince_e {
+	
+	CODICE("Codice"),
+	DESCRIZIONE("Descrizione");
+	
+	public static EnumMap<OrdinamentoRicercaProvince_e, String> descriptions = new 
+	EnumMap<OrdinamentoRicercaProvince_e, String>(
+			OrdinamentoRicercaProvince_e.class);
+
+	static
+	{
+		for(OrdinamentoRicercaProvince_e e : OrdinamentoRicercaProvince_e.values())
+			descriptions.put(e,e.description);
+	}
+	
+	private String description;
+	private Integer drOrdinal;
+	
+	private OrdinamentoRicercaProvince_e(String dsc)
+	{
+		this(dsc,null);
+	}
+	
+	private OrdinamentoRicercaProvince_e(String dsc,Integer drOrdinal)
+	{
+		this.description = dsc;
+		this.drOrdinal = drOrdinal;
+	}
+	
+	public final String getDescription()	{	return description;	}
+	public final int getDrOrdinal()		{	return null == drOrdinal ? ordinal() : drOrdinal;	}
+	
+	public static final OrdinamentoRicercaProvince_e getValue(int ordinal)
+	{
+		for (OrdinamentoRicercaProvince_e stato : OrdinamentoRicercaProvince_e.values()) {
+			if (stato.ordinal() == ordinal)
+				return stato;
+		} 
+		return OrdinamentoRicercaProvince_e.CODICE;
+	}
+
+}

+ 46 - 0
src/main/java/commons/enumerate/OrdinamentoRicercaRegioni_e.java

@@ -0,0 +1,46 @@
+package commons.enumerate;
+
+import java.util.EnumMap;
+
+public enum OrdinamentoRicercaRegioni_e {
+	
+	CODICE("Codice"),
+	DESCRIZIONE("Descrizione");
+	
+	public static EnumMap<OrdinamentoRicercaRegioni_e, String> descriptions = new 
+	EnumMap<OrdinamentoRicercaRegioni_e, String>(
+			OrdinamentoRicercaRegioni_e.class);
+
+	static
+	{
+		for(OrdinamentoRicercaRegioni_e e : OrdinamentoRicercaRegioni_e.values())
+			descriptions.put(e,e.description);
+	}
+	
+	private String description;
+	private Integer drOrdinal;
+	
+	private OrdinamentoRicercaRegioni_e(String dsc)
+	{
+		this(dsc,null);
+	}
+	
+	private OrdinamentoRicercaRegioni_e(String dsc,Integer drOrdinal)
+	{
+		this.description = dsc;
+		this.drOrdinal = drOrdinal;
+	}
+	
+	public final String getDescription()	{	return description;	}
+	public final int getDrOrdinal()		{	return null == drOrdinal ? ordinal() : drOrdinal;	}
+	
+	public static final OrdinamentoRicercaRegioni_e getValue(int ordinal)
+	{
+		for (OrdinamentoRicercaRegioni_e stato : OrdinamentoRicercaRegioni_e.values()) {
+			if (stato.ordinal() == ordinal)
+				return stato;
+		} 
+		return OrdinamentoRicercaRegioni_e.CODICE;
+	}
+
+}

+ 40 - 0
src/main/java/commons/enumerate/OrdinamentoRicercaStradario_e.java

@@ -0,0 +1,40 @@
+package commons.enumerate;
+
+import java.util.EnumMap;
+
+public enum OrdinamentoRicercaStradario_e {
+	
+	NOME_STRADA("nomeStrada"),
+    CAP("CAP"),
+    TIPOLOGIA("Tipologia"),
+    QUARTIERE("Quartiere");
+	
+	public static EnumMap<OrdinamentoRicercaStradario_e, String> descriptions = new 
+	EnumMap<OrdinamentoRicercaStradario_e, String>(
+			OrdinamentoRicercaStradario_e.class);
+
+	static
+	{
+		for(OrdinamentoRicercaStradario_e e : OrdinamentoRicercaStradario_e.values())
+			descriptions.put(e,e.description);
+	}
+	
+	private String description;
+	private Integer drOrdinal;
+	
+	private OrdinamentoRicercaStradario_e(String dsc)
+	{
+		this(dsc,null);
+	}
+	
+	private OrdinamentoRicercaStradario_e(String dsc,Integer drOrdinal)
+	{
+		this.description = dsc;
+		this.drOrdinal = drOrdinal;
+	}
+	
+	public final String getDescription()	{	return description;	}
+	public final int getDrOrdinal()		{	return null == drOrdinal ? ordinal() : drOrdinal;	}
+	
+
+}

+ 48 - 0
src/main/java/commons/enumerate/OrdinamentoRicercaTipologiaIndirizzo_e.java

@@ -0,0 +1,48 @@
+package commons.enumerate;
+
+import java.util.EnumMap;
+
+public enum OrdinamentoRicercaTipologiaIndirizzo_e {
+	
+	CODICE_CATASTALE("Codice catastale"),
+	DESCRIZIONE("Descrizione"),
+	PROVINCIA("Provincia"),
+	CAP("Cap");
+	
+	public static EnumMap<OrdinamentoRicercaTipologiaIndirizzo_e, String> descriptions = new 
+	EnumMap<OrdinamentoRicercaTipologiaIndirizzo_e, String>(
+			OrdinamentoRicercaTipologiaIndirizzo_e.class);
+
+	static
+	{
+		for(OrdinamentoRicercaTipologiaIndirizzo_e e : OrdinamentoRicercaTipologiaIndirizzo_e.values())
+			descriptions.put(e,e.description);
+	}
+	
+	private String description;
+	private Integer drOrdinal;
+	
+	private OrdinamentoRicercaTipologiaIndirizzo_e(String dsc)
+	{
+		this(dsc,null);
+	}
+	
+	private OrdinamentoRicercaTipologiaIndirizzo_e(String dsc,Integer drOrdinal)
+	{
+		this.description = dsc;
+		this.drOrdinal = drOrdinal;
+	}
+	
+	public final String getDescription()	{	return description;	}
+	public final int getDrOrdinal()		{	return null == drOrdinal ? ordinal() : drOrdinal;	}
+	
+	public static final OrdinamentoRicercaTipologiaIndirizzo_e getValue(int ordinal)
+	{
+		for (OrdinamentoRicercaTipologiaIndirizzo_e stato : OrdinamentoRicercaTipologiaIndirizzo_e.values()) {
+			if (stato.ordinal() == ordinal)
+				return stato;
+		} 
+		return OrdinamentoRicercaTipologiaIndirizzo_e.DESCRIZIONE;
+	}
+
+}

+ 38 - 0
src/main/java/commons/enumerate/Sesso_e.java

@@ -0,0 +1,38 @@
+package commons.enumerate;
+
+import java.util.EnumMap;
+
+public enum Sesso_e {
+	
+	NULLO(""),
+	MASCHIO("Maschio"),
+	FEMMINA("Femmina");
+	
+	public static EnumMap<Sesso_e, String> descriptions = new 
+	EnumMap<Sesso_e, String>(
+			Sesso_e.class);
+
+	static
+	{
+		for(Sesso_e e : Sesso_e.values())
+			descriptions.put(e,e.description);
+	}
+	
+	private String description;
+	private Integer drOrdinal;
+	
+	private Sesso_e(String dsc)
+	{
+		this(dsc,null);
+	}
+	
+	private Sesso_e(String dsc,Integer drOrdinal)
+	{
+		this.description = dsc;
+		this.drOrdinal = drOrdinal;
+	}
+	
+	public final String getDescription()	{	return description;	}
+	public final int getDrOrdinal()		{	return null == drOrdinal ? ordinal() : drOrdinal;	}
+
+}

+ 47 - 0
src/main/java/commons/enumerate/TipoOrdinamentoRicerca_e.java

@@ -0,0 +1,47 @@
+package commons.enumerate;
+
+import java.util.EnumMap;
+
+public enum TipoOrdinamentoRicerca_e {
+	
+	NULLO(""),
+	ASC("ASC"),
+	DESC("DESC");
+	
+	public static EnumMap<TipoOrdinamentoRicerca_e, String> descriptions = new 
+	EnumMap<TipoOrdinamentoRicerca_e, String>(
+			TipoOrdinamentoRicerca_e.class);
+
+	static
+	{
+		for(TipoOrdinamentoRicerca_e e : TipoOrdinamentoRicerca_e.values())
+			descriptions.put(e,e.description);
+	}
+	
+	private String description;
+	private Integer drOrdinal;
+	
+	private TipoOrdinamentoRicerca_e(String dsc)
+	{
+		this(dsc,null);
+	}
+	
+	private TipoOrdinamentoRicerca_e(String dsc,Integer drOrdinal)
+	{
+		this.description = dsc;
+		this.drOrdinal = drOrdinal;
+	}
+	
+	public final String getDescription()	{	return description;	}
+	public final int getDrOrdinal()		{	return null == drOrdinal ? ordinal() : drOrdinal;	}
+	
+	public static final TipoOrdinamentoRicerca_e getValue(int ordinal)
+	{
+		for (TipoOrdinamentoRicerca_e stato : TipoOrdinamentoRicerca_e.values()) {
+			if (stato.ordinal() == ordinal)
+				return stato;
+		} 
+		return TipoOrdinamentoRicerca_e.NULLO;
+	}
+
+}

+ 39 - 0
src/main/java/commons/enumerate/TipoPeriodoAbbonamento_e.java

@@ -0,0 +1,39 @@
+package commons.enumerate;
+
+import java.util.EnumMap;
+
+public enum TipoPeriodoAbbonamento_e {
+	
+	NULLO(""),
+	GIORNI("Giorni"),
+	MESI("Mesi"),
+	ANNI("Anni");
+	
+	public static EnumMap<TipoPeriodoAbbonamento_e, String> descriptions = new 
+	EnumMap<TipoPeriodoAbbonamento_e, String>(
+			TipoPeriodoAbbonamento_e.class);
+
+	static
+	{
+		for(TipoPeriodoAbbonamento_e e : TipoPeriodoAbbonamento_e.values())
+			descriptions.put(e,e.description);
+	}
+	
+	private String description;
+	private Integer drOrdinal;
+	
+	private TipoPeriodoAbbonamento_e(String dsc)
+	{
+		this(dsc,null);
+	}
+	
+	private TipoPeriodoAbbonamento_e(String dsc,Integer drOrdinal)
+	{
+		this.description = dsc;
+		this.drOrdinal = drOrdinal;
+	}
+	
+	public final String getDescription()	{	return description;	}
+	public final int getDrOrdinal()		{	return null == drOrdinal ? ordinal() : drOrdinal;	}
+
+}

+ 47 - 0
src/main/java/commons/enumerate/TipoResponseAJAX_e.java

@@ -0,0 +1,47 @@
+package commons.enumerate;
+
+import java.util.EnumMap;
+
+public enum TipoResponseAJAX_e {
+	
+	NULLO(""),
+	XML("XML"),
+	JSON("JSON"),
+	TEXT("Text");
+	
+	public static EnumMap<TipoResponseAJAX_e, String> descriptions = new 
+	EnumMap<TipoResponseAJAX_e, String>(
+			TipoResponseAJAX_e.class);
+
+	static
+	{
+		for(TipoResponseAJAX_e e : TipoResponseAJAX_e.values())
+			descriptions.put(e,e.description);
+	}
+	
+	private String description;
+	private Integer drOrdinal;
+	
+	private TipoResponseAJAX_e(String dsc)
+	{
+		this(dsc,null);
+	}
+	
+	private TipoResponseAJAX_e(String dsc,Integer drOrdinal)
+	{
+		this.description = dsc;
+		this.drOrdinal = drOrdinal;
+	}
+	
+	public final String getDescription()	{	return description;	}
+	public final int getDrOrdinal()		{	return null == drOrdinal ? ordinal() : drOrdinal;	}
+	
+	public static final TipoResponseAJAX_e getValue(int ordinal)
+	{
+		for (TipoResponseAJAX_e stato : TipoResponseAJAX_e.values()) {
+			if (stato.ordinal() == ordinal)
+				return stato;
+		} 
+		return TipoResponseAJAX_e.NULLO;
+	}
+}

+ 49 - 0
src/main/java/commons/enumerate/TipoRichiestaAJAX_e.java

@@ -0,0 +1,49 @@
+package commons.enumerate;
+
+import java.util.EnumMap;
+
+public enum TipoRichiestaAJAX_e {
+	
+	NULLO(""),
+	LOGIN("Login"),
+	REGISTRAZIONE("Registrazione");
+	
+	public static EnumMap<TipoRichiestaAJAX_e, String> descriptions = new 
+	EnumMap<TipoRichiestaAJAX_e, String>(
+			TipoRichiestaAJAX_e.class);
+
+	static
+	{
+		for(TipoRichiestaAJAX_e e : TipoRichiestaAJAX_e.values())
+			descriptions.put(e,e.description);
+	}
+	
+	private String description;
+	private Integer drOrdinal;
+	
+	private TipoRichiestaAJAX_e(String dsc)
+	{
+		this(dsc,null);
+	}
+	
+	private TipoRichiestaAJAX_e(String dsc,Integer drOrdinal)
+	{
+		this.description = dsc;
+		this.drOrdinal = drOrdinal;
+	}
+	
+	public final String getDescription()	{	return description;	}
+	public final int getDrOrdinal()		{	return null == drOrdinal ? ordinal() : drOrdinal;	}
+	
+	
+	public static final TipoRichiestaAJAX_e getValue(int ordinal)
+	{
+		for (TipoRichiestaAJAX_e stato : TipoRichiestaAJAX_e.values()) {
+			if (stato.ordinal() == ordinal)
+				return stato;
+		} 
+		return TipoRichiestaAJAX_e.NULLO;
+	}
+
+
+}

+ 12 - 0
src/main/java/commons/exception/ExceptionUtils.java

@@ -0,0 +1,12 @@
+package commons.exception;
+
+
+public class ExceptionUtils {
+
+	public static Throwable findRootCause(Exception excp) {		
+		Throwable rootCause = org.apache.commons.lang.exception.ExceptionUtils.getRootCause(excp);
+		if (rootCause == null) rootCause = excp;
+		return rootCause;
+	}
+	
+}

+ 35 - 0
src/main/java/commons/exception/WebException.java

@@ -0,0 +1,35 @@
+package commons.exception;
+
+
+public class WebException extends Exception
+{
+	/**
+     * Comment for <code>serialVersionUID</code>
+     */
+    private static final long serialVersionUID = 1L;
+
+    public WebException()
+	{
+		super();
+	}
+	
+	public WebException(Exception e)
+	{
+		super(e);
+	}
+	
+	public WebException(String message)
+	{
+		super(message);
+	}
+	
+	public WebException(String message, Throwable cause)
+	{
+		super(message, cause);
+	}
+
+	public WebException(Throwable cause)
+	{
+		super(cause);
+	}
+}

+ 51 - 0
src/main/java/commons/exception/WebValidateActionException.java

@@ -0,0 +1,51 @@
+package commons.exception;
+
+import commons.utility.exception.WebActionException;
+
+
+
+public class WebValidateActionException extends WebActionException
+{
+
+	/**
+     * Comment for <code>serialVersionUID</code>
+     */
+    private static final long serialVersionUID = 1L;
+
+    /**
+	 * @param action
+	 */
+	public WebValidateActionException(String action)
+	{
+		super(action);
+	}
+
+	/**
+	 * @param message
+	 * @param action
+	 */
+	public WebValidateActionException(String message, String action)
+	{
+		super(message, action);
+	}
+
+	/**
+	 * @param message
+	 * @param cause
+	 * @param action
+	 */
+	public WebValidateActionException(String message, Throwable cause, String action)
+	{
+		super(message, cause, action);
+	}
+
+	/**
+	 * @param cause
+	 * @param action
+	 */
+	public WebValidateActionException(Throwable cause, String action)
+	{
+		super(cause, action);
+	}
+
+}

+ 44 - 0
src/main/java/commons/exception/ZApplicationException.java

@@ -0,0 +1,44 @@
+package commons.exception;
+
+public class ZApplicationException extends Exception
+{
+
+	/**
+     * Comment for <code>serialVersionUID</code>
+     */
+    private static final long serialVersionUID = 1L;
+
+    /**
+	 * 
+	 */
+	public ZApplicationException()
+	{
+		super();
+	}
+
+	/**
+	 * @param message
+	 */
+	public ZApplicationException(String message)
+	{
+		super(message);
+	}
+
+	/**
+	 * @param message
+	 * @param cause
+	 */
+	public ZApplicationException(String message, Throwable cause)
+	{
+		super(message, cause);
+	}
+
+	/**
+	 * @param cause
+	 */
+	public ZApplicationException(Throwable cause)
+	{
+		super(cause);
+	}
+
+}

+ 29 - 0
src/main/java/commons/exception/ZCompressException.java

@@ -0,0 +1,29 @@
+package commons.exception;
+
+import java.io.IOException;
+import java.util.zip.DataFormatException;
+
+
+
+public class ZCompressException extends ZSystemException
+{
+	/**
+     * Comment for <code>serialVersionUID</code>
+     */
+    private static final long serialVersionUID = 1L;
+
+    public ZCompressException(String message)
+	{
+		super(message);
+	}
+	
+	public ZCompressException(IOException e)
+	{
+		super(e);
+	}
+
+	public ZCompressException(DataFormatException e)
+	{
+		super(e);
+	}
+}

+ 19 - 0
src/main/java/commons/exception/ZCryptoException.java

@@ -0,0 +1,19 @@
+package commons.exception;
+
+
+
+public class ZCryptoException extends ZSystemException {
+	
+	/**
+     * Comment for <code>serialVersionUID</code>
+     */
+    private static final long serialVersionUID = 1L;
+
+    public ZCryptoException() {
+		super("Generici crypto error");
+	}
+	
+	public ZCryptoException(String message) {
+		super(message);
+	}
+}

+ 27 - 0
src/main/java/commons/exception/ZDataBaseException.java

@@ -0,0 +1,27 @@
+package commons.exception;
+
+import java.sql.SQLException;
+
+import javax.naming.NamingException;
+
+
+public class ZDataBaseException extends ZSystemException {
+	/**
+     * Comment for <code>serialVersionUID</code>
+     */
+    private static final long serialVersionUID = 1L;
+    
+    public ZDataBaseException(SQLException e) {
+		super(e);
+	}
+	public ZDataBaseException(NamingException e) {
+		super(e);
+	}
+	public ZDataBaseException(String e) {
+		super(e);
+	}
+	public ZDataBaseException(Exception e)
+	{
+		super(e);
+	}
+}

+ 72 - 0
src/main/java/commons/exception/ZDbUpdateException.java

@@ -0,0 +1,72 @@
+package commons.exception;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+
+public class ZDbUpdateException extends ZSystemException {
+
+	/**
+     * Comment for <code>serialVersionUID</code>
+     */
+    private static final long serialVersionUID = 1L;
+    
+    public List<Error> ex;
+
+	public ZDbUpdateException() {
+		ex = new ArrayList<Error>();
+	}
+	
+	public ZDbUpdateException(Throwable e) {
+		this();
+		addStackTrace(e);
+	}
+	
+	public void addStackTrace(Throwable e) {
+		Error e1 = new Error();
+		e1.setStackTrace(e.getStackTrace());
+		e1.setMessage(" "+e.getMessage()+"\t-->\t"+e.getClass());
+		ex.add(e1);
+	}
+
+	public String getCompleteStackTrace() {
+		StringBuffer sb = new StringBuffer();
+		for (Iterator iter = ex.iterator(); iter.hasNext();) {
+			Error element = (Error)iter.next();
+			sb.append(element.getMessage() + "\n");
+			StackTraceElement[] st = element.getStackTrace();
+			for (int i = 0;i<st.length;++i){
+				sb.append(printST(st[i]));
+			}
+		}
+		return sb.toString();
+	}
+
+	private String printST(StackTraceElement trace) {
+		String rsl = "\tat "+trace.getClassName()+"."+trace.getMethodName()+"("+trace.getFileName()+".java:"+trace.getLineNumber()+")\n";
+		return rsl;
+	}
+}
+
+class Error {
+	private StackTraceElement[] stackTrace;
+	private String message = "";
+
+	public String getMessage() {
+		return message;
+	}
+
+	public StackTraceElement[] getStackTrace() {
+		return stackTrace;
+	}
+
+	public void setMessage(String string) {
+		message = string;
+	}
+
+	public void setStackTrace(StackTraceElement[] elements) {
+		stackTrace = elements;
+	}
+
+}

+ 25 - 0
src/main/java/commons/exception/ZException.java

@@ -0,0 +1,25 @@
+package commons.exception;
+
+public class ZException extends Exception
+{
+	/**
+     * Comment for <code>serialVersionUID</code>
+     */
+    private static final long serialVersionUID = 1L;
+
+    public ZException(Exception e) {
+		super(e);
+	}
+
+	public ZException(Throwable e) {
+		super(e);
+	}
+	
+	public ZException(String message) {
+		super(message);
+	}
+	
+	public ZException() {
+		super();
+	}
+}

+ 11 - 0
src/main/java/commons/exception/ZHbmDuplicateIndexException.java

@@ -0,0 +1,11 @@
+package commons.exception;
+
+public class ZHbmDuplicateIndexException extends ZHbmException {
+
+	private static final long serialVersionUID = 1L;
+
+	public ZHbmDuplicateIndexException(Exception e) {
+		 super(e);     
+	}
+
+}

+ 12 - 0
src/main/java/commons/exception/ZHbmException.java

@@ -0,0 +1,12 @@
+package commons.exception;
+
+
+public class ZHbmException extends ZDataBaseException {
+
+  private static final long serialVersionUID = 1L;
+
+  public ZHbmException(Exception e) {
+     super(e);        
+   }
+
+}

+ 33 - 0
src/main/java/commons/exception/ZMailException.java

@@ -0,0 +1,33 @@
+package commons.exception;
+
+
+
+public class ZMailException extends ZSystemException
+{
+
+	/**
+     * Comment for <code>serialVersionUID</code>
+     */
+    private static final long serialVersionUID = 1L;
+
+    public ZMailException(Exception e)
+	{
+		super(e);
+	}
+
+	public ZMailException(Throwable e)
+	{
+		super(e);
+	}
+
+	public ZMailException(String message)
+	{
+		super(message);
+	}
+
+	public ZMailException()
+	{
+		super();
+	}
+
+}

+ 28 - 0
src/main/java/commons/exception/ZParseException.java

@@ -0,0 +1,28 @@
+package commons.exception;
+
+
+
+public class ZParseException extends ZSystemException
+{
+
+	/**
+     * Comment for <code>serialVersionUID</code>
+     */
+    private static final long serialVersionUID = 1L;
+
+    public ZParseException()
+	{
+		super();
+	}
+
+	public ZParseException(String message)
+	{
+		super(message);
+	}
+
+	public ZParseException(Throwable cause)
+	{
+		super(cause);
+	}
+
+}

+ 35 - 0
src/main/java/commons/exception/ZSistemaException.java

@@ -0,0 +1,35 @@
+package commons.exception;
+
+
+
+public class ZSistemaException extends ZApplicationException
+{
+
+	private static final long serialVersionUID = 1L;
+
+	public ZSistemaException()
+	{
+		super();
+	}
+	
+	public ZSistemaException(String message)
+	{
+		super(message);
+	}
+	
+	public ZSistemaException(Exception e)
+	{
+		super(e);
+	}
+	
+	public ZSistemaException(Throwable e)
+	{
+		super(e);
+	}
+	
+	public ZSistemaException(String message, Throwable cause)
+	{
+		super(message, cause);
+	}
+	
+}

+ 32 - 0
src/main/java/commons/exception/ZSystemException.java

@@ -0,0 +1,32 @@
+package commons.exception;
+
+public class ZSystemException extends RuntimeException
+{
+	private static final long serialVersionUID = 1L;
+
+	public ZSystemException()
+	{
+		super();
+	}
+
+	public ZSystemException(String message)
+	{
+		super(message);
+	}
+
+	public ZSystemException(Exception e)
+	{
+		super(e);
+	}
+
+	public ZSystemException(Throwable e)
+	{
+		super(e);
+	}
+
+	public ZSystemException(String message,
+	                        Throwable cause)
+	{
+		super(message, cause);
+	}
+}

+ 34 - 0
src/main/java/commons/exception/ZTransactionException.java

@@ -0,0 +1,34 @@
+package commons.exception;
+
+
+
+/**
+ * Eccezione legata alle transazioni
+ */
+public class ZTransactionException extends ZSystemException
+{
+	/**
+     * Comment for <code>serialVersionUID</code>
+     */
+    private static final long serialVersionUID = 1L;
+
+    public ZTransactionException(Exception e)
+	{
+		super(e);
+	}
+
+	public ZTransactionException(Throwable e)
+	{
+		super(e);
+	}
+
+	public ZTransactionException(String message)
+	{
+		super(message);
+	}
+
+	public ZTransactionException()
+	{
+		super();
+	}
+}

+ 23 - 0
src/main/java/commons/exception/ZWebException.java

@@ -0,0 +1,23 @@
+package commons.exception;
+
+
+public class ZWebException extends ZApplicationException {
+
+    private static final long serialVersionUID = 1L;
+    
+	public ZWebException() {
+        super();
+    }
+    
+    public ZWebException(String message){
+        super(message);
+    }
+    
+    public ZWebException(Throwable cause, String message) {
+        super(message, cause);
+    }
+    
+    public ZWebException(Throwable cause) {
+        super(cause);
+    }
+}

+ 23 - 0
src/main/java/commons/exception/ZWebSessioneScadutaException.java

@@ -0,0 +1,23 @@
+package commons.exception;
+
+
+public class ZWebSessioneScadutaException extends ZApplicationException {
+
+    private static final long serialVersionUID = 1L;
+    
+	public ZWebSessioneScadutaException() {
+        super();
+    }
+    
+    public ZWebSessioneScadutaException(String message){
+        super(message);
+    }
+    
+    public ZWebSessioneScadutaException(Throwable cause, String message) {
+        super(message, cause);
+    }
+    
+    public ZWebSessioneScadutaException(Throwable cause) {
+        super(cause);
+    }
+}

+ 26 - 0
src/main/java/commons/exception/ZXMLException.java

@@ -0,0 +1,26 @@
+package commons.exception;
+
+
+
+public class ZXMLException extends ZSystemException
+{
+	/**
+     * Comment for <code>serialVersionUID</code>
+     */
+    private static final long serialVersionUID = 1L;
+
+    public ZXMLException()
+	{
+		super();
+	}
+
+    public ZXMLException(Exception e)
+	{
+		super(e);
+	}
+
+	public ZXMLException(String message)
+	{
+		super(message);
+	}
+}

+ 73 - 0
src/main/java/commons/exporters/impl/BaseExporter.java

@@ -0,0 +1,73 @@
+package commons.exporters.impl;
+
+import java.math.RoundingMode;
+import java.text.DecimalFormat;
+import java.text.NumberFormat;
+import java.util.List;
+
+public abstract class BaseExporter<T> {
+
+	protected List<T> dataSet;
+	
+	protected abstract List<T> fetchDataToExport();
+	protected abstract void setFileName();
+	public abstract List<String> getFullFileName();
+	protected abstract void exportRecord(T record);
+	protected String baseFolder;
+	protected String zipFileName;
+	protected abstract boolean createFile();
+	protected abstract void closeFile();
+	
+	public void setBaseFolder(String baseFolder) {
+		this.baseFolder = baseFolder;
+	}
+	
+	public void setFileName(String zipFileName) {
+		this.zipFileName = zipFileName;
+	}
+	
+	public boolean runExport() {
+		boolean res=true;
+		
+		dataSet = fetchDataToExport();
+		setFileName();
+		if (createFile()) {
+			
+			for (T currentRecord:dataSet) {
+				exportRecord(currentRecord);
+			}
+				
+		} else
+			res = false;
+		closeFile();
+		return res;	
+	}
+	
+	protected String formatNum(Float f, int dec) {
+		if (f==null)
+    		return "0";
+        NumberFormat format = DecimalFormat.getInstance();
+        format.setRoundingMode(RoundingMode.FLOOR);
+        format.setGroupingUsed(false);
+       
+        format.setMinimumFractionDigits(dec);
+        format.setMaximumFractionDigits(dec);
+        return format.format(f).replace(",","").replace(".", "");
+        
+    	
+	}
+	
+    protected String formatNumber(Float f) {
+    	if (f==null)
+    		return "0";
+        NumberFormat format = DecimalFormat.getInstance();
+        format.setRoundingMode(RoundingMode.FLOOR);
+        format.setGroupingUsed(false);
+       
+        format.setMinimumFractionDigits(0);
+        format.setMaximumFractionDigits(0);
+        return format.format(f);
+    }
+
+	
+}

+ 11 - 0
src/main/java/commons/exporters/intf/IBaseExporter.java

@@ -0,0 +1,11 @@
+package commons.exporters.intf;
+
+public interface IBaseExporter {
+	public void setFile(String fileName);
+	public boolean openFile();
+	public boolean writeLine();
+	public boolean isFileEnd();
+	public void closeFile();	
+	public void processRecord();
+	public boolean runExport();
+}

+ 5 - 0
src/main/java/commons/exporters/intf/IExportFileProcessor.java

@@ -0,0 +1,5 @@
+package commons.exporters.intf;
+
+public interface IExportFileProcessor {
+		public boolean GenerateUpdateFile(String outputFolder, String outputFileName);
+}

+ 5 - 0
src/main/java/commons/exporters/intf/IFileExporter.java

@@ -0,0 +1,5 @@
+package commons.exporters.intf;
+
+public interface IFileExporter {
+	public boolean ExportZipFile(String zipFileName, String destinationFolder);
+}

+ 110 - 0
src/main/java/commons/type/BaseField.java

@@ -0,0 +1,110 @@
+package commons.type;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.Vector;
+
+public abstract class BaseField {
+	//Campo di comodo per tenere traccia del formattedValue originale
+	//dopo eventuali trasformazioni
+	private String stringValue;
+	private List<IFieldModificator> modificators = new Vector<IFieldModificator>();
+	private List<IFieldValidator> validators = new Vector<IFieldValidator>();
+	private IFieldTrasformer transformer = null;
+	private Object nativeValue = null;
+	//	Il valore in formato stringa dopo essere
+	//	stato processato dai modificatori
+	//private String modifiedStringValue = null;
+	//  Valore formattato
+	private String formattedValue = null;
+
+	public String getStringValue() {
+		return stringValue;
+	}
+
+	public void setStringValue(String string) {
+		stringValue = string;
+	}
+
+	public Object getNativeValue() {
+		return nativeValue;
+	}
+
+	public IFieldTrasformer getTransformer() {
+		return transformer;
+	}
+
+	public void setNativeValue(Object object) {
+		nativeValue = object;
+	}
+
+	public void setTransformer(IFieldTrasformer trasformer) {
+		transformer = trasformer;
+	}
+
+	public BaseField addModificator(IFieldModificator m) {
+		modificators.add(m);
+		return this;
+	}
+
+	public void removeModificator(IFieldModificator m) {
+		modificators.remove(m);
+	}
+
+	public BaseField addValidator(IFieldValidator m) {
+		validators.add(m);
+		return this;
+	}
+
+	public void removeValidator(IFieldValidator m) {
+		validators.remove(m);
+	}
+
+//	public String getModifiedStringValue()
+//	{
+//		return modifiedStringValue;
+//	}
+//
+//	public void setModifiedStringValue(String string)
+//	{
+//		modifiedStringValue = string;
+//	}
+	
+	public String getFormattedValue() {
+		return formattedValue;
+	}
+
+	public void setFormattedValue(String string) {
+		formattedValue = string;
+		setStringValue(string);
+	}
+
+	public void convertToNative() throws TransformException, ValidateException, ModifyException {
+		//setModifiedStringValue(stringValue);
+		String modifiedValue = getFormattedValue();
+		for (Iterator iter = modificators.iterator(); iter.hasNext();) {
+			IFieldModificator element = (IFieldModificator)iter.next();
+			/*LVL01*/
+			modifiedValue = element.modify(modifiedValue);
+			
+			//element.modify(getFormattedValue())
+			
+		
+		}
+		setNativeValue(transformer.transform(modifiedValue));
+		
+		//setNativeValue(transformer.transform(getFormattedValue()));
+		
+		for (Iterator iter = validators.iterator(); iter.hasNext();) {
+			IFieldValidator element = (IFieldValidator)iter.next();
+			element.validate(getNativeValue());
+		}
+	}
+	
+	public void convertToText() throws TransformException {
+		setFormattedValue(transformer.format(getNativeValue()));
+	}
+		
+	public abstract boolean isEmpty();
+
+}

+ 5 - 0
src/main/java/commons/type/IFieldModificator.java

@@ -0,0 +1,5 @@
+package commons.type;
+
+public interface IFieldModificator {
+	public String modify(String object) throws ModifyException;
+}

+ 6 - 0
src/main/java/commons/type/IFieldTrasformer.java

@@ -0,0 +1,6 @@
+package commons.type;
+
+public interface IFieldTrasformer {
+	public Object transform(String object) throws TransformException;
+	public String format(Object object) throws TransformException;
+}

+ 8 - 0
src/main/java/commons/type/IFieldValidator.java

@@ -0,0 +1,8 @@
+package commons.type;
+
+
+
+
+public interface IFieldValidator {
+	public void validate(Object object) throws ValidateException;
+}

+ 13 - 0
src/main/java/commons/type/ModifyException.java

@@ -0,0 +1,13 @@
+package commons.type;
+
+
+public class ModifyException extends RuntimeException {
+	/**
+     * Comment for <code>serialVersionUID</code>
+     */
+    private static final long serialVersionUID = 1L;
+
+    public ModifyException(){
+		super();
+	}
+}

+ 11 - 0
src/main/java/commons/type/NotNullModificator.java

@@ -0,0 +1,11 @@
+package commons.type;
+
+import commons.utility.database.NullValue;
+
+
+public class NotNullModificator implements IFieldModificator {
+	public String modify(String object) throws ModifyException {
+		return (object == null ? NullValue.STRING : object);
+	}
+
+}

+ 13 - 0
src/main/java/commons/type/TransformException.java

@@ -0,0 +1,13 @@
+package commons.type;
+
+
+public class TransformException extends RuntimeException {
+	/**
+     * Comment for <code>serialVersionUID</code>
+     */
+    private static final long serialVersionUID = 1L;
+
+    public TransformException(){
+		super();
+	}
+}

+ 13 - 0
src/main/java/commons/type/ValidateException.java

@@ -0,0 +1,13 @@
+package commons.type;
+
+
+public class ValidateException extends RuntimeException {
+	/**
+     * Comment for <code>serialVersionUID</code>
+     */
+    private static final long serialVersionUID = 1L;
+
+    public ValidateException(){
+		super();
+	}
+}

+ 136 - 0
src/main/java/commons/utility/BrowserVersion.java

@@ -0,0 +1,136 @@
+package commons.utility;
+
+import jakarta.servlet.http.HttpServletRequest;
+
+import commons.utility.database.NullValue;
+
+public class BrowserVersion {
+	private boolean dipendente = false;
+
+	private boolean operatore = false;
+
+	private HttpServletRequest req = null;
+
+	public BrowserVersion(HttpServletRequest req) {
+		super();
+		this.req = req;
+	}
+
+	public void check() {
+
+		String agt = NullValue.STRING;
+		String majorS=NullValue.STRING;;
+
+		try {
+			agt = req.getHeader("user-agent");
+			if (agt != null)
+				agt = agt.toLowerCase();
+			else
+				return;
+
+			boolean firefx = (agt.indexOf("firefox") != -1);
+			if (firefx) {
+				operatore = true;
+				dipendente = true;
+			} else {
+				boolean ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
+
+				// int minor = Integer.parseInt(minorS);
+
+				if (ie) {
+					majorS = agt.substring(agt.indexOf("msie") + 5, agt.indexOf("msie") + 5 + 1);
+					int major = Integer.parseInt(majorS);
+					boolean ie3 = (major < 4);
+					boolean ie4 = (major == 4 && (agt.indexOf("msie 4") != -1));
+					boolean ie4up = (major >= 4);
+					boolean ie5 = (major == 5 && (agt.indexOf("msie 5.0") != -1));
+					boolean ie5_5 = (major == 5 && (agt.indexOf("msie 5.5") != -1));
+					boolean ie5up = (major >= 5 && !ie3 && !ie4 && !ie5);
+					boolean ie5_5up = (major >= 5 && !ie3 && !ie4 && !ie5 && !ie5_5);
+					boolean ie6 = (major == 6 && (agt.indexOf("msie 6.0") != -1));
+					boolean ie6up = (major >= 6 && !ie3 && !ie4 && !ie5 && !ie5_5 && !ie6);
+
+					if (ie5_5 || ie5_5up) {
+						dipendente = true;
+					}
+
+					if (ie6 || ie6up) {
+						operatore = true;
+						dipendente = true;
+					}
+				}
+			}
+		} catch (Exception er) {
+			
+			if (agt == null) {
+				System.out.println("*************************************** USER-AGENT ***************************");
+				System.out.println("USER-AGENT NULLO " + er.getMessage());
+				er.printStackTrace();
+				System.out.println("*************************************** USER-AGENT ***************************");
+			}
+			if (req == null) {
+				
+				System.out.println("*************************************** USER-AGENT ***************************");
+				System.out.println("Request NULLA " + er.getMessage());
+				er.printStackTrace();
+				System.out.println("*************************************** USER-AGENT ***************************");
+			}
+
+			if (agt.length() == 0) {
+				
+				System.out.println("*************************************** USER-AGENT ***************************");
+				System.out.println("Agent == blank" + er.getMessage());
+				er.printStackTrace();
+				System.out.println("*************************************** USER-AGENT ***************************");
+			}
+			 if (er instanceof NumberFormatException) {
+					System.out.println("*************************************** USER-AGENT ***************************");
+					System.out.println("NumberFormatException");
+					System.out.println("Valore= "+majorS);
+					System.out.println(er.getMessage());
+					er.printStackTrace();
+					System.out.println("*************************************** USER-AGENT ***************************");
+			}
+			
+			System.out.println("*************************************** USER-AGENT ***************************");
+			System.out.println("GENERAL");
+			System.out.println("agt= " +agt);
+			System.out.println("majorS= "+majorS);
+			System.out.println("");
+			System.out.println(er.getMessage());
+			er.printStackTrace();
+			System.out.println("*************************************** USER-AGENT ***************************");
+			
+			
+			operatore = false;
+			dipendente = true;
+		}
+
+	}
+
+	public boolean isDipendente() {
+		return dipendente;
+	}
+
+	public boolean isOperatore() {
+		return operatore;
+	}
+
+	
+	public String recoverRemoteAddress() {
+		String retVal = req.getRemoteAddr(); 
+		return (!StringUtility.empty(retVal) && retVal.length() > 30)?retVal.substring(0,30):retVal;
+	}
+
+	public String recoverHost() {
+		String retVal = req.getHeader("host"); 
+		return (!StringUtility.empty(retVal) && retVal.length() > 50)?retVal.substring(0,50):retVal;
+	}
+
+	public String recoverUserAgent() {
+		String retVal = req.getHeader("user-agent"); 
+		return (!StringUtility.empty(retVal) && retVal.length() > 100)?retVal.substring(0,100):retVal;
+	}
+
+
+}

+ 401 - 0
src/main/java/commons/utility/Compression.java

@@ -0,0 +1,401 @@
+package commons.utility;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.Enumeration;
+import java.util.zip.DataFormatException;
+import java.util.zip.Deflater;
+import java.util.zip.Inflater;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+import java.util.zip.ZipOutputStream;
+
+import commons.utility.database.NullValue;
+import commons.exception.ZCompressException;
+
+
+public class Compression {
+	
+	/**	Factory per la creazione dei file in uscita
+	 */
+	public final static class OutputZipFileFactory
+	{
+		/**	Crea un file zip aperto in scrittura a partire da un OutputStream
+		 * @param outstream lo stream su cui wrappare lo zip
+		 * @param sizeBuffer se != null && > 0 allora lo stream viene wrappato all'interno di un BufferedOutputStream
+		 * @return Una impl wrappata nel seguente modo:
+		 * 			se outstream instanceof ZipOutputStream wrap diretto su outstream
+		 * 			se outstream instanceof BufferedOutputStream allora wrap di un ZipOutputStream intorno a outstrema
+		 * 			negli altri casi,se sizeBuffer > 0 allora wrapping su un BufferedOutputStream(outstream,sizeBuffer)
+		 * 			altrimenti wrapping diretto su outstream
+		 * @throws ZCompressException
+		 */
+		public final static OutputZipFile create(final OutputStream outstream,final Integer sizeBuffer) throws ZCompressException
+		{
+			OutputZipFile impl = null;
+			//	Se lo stream ? quello di un file zip...
+			if(outstream instanceof ZipOutputStream)
+				//	...aggancialo e basta!
+				impl = new OutputZipFile((ZipOutputStream) outstream);
+			else
+			{
+				OutputStream _outstream = outstream;
+				if(null != sizeBuffer && sizeBuffer.intValue() > 0 && !(outstream instanceof BufferedOutputStream))
+					_outstream = new BufferedOutputStream(outstream,sizeBuffer);
+				impl = new OutputZipFile
+				(
+					new ZipOutputStream(_outstream)
+				);
+			}
+			return impl;
+		}
+		
+		/**	Crea un file zip aperto in scrittura,se il file esiste viene sovrascritto
+		 * @param filename
+		 * @return
+		 * @throws ZCompressException
+		 */
+		public final static OutputZipFile create(String filename) throws ZCompressException
+		{
+			FileOutputStream fos = null;
+			try
+			{
+				fos = new FileOutputStream(filename);
+				return create(fos,10);
+			}
+			catch(IOException e)
+			{
+				if(null != fos)
+				{
+					try
+					{
+						fos.close();
+					}
+					catch (IOException e1)
+					{
+					}
+					fos = null;
+				}
+				throw new ZCompressException(e);
+			}
+			finally
+			{
+			}
+		}
+	}
+	
+	public Compression() {}
+	private static final int BUFFER= 2048;
+
+	/////////////////////////////////////////////////////////////////////////////
+	//Compressione Decompressione FILE
+
+	/**	Comprime un blocco di dati all'interno di un file zip
+	 * @param dataToStore il blocco di dati da comprimere
+	 * @param dataToStoreName il nome che il blocco di dati avr? all'interno del file zip
+	 * @param outputFile il nome del file di uscita
+	 * @throws ZCompressException
+	 */
+	public static void CompressFile(byte[] dataToStore, String dataToStoreName, String outputFile) throws ZCompressException
+	{
+		ZipOutputStream out = null;
+		try
+		{
+			out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outputFile)));
+			ZipEntry entry = new ZipEntry(dataToStoreName);
+			out.putNextEntry(entry);
+			out.write(dataToStore);
+		}
+		catch(IOException e)
+		{
+			throw new ZCompressException(e);
+		}
+		finally
+		{
+			try
+			{
+				if(null != out)		out.close();
+			}
+			catch(IOException e)
+			{
+				throw new ZCompressException(e);
+			}
+		}
+	}
+	
+	public static String CompressFile(String inputFile, String outputFile) throws ZCompressException {
+		try
+		{
+			String err= "OK";
+			BufferedInputStream origin= null;
+			ZipOutputStream out= null;
+			FileInputStream fi= null;
+			try {
+				FileOutputStream dest= new FileOutputStream(outputFile);
+				out= new ZipOutputStream(new BufferedOutputStream(dest));
+				byte data[]= new byte[BUFFER];
+				File f= new File(inputFile);
+				fi= new FileInputStream(f);
+				origin= new BufferedInputStream(fi, BUFFER);
+				ZipEntry entry= new ZipEntry(f.getName());
+				out.putNextEntry(entry);
+				int count;
+				while ((count= origin.read(data, 0, BUFFER)) != -1) {
+					out.write(data, 0, count);
+				}
+			} catch (IOException ex) {
+				err= ex.getMessage();
+			} finally {
+				origin.close();
+				out.close();
+				fi.close();
+			}
+			return err;
+		}
+		catch (IOException e)
+		{
+			throw new ZCompressException(e);
+		}
+	}
+
+	public static String CompressFile(String[] inputFile, String outputFile) throws ZCompressException {
+		try
+		{
+			String err= "OK";
+			BufferedInputStream origin= null;
+			ZipOutputStream out= null;
+			FileInputStream fi= null;
+			try {
+				FileOutputStream dest= new FileOutputStream(outputFile);
+				out= new ZipOutputStream(new BufferedOutputStream(dest));
+				byte data[]= new byte[BUFFER];
+				for (int i= 0; i < inputFile.length; i++) {
+					File f= new File(inputFile[i]);
+					fi= new FileInputStream(f);
+					origin= new BufferedInputStream(fi, BUFFER);
+					ZipEntry entry= new ZipEntry(f.getName());
+					out.putNextEntry(entry);
+					int count;
+					while ((count= origin.read(data, 0, BUFFER)) != -1) {
+						out.write(data, 0, count);
+					}
+					fi.close();
+				}
+			} catch (IOException ex) {
+				err= ex.getMessage();
+			} finally {
+				if (origin != null) {
+					origin.close();
+				}
+				if (out != null) {
+					out.close();
+				}
+				if (fi != null) {
+					fi.close();
+				}
+			}
+			return err;
+		}
+		catch (IOException e)
+		{
+			throw new ZCompressException(e);
+		}
+	}
+
+	public static String DecompressFile(String inputFile, String outputFile) throws ZCompressException {
+		try
+		{
+			String err= "OK";
+			BufferedOutputStream dest= null;
+			BufferedInputStream is= null;
+			FileOutputStream fos= null;
+			ZipFile zipfile= null;
+			try {
+				ZipEntry entry;
+				zipfile= new ZipFile(inputFile);
+				Enumeration e= zipfile.entries();
+				while (e.hasMoreElements()) {
+					entry= (ZipEntry)e.nextElement();
+					is= new BufferedInputStream(zipfile.getInputStream(entry));
+					int count;
+					byte data[]= new byte[BUFFER];
+					if (null == outputFile || NullValue.STRING.equalsIgnoreCase(outputFile))
+					{
+					    String path = inputFile.substring(0, inputFile.lastIndexOf(File.separator));
+					    fos= new FileOutputStream(path + File.separator + entry.getName());
+					}
+					else
+					{
+					    fos= new FileOutputStream(outputFile);
+					}
+					dest= new BufferedOutputStream(fos, BUFFER);
+					while ((count= is.read(data, 0, BUFFER)) != -1) {
+						dest.write(data, 0, count);
+					}
+					if(dest != null)
+				    {
+				        dest.flush();
+						dest.close();
+				    }
+					
+				    if(is != null)
+				    {
+				        is.close();
+				    }
+				    
+				    if(fos != null)
+				    {
+				        fos.flush();
+						fos.close();    
+				    }
+				}
+			} catch (IOException ex) {
+				err= ex.getMessage();
+			} finally {
+			    if(dest != null)
+			    {
+			        dest.flush();
+					dest.close();
+			    }
+				
+			    if(is != null)
+			    {
+			        is.close();
+			    }
+			    
+			    if(fos != null)
+			    {
+			        fos.flush();
+					fos.close();    
+			    }
+			    
+			    if(zipfile != null)
+			    {
+			        zipfile.close();
+			    }
+			}
+			
+			return err;
+		}
+		catch (IOException e)
+		{
+			throw new ZCompressException(e);
+		}
+	}
+	
+	public static String DecompressFile(String inputFile) throws ZCompressException {
+		return DecompressFile(inputFile, null);
+	}
+
+	/////////////////////////////////////////////////////////////////////////////
+	//Compressione Decompressione BYTE[]
+
+	public static byte[] Compress(byte[] input) throws ZCompressException {
+		try
+		{
+			Deflater compressor= new Deflater();
+			compressor.setLevel(Deflater.BEST_COMPRESSION);
+			
+			// Give the compressor the data to compress
+			compressor.setInput(input);
+			compressor.finish();
+			
+			ByteArrayOutputStream bos= new ByteArrayOutputStream(input.length);
+			
+			// Compress the data
+			byte[] buf= new byte[BUFFER];
+			while (!compressor.finished()) {
+				int count= compressor.deflate(buf);
+				bos.write(buf, 0, count);
+			}
+			//try {
+			bos.close();
+			//} catch (IOException e){
+			//}
+			
+			// Get the compressed data
+			byte[] compressedData= bos.toByteArray();
+			return compressedData;
+		}
+		catch (IOException e)
+		{
+			throw new ZCompressException(e);
+		}
+
+	}
+
+	public static byte[] Decompress(byte[] input) throws ZCompressException {
+		try
+		{
+			Inflater decompressor= new Inflater();
+			decompressor.setInput(input);
+			
+			// Create an expandable byte array to hold the decompressed data
+			ByteArrayOutputStream bos= new ByteArrayOutputStream(input.length);
+			
+			// Decompress the data
+			byte[] buf= new byte[BUFFER];
+			while (!decompressor.finished()) {
+				//try {
+				int count= decompressor.inflate(buf);
+				bos.write(buf, 0, count);
+				//} catch (DataFormatException e) {
+				//}
+			}
+			//try {
+			bos.close();
+			//} catch (IOException e) {
+			//}
+			
+			// Get the decompressed data
+			byte[] decompressedData= bos.toByteArray();
+			return decompressedData;
+		}
+		catch (DataFormatException e)
+		{
+			throw new ZCompressException(e);
+		}
+		catch (IOException e)
+		{
+			throw new ZCompressException(e);
+		}
+	}
+	
+	public static void CompressFile(String pathRedix, String pathSingleFile, ZipOutputStream out) throws IOException {
+        BufferedInputStream origin = null;
+        FileInputStream fi = null;
+        try {
+            byte data[] = new byte[BUFFER];
+
+            File f = new File(pathRedix + pathSingleFile);
+            fi = new FileInputStream(f);
+            origin = new BufferedInputStream(fi, BUFFER);
+
+            ZipEntry entry = new ZipEntry(pathSingleFile);
+            out.putNextEntry(entry);
+            int count;
+            while ((count = origin.read(data, 0, BUFFER)) != -1) {
+                out.write(data, 0, count);
+            }
+            fi.close();
+        } catch (IOException ex) {
+            throw ex;
+        } finally {
+            if (origin != null) {
+                origin.close();
+                origin = null;
+            }
+            if (fi != null) {
+                fi.close();
+                fi = null;
+            }
+        }
+    }
+
+}

+ 150 - 0
src/main/java/commons/utility/CryptedCookie.java

@@ -0,0 +1,150 @@
+package commons.utility;
+
+import jakarta.servlet.http.Cookie;
+
+public class CryptedCookie extends Cookie
+{
+
+	private Cookie ck = null;
+	
+	public CryptedCookie(Cookie ck) {
+		super(ck.getName(), "");
+		this.ck = ck;
+	}
+	
+	public CryptedCookie(String name, String value) {
+		this(new Cookie(name, ""));
+		this.setValue(value);
+	}
+
+	public Cookie getCk()
+	{
+		return ck;
+	}
+
+	public void setCk(Cookie ck)
+	{
+		this.ck = ck;
+	}
+
+	public Object clone()
+	{
+		return ck.clone();
+	}
+
+	public boolean equals(Object o)
+	{
+		return ck.equals(o);
+	}
+
+	public String getComment()
+	{
+		return ck.getComment();
+	}
+
+	public String getDomain()
+	{
+		return ck.getDomain();
+	}
+
+	public int getMaxAge()
+	{
+		return ck.getMaxAge();
+	}
+
+	public String getName()
+	{
+		return ck.getName();
+	}
+
+	public String getPath()
+	{
+		return ck.getPath();
+	}
+
+	public boolean getSecure()
+	{
+		return ck.getSecure();
+	}
+
+	public String getValue()
+	{
+		try
+		{
+			return Crypto.decrypt(ck.getValue());
+		}
+		catch(Exception e)
+		{
+			setValue("");
+			return "";
+		}
+	}
+
+	public int getVersion()
+	{
+		return ck.getVersion();
+	}
+
+	public int hashCode()
+	{
+		return ck.hashCode();
+	}
+
+	public void setComment(String arg0)
+	{
+		ck.setComment(arg0);
+		super.setComment(arg0);
+	}
+
+	public void setDomain(String arg0)
+	{
+		ck.setDomain(arg0);
+		super.setDomain(arg0);
+	}
+
+	public void setMaxAge(int arg0)
+	{
+		ck.setMaxAge(arg0);
+		super.setMaxAge(arg0);
+	}
+
+	public void setPath(String arg0)
+	{
+		ck.setPath(arg0);
+		super.setPath(arg0);
+	}
+
+	public void setSecure(boolean arg0)
+	{
+		ck.setSecure(arg0);
+		super.setSecure(arg0);
+	}
+
+	public void setValue(String arg0)
+	{
+		try
+		{
+			ck.setValue(Crypto.encrypt(arg0));
+			super.setValue(ck.getValue());
+		}
+		catch(Exception e)
+		{
+			ck.setValue("");
+			super.setValue("");
+		}
+	}
+
+	public void setVersion(int arg0)
+	{
+		ck.setVersion(arg0);
+		super.setVersion(arg0);
+	}
+
+	public String toString()
+	{
+		return ck.toString();
+	}
+	
+	
+
+}

+ 190 - 0
src/main/java/commons/utility/Crypto.java

@@ -0,0 +1,190 @@
+package commons.utility;
+
+import commons.exception.ZCryptoException;
+
+
+
+public class Crypto {
+  private static String KEY="Zucchetti2004";
+
+  public static String encrypt(String input) throws ZCryptoException{
+      if (input == null || (input != null && input.length() < 3))
+          return input;
+      return encrypt(input, KEY);
+  }
+
+  private static String encrypt(String input,String key) throws ZCryptoException{
+      if (input == null)
+        return input;
+
+      String output = "";
+      int y = 3;
+      int k = 0;
+      int x = 0;
+      char[] chKey = key.toCharArray();
+      char[] tmp = input.toCharArray();
+      long chk = 100;
+      String strChk = "";
+      //Random rdm1 = new Random(((int)new Date().getTime()));
+      //String randomKey = "" + Math.round((rdm1.nextDouble() * 700) + 123);
+	  String randomKey = "" + ((Math.random() * 700) + 123);
+      char[] chRandomKey = randomKey.toCharArray();
+      for (int i = 0; i < 3; i++) {
+        output += ((char)((chRandomKey[i]+chKey[k])-(80+y)));
+        y++;
+        if (y > 7)
+          y = 0;
+        k++;
+        if (k >= chKey.length)
+          k = 0;
+      }
+      for (int i = 0; i < tmp.length; i++)
+        chk += tmp[i];
+      chk = chk * tmp.length;
+      strChk = "000" + chk;
+      strChk = strChk.substring((strChk.length()-3));
+      input = input + strChk;
+      char[] tmp1 = input.toCharArray();
+      int iTmp = 0;
+      for (int i = 0; i < tmp1.length; i++) {
+        iTmp = ((tmp1[i]+chKey[k])-(80+y)+chRandomKey[x]-(35 + x));
+        if (iTmp > 255)
+          iTmp -= 255;
+        else if (iTmp < 0)
+          iTmp += 255;
+        output += ((char)iTmp);
+        y++;
+        if (y > 7)
+          y = 0;
+        k++;
+        if (k >= chKey.length)
+          k = 0;
+        x++;
+        if (x > 2)
+          x = 0;
+      }
+      output = adjustCrypt(output);
+      return output;
+  }
+
+
+  private static String adjustCrypt(String input) throws ZCryptoException{
+    String output = "";
+    String sTmp = "";
+    char[] tmp = input.toCharArray();
+    for (int i=0; i<tmp.length; i++)
+    {
+            sTmp = "" + (tmp[i] + 0);
+            sTmp =  Integer.toHexString(tmp[i]);
+            sTmp = padLeft(sTmp,2,'0');
+            output += sTmp;
+
+    }
+    return output;
+  }
+
+  private static String padLeft(String str, int w, char c) throws ZCryptoException{
+    if (str.length() >= w) return str;
+    StringBuffer sb=new StringBuffer();
+    for (int i = w - str.length(); i > 0; --i) sb.append(c);
+    sb.append(str);
+    return new String(sb);
+  }
+
+
+  private static String adjustDecrypt(String input) throws ZCryptoException{
+    String output = "";
+    String sTmp = "";
+
+    for (int i=0; i<(input.length()); i += 2)
+    {
+            sTmp = input.substring(i,i+2);
+            if(sTmp.startsWith("0"))
+            {
+                    sTmp = sTmp.substring(1);
+                    if(sTmp.startsWith("0"))
+                            sTmp = "0";
+            }
+            output += "" + ((char)(Integer.parseInt(sTmp,16)));
+    }
+    return output;
+  }
+
+  public static String decrypt(String input) throws ZCryptoException{
+      if (input == null || (input != null && input.length() < 3))
+          return input;
+      return decrypt(input,KEY);
+  }
+
+  private static String decrypt(String input,String key) throws ZCryptoException{
+    if (input == null)
+      return input;
+
+    char[] chKey = key.toCharArray();
+    input = adjustDecrypt(input);
+
+    String output = "";
+    int y = 3;
+    int k = 0;
+    int x = 0;
+    char[] tmp = input.toCharArray();
+    long chk = 100;
+    String strChk = "";
+    String strChk1 = "";
+    String randomKey = "";
+    for (int i = 0; i < 3; i++) {
+      randomKey += ((char)((tmp[i]-chKey[k])+(80+y)));
+      y++;
+      if (y > 7)
+        y = 0;
+      k++;
+      if (k >= chKey.length)
+        k = 0;
+    }
+    char[] chRandomKey = randomKey.toCharArray();
+
+    int iTmp = 0;
+    for (int i = 3; i < tmp.length; i++) {
+      iTmp = ( (tmp[i] - chKey[k]) + (80 + y) - chRandomKey[x] + (35 + x));
+      if (iTmp < 0)
+        iTmp += 255;
+      else if (iTmp > 255)
+        iTmp -= 255;
+
+      output += ( (char) iTmp);
+      y++;
+      if (y > 7)
+        y = 0;
+      k++;
+      if (k >= chKey.length)
+        k = 0;
+      x++;
+      if (x > 2)
+        x = 0;
+    }
+    strChk = output.substring( (output.length() - 3));
+    output = output.substring(0, (output.length() - 3));
+    char[] tmp1 = output.toCharArray();
+    for (int i = 0; i < tmp1.length; i++)
+      chk += tmp1[i];
+    chk = chk * tmp1.length;
+    strChk1 = "000" + chk;
+    strChk1 = strChk1.substring( (strChk1.length() - 3));
+    if (!strChk.equals(strChk1)) {
+       throw new ZCryptoException();
+    }
+    return output;
+  }
+}
+
+
+
+
+
+
+
+
+
+
+
+

+ 628 - 0
src/main/java/commons/utility/DateUtility.java

@@ -0,0 +1,628 @@
+package commons.utility;
+
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.List;
+import java.util.TimeZone;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import commons.utility.database.NullValue;
+import commons.utility.entity.Interval;
+import commons.exception.ZParseException;
+import commons.utility.formatter.DataFormatter;
+
+
+public final class DateUtility
+{
+	public static final double MILLIS_IN_DAY = 86400000.0;
+	
+	private static final short MAGGIORE_ETA = 18;
+
+	// private final static String DATE_SEPARATOR = "/";
+	//
+	public static boolean checkData(String data)
+	{
+		String input = data;
+		String pattern = "(((0[1-9]|[12][0-9]|3[01])([-./])(0[13578]|10|12)([-./])(\\d{4}))|(([0][1-9]|[12][0-9]|30)([-./])(0[469]|11)([-./])(\\d{4}))|((0[1-9]|1[0-9]|2[0-8])([-./])(02)([-./])(\\d{4}))|((29)(\\.|-|\\/)(02)([-./])([02468][048]00))|((29)([-./])(02)([-./])([13579][26]00))|((29)([-./])(02)([-./])([0-9][0-9][0][48]))|((29)([-./])(02)([-./])([0-9][0-9][2468][048]))|((29)([-./])(02)([-./])([0-9][0-9][13579][26])))";
+		Pattern p = Pattern.compile(pattern);
+		Matcher m = p.matcher(input);
+		return m.matches();
+	}
+
+	// public static boolean checkData(String data) {
+	// String input = data;
+	// String pattern =
+	// "(((0[1-9]|[12][0-9]|3[01])([-./])(0[13578]|10|12)([-./])(\\d{4}))|(([0][1-9]|[12][0-9]|30)([-./])(0[469]|11)([-./])(\\d{4}))|((0[1-9]|1[0-9]|2[0-8])([-./])(02)([-./])(\\d{4}))|((29)(\\.|-|\\/)(02)([-./])([02468][048]00))|((29)([-./])(02)([-./])([13579][26]00))|((29)([-./])(02)([-./])([0-9][0-9][0][48]))|((29)([-./])(02)([-./])([0-9][0-9][2468][048]))|((29)([-./])(02)([-./])([0-9][0-9][13579][26])))";
+	// Pattern p = Pattern.compile(pattern);
+	// Matcher m = p.matcher(input);
+	// return m.matches();
+	// }
+
+	public static int getYear(Date date)
+	{
+		return getDatePart(date, Calendar.YEAR);
+	}
+
+	/**
+	 * Base 1: Gennaio=1, Febbraio=2 ... Dicembre=12
+	 */
+	public static int getMonth(Date date)
+	{
+		return getDatePart(date, Calendar.MONTH) + 1;
+	}
+
+	public static int getDay(Date date)
+	{
+		return getDatePart(date, Calendar.DAY_OF_MONTH);
+	}
+
+	public static int getDayOfTheWeek(Date date)
+	{
+		return getDatePart(date, Calendar.DAY_OF_WEEK);
+	}
+
+	private static int getDatePart(Date date, int part)
+	{
+		GregorianCalendar g = new GregorianCalendar();
+		g.setTime(date);
+		return g.get(part);
+	}
+	
+	
+	/**
+	 * Restituisce il numero di giorni nel mese
+	 * @param year
+	 * @param month
+	 * @return
+	 */
+	public static int getDaysOfMonth(int month, int year) {
+
+		boolean condition = true;
+		int day = 31;
+		String monthString = "00" + month;
+		monthString = monthString.substring(monthString.length() - 2,
+		                                    monthString.length());
+
+		while (condition) {
+			try {
+				Date dt = parseDate(day + "/"+ monthString+ "/"+ year);
+				if (getMonth(dt) == month && getDay(dt) == day ){
+
+					return day;
+				}
+			} catch (ZParseException e) {
+				if (day <= 0) {
+					return 31;
+				}
+			}
+			day = day - 1;			
+
+		}
+		return 31;
+
+	}
+
+	/**
+	 * Torna la differenza in mesi
+	 *
+	 * @param data1
+	 * @param data2
+	 * @return La differenza in mesi (eventualmente anche negativa)
+	 */
+	public static int differenzaDate(Date data1, Date data2)
+	{
+		Calendar cal1 = Calendar.getInstance();
+		Calendar cal2 = Calendar.getInstance();
+
+		cal1.setTime(data1);
+		cal2.setTime(data2);
+
+		int yearDiff = cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
+		int monthDiff = yearDiff * 12 + cal1.get(Calendar.MONTH) - cal2.get(Calendar.MONTH);
+
+		return monthDiff;
+	}
+	
+	public static Date parseDate(String date) throws ZParseException
+	{
+		// x importazione
+		try
+		{
+			if (date.length() == 8)
+			{
+				date = date.substring(0, 2) + "/" + date.substring(2, 4) + "/" + date.substring(4, 8);
+				DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
+				return df.parse(date);
+			}
+			else if (date.length() == 10)
+			{
+				// cerca il separatore
+				String sep = date.substring(2,3);
+				DateFormat df = new SimpleDateFormat("dd"+sep+"MM"+sep+"yyyy");
+				return df.parse(date);
+			}
+			else if (date.length() == 12)
+			{
+				// cerca il separatore
+				String sep = date.substring(2,1);
+			
+				DateFormat df = new SimpleDateFormat("dd"+sep+"MM"+sep+"yyyy");
+				return df.parse(date);
+			}
+			DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
+			return df.parse(date);
+		}
+		catch (ParseException e)
+		{
+			throw new ZParseException(e);
+		}
+
+	}
+
+	public static String parseDate(Date date)
+	{
+		DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
+		return df.format(date);
+	}
+
+	public static String parseDateShort(Date date)
+	{
+		if(date == null)
+			return NullValue.STRING;
+		DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
+		return df.format(date);
+	}
+
+	public static String parseHourShort(Date date)
+	{
+		DateFormat df = new SimpleDateFormat("HH:mm:ss");
+		return df.format(date);
+	}
+	
+	
+	public static String getStrTime(Date time, String format)
+	{
+		if (time == null)
+			return "";
+		SimpleDateFormat sdf = new SimpleDateFormat(format);
+		String s = sdf.format(time);
+		return s;
+	}
+
+	/**
+	 * Ritorna l'et? in anni a partire dalla data di nascita calcolata in base
+	 * alla data di sistema
+	 *
+	 * @param birthDate
+	 *            --> data di nascita
+	 * @return --> et? espressa in anni
+	 */
+	public static int getAge(Date birthDate)
+	{
+		int age = 0;
+		if (birthDate != null)
+		{
+			Calendar dateOfBirth = new GregorianCalendar();
+			dateOfBirth.setTime(birthDate);
+			Calendar today = Calendar.getInstance();
+			age = today.get(Calendar.YEAR) - dateOfBirth.get(Calendar.YEAR);
+			dateOfBirth.add(Calendar.YEAR, age);
+			if (today.before(dateOfBirth))
+			{
+				age--;
+			}
+		}
+		return age;
+	}
+
+	
+	/**
+	 * Ritorna l'et? in anni a partire dalla data di <code>limitDate</code>
+	 * 
+	 * @param birthDate
+	 * @param limitDate
+	 * @return
+	 */
+	public static int getAge(Date birthDate, Date limitDate) {
+		int age = 0;
+		if (birthDate != null && limitDate != null
+		    && birthDate.before(limitDate)) {
+			Calendar dateOfBirth = new GregorianCalendar();
+			dateOfBirth.setTime(birthDate);
+			Calendar limitDay = Calendar.getInstance();
+			limitDay.setTime(limitDate);
+			age = limitDay.get(Calendar.YEAR) - dateOfBirth.get(Calendar.YEAR);
+			dateOfBirth.add(Calendar.YEAR,
+			                age);
+			if (limitDay.before(dateOfBirth)) {
+				age--;
+			}
+		}
+		return age;
+	}
+	
+	/**
+	 * Controlla se l'et? ? una maggiore et? o meno.
+	 * 
+	 * @param eta
+	 * @return vero se et? ? una meggiore et?
+	 */
+	public static boolean isMaggiorenne(int eta){
+		
+		if (eta >= MAGGIORE_ETA){
+			return true;
+		}
+		
+		return false;
+	}
+	
+	/**
+	 * Controlla se l'et? ? una maggiore et? o meno a partire dalla
+	 * data di nascita.
+	 * 
+	 * @param birthDate --> data di nascita
+	 * @return vero se et? ? una meggiore et?
+	 */
+	public static boolean isMaggiorenne(Date birthDate){
+		
+		int eta = getAge(birthDate);
+		
+		return isMaggiorenne(eta);
+		
+	}
+	
+
+	/**
+	 * Differenza di 2 date in giorni.
+	 * @param from
+	 * @param to
+	 * @param tz
+	 * @return
+	 */
+	private static int getDifferenzaDate_Giorni(Date from, Date to, TimeZone tz)
+	{
+		Calendar cal1 = null;
+		Calendar cal2 = null;
+		if (tz == null)
+		{
+			cal1 = Calendar.getInstance();
+			cal2 = Calendar.getInstance();
+		}
+		else
+		{
+			cal1 = Calendar.getInstance(tz);
+			cal2 = Calendar.getInstance(tz);
+		}
+		// different date might have different offset
+		cal1.setTime(from);
+		long ldate1 = from.getTime() + cal1.get(Calendar.ZONE_OFFSET) + cal1.get(Calendar.DST_OFFSET);
+		cal2.setTime(to);
+		long ldate2 = to.getTime() + cal2.get(Calendar.ZONE_OFFSET) + cal2.get(Calendar.DST_OFFSET);
+		// Use integer calculation, truncate the decimals
+		int dateDiff = (int) Math.round((ldate1-ldate2)/MILLIS_IN_DAY);
+
+		// RITORNA DIFFERENZA DATE
+		return dateDiff;
+	}
+
+	/**
+	 * Calcola il numero dei Giorni tra 2 date.
+	 * 01/06 - 30/06 = 181
+	 * @param from
+	 * @param to
+	 * @param tz
+	 * @return
+	 */
+	public static int getGiorni(Date from, Date to)
+	{
+		return getDifferenzaDate_Giorni(to,from,null) + 1;
+	}
+	
+	/**
+	 * Controlla se la data ? presente
+	 * @param date
+	 * @return true se presente
+	 */
+	public static boolean exists(Date date){
+		return (date != NullValue.DATE);
+	}
+
+	
+	/**
+	 * Formatta la data a seconda del pattern passato
+	 * come parametri 
+	 * @param date
+	 * @param pattern
+	 * @return data formattata secondo il pattern
+	 */
+    public static String parseDate(Date date,
+								   String pattern) {
+		DateFormat df = new SimpleDateFormat(pattern);
+		return df.format(date);
+	}
+
+    /**
+	 * Controlla che la data passata con il parametro <data> non sia superiore a <dataLimite>
+	 * @param data
+	 * @param dataLimite
+	 * @return java.util.Date
+	 */
+    public static Date controllaLimiteMassimo(Date data, Date dataLimite) {
+		if (data == null) {
+			return null;
+		}
+		return DateUtility.differenzaDate(data, dataLimite) > 0 ? data : null;
+	}
+    /**
+     * Crea una data dato il  <code>giorno</code>, <code>mese</code> e <code>anno</code>
+     * @param giorno
+     * @param mese
+     * @param anno
+     * @return
+     */
+	public static Date parseDate(int giorno, int mese, int anno){
+		String gg = "00"+giorno;
+		gg = gg.substring(gg.length()-2);
+		String mm = "00"+mese;
+		mm = mm.substring(mm.length()-2);
+		if (anno < 100){
+			anno = 2000 +anno;
+		}else if (anno < 1000){
+			anno = 1000 +anno;
+		}
+		String data = gg+"/"+mm+"/"+anno;
+		return parseDate(data);
+//		Calendar cal = Calendar.getInstance();
+//		cal.set(Calendar.DAY_OF_MONTH, giorno);
+//		cal.set(Calendar.MONTH, mese-1);
+//		cal.set(Calendar.YEAR, anno);
+//		cal.set(Calendar.HOUR, 0);
+//		cal.set(Calendar.MINUTE, 0);
+//		cal.set(Calendar.SECOND, 0);
+//		cal.set(Calendar.MILLISECOND, 0);
+//		return cal.getTime();
+	}
+
+	/**
+	 * Aggiunge un numero di </code>giorni</code> alla <code>data</code> passata come parametro
+	 * @param data
+	 * @param giorni
+	 * @return una data incrementata del numero giorni passato
+	 */
+	public static Date aggiungiGiorni(Date data, int giorni){
+		GregorianCalendar cal = new GregorianCalendar();
+		cal.setTime(data);
+		cal.add(Calendar.DAY_OF_YEAR, giorni);
+		return cal.getTime();
+	}
+	/**
+	 * Ritorna la data minore tra le due date passate come parametro
+	 * @param data1
+	 * @param data2
+	 * @return
+	 */
+	public static Date min(Date data1, Date data2){
+		if (data1 == null || data2 == null)
+			return null;
+		if (data1.after(data2)){
+			return data2;
+		}else{
+			return data1;
+		}
+	}
+	
+	/**
+	 * Ritorna la data maggiore tra le due date passate come parametro
+	 * @param data1
+	 * @param data2
+	 * @return
+	 */
+	public static Date max(Date data1, Date data2){
+		if (data1 == null || data2 == null)
+			return null;
+		if (data1.after(data2)){
+			return data1;
+		}else{
+			return data2;
+		}
+	}
+	
+	public static Date createDate(int anno, int mese, int giorno, int ora, int minuti, int secondi, int millisecondi )
+	{
+		
+		Calendar gcDa = new GregorianCalendar();
+		gcDa.set(Calendar.YEAR, anno);
+		gcDa.set(Calendar.MONTH, mese-1);
+		gcDa.set(Calendar.DAY_OF_MONTH, giorno);
+		gcDa.set(Calendar.HOUR_OF_DAY, ora);
+		gcDa.set(Calendar.MINUTE, minuti);
+		gcDa.set(Calendar.SECOND, secondi);
+		gcDa.set(Calendar.MILLISECOND, millisecondi);
+		return new Date(gcDa.getTimeInMillis()); 
+	}
+
+	/**
+	 * Azzera i valori dell'ora nella data passata come parametro
+	 * @param data
+	 * @return
+	 */
+	public static Date azzeraOrario(Date data)
+	{
+		Calendar gcDa = new GregorianCalendar();
+		gcDa.setTime(data);
+		gcDa.set(Calendar.HOUR_OF_DAY, 0);
+		gcDa.set(Calendar.MINUTE, 0);
+		gcDa.set(Calendar.SECOND, 0);
+		gcDa.set(Calendar.MILLISECOND, 0);
+		return new Date(gcDa.getTimeInMillis()); 
+	}
+	/**
+	 * Verifica se il valore del parametro <b>data</b> ? nel range specificato dai parametri <b>dal</b> e <b>al</b>
+	 * tenendo conto che sia <b>dal</b> sia <b>al</b> possono essere <code>null</code>
+	 * @param data data di riferimento che bisogna confrontare con dal e al
+	 * @param dal data inizio range (puo' essere <code>null</code>)
+	 * @param al data fine range (puo' essere <code>null</code>)
+	 * @param includeHour indica se escludere dal confronto l'orario (ora, minuti, secondi, millisecondi)
+	 * @return
+	 */
+	public static boolean dataInRange(Date data, Date dal, Date al, boolean includeHour)
+	{
+		Date internalData = data;
+		Date internalDal = dal;
+		Date internalAl = al;
+		if (internalData != null)
+		{
+			internalData = includeHour ? internalData : azzeraOrario(internalData);
+		}
+		if (internalDal != null)
+		{
+			internalDal = includeHour ? internalDal : azzeraOrario(internalDal);
+		}
+		if (internalAl != null)
+		{
+			internalAl = includeHour ? internalAl : azzeraOrario(internalAl);
+		}
+		
+		boolean valRet = true;
+		if (valRet && dal != null)
+		{
+			valRet = internalData.compareTo(internalDal) >= 0;
+		}
+		if (valRet && al != null)
+		{
+			valRet = internalData.compareTo(internalAl) <= 0;
+		}
+		
+		return valRet;
+		
+	}
+	
+	/**
+	 * Ritorna la data odierna senza ore, minuti e secondi
+	 * @return
+	 */
+	public static Date creaDataOdierna()
+	{
+		DataFormatter df = DataFormatter.getInstance();
+		return df.parseData(df.formatData(new Date()));
+	}
+	
+	public static List<Interval> dividiInIntervalli(Date dataDa,
+	                                         Date dataA)
+	{
+		List<Interval> elenco = new ArrayList<Interval>();
+		Calendar cal = Calendar.getInstance();
+		Date it = dataDa;
+		cal.setTime(dataDa);
+		while(it.before(dataA))
+		{
+			Interval inter = new Interval(it, getLastDayOfMonth(it));
+			elenco.add(inter);
+			it = addMonth(it);
+		}	
+		return elenco;
+	}
+	
+	private static Date getLastDayOfMonth(Date data)
+	{
+		Calendar cal = Calendar.getInstance();
+		cal.setTime(data);
+		int lastDate = cal.getActualMaximum(Calendar.DATE);
+		cal.set(Calendar.DAY_OF_MONTH, lastDate);
+		return cal.getTime();
+	}
+	
+	private static Date addMonth(Date data)
+	{
+		Calendar cal = Calendar.getInstance();
+		cal.setTime(data);
+		cal.add(Calendar.MONTH, 1);
+		return cal.getTime();
+	}
+	
+	public static boolean between(Date rif, Date dataInizio, Date dataFine)
+	{
+		if((rif.equals(dataInizio) || rif.after(dataInizio)) &&
+				((rif.equals(dataFine) || rif.before(dataFine))))
+				return true;
+		return false;
+	}
+	
+	public static Date getUltimaOreDelGiorno(Date data)
+	{
+		Calendar cal = Calendar.getInstance();
+		cal.setTime(data);
+		cal.set(Calendar.HOUR, 23);
+		cal.set(Calendar.MINUTE, 59);
+		cal.set(Calendar.SECOND, 59);
+		return cal.getTime();
+	}
+	
+	public static Date getUltimoGiornoDelMese(Date data)
+	{
+		Calendar cal = Calendar.getInstance();
+		cal.setTime(data);
+		cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
+		return cal.getTime();
+	}
+	
+	public static Calendar getInizioSettimana(Calendar cal)	{
+        Calendar firstDayOfWeek = cal;
+        
+        while (firstDayOfWeek.get(Calendar.DAY_OF_WEEK)!=Calendar.MONDAY)
+                firstDayOfWeek.add(Calendar.DAY_OF_MONTH,-1);
+
+        return firstDayOfWeek;
+	}
+	
+	public static Calendar getFineSettimana(Calendar cal) {
+	
+        Calendar lastDayOfWeek = cal;
+        while (lastDayOfWeek.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY)
+                lastDayOfWeek.add(Calendar.DAY_OF_MONTH,1);
+
+        return lastDayOfWeek;
+	}
+        
+	public static Calendar getInizioMese(Calendar cal) {
+
+        cal.set(Calendar.DAY_OF_MONTH, 1);
+        return cal;
+	}
+	
+	public static Calendar getFineMese(Calendar cal) {
+        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
+        return cal;
+	}    
+	
+	public static boolean maggioreUguale(Date data1, Date data2)
+	{
+		return (data1.after(data2) || data1.equals(data2));
+	}
+	
+	public static boolean minoreUguale(Date data1, Date data2)
+	{
+		return (data1.before(data2) || data1.equals(data2));
+	}
+	
+	public static Calendar StringToCalendar(String str) {
+		Calendar res = null;
+		if (str != null && !str.isEmpty()) {
+			try {
+				res = Calendar.getInstance();
+				res.setTime(DateUtility.parseDate(str));
+			} catch (Exception ex) {
+				res = null;
+			
+			}
+		}
+		return res;
+	}
+
+}

+ 180 - 0
src/main/java/commons/utility/FileUtility.java

@@ -0,0 +1,180 @@
+package commons.utility;
+
+import java.awt.Graphics2D;
+import java.awt.image.BufferedImage;
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.channels.FileChannel;
+import java.util.Date;
+
+import javax.imageio.ImageIO;
+
+import commons.utility.database.NullValue;
+
+
+public class FileUtility {
+	
+    public static byte[] fromFileToByte(String pathFile) throws IOException 
+    {
+		File file = new File(pathFile);
+		InputStream is = new FileInputStream(file);
+		long length = file.length();
+		byte[] bytes = new byte[(int)length];
+		// Read in the bytes
+		int offset = 0;
+		int numRead = 0;
+		while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
+			offset += numRead;
+		}
+		// Ensure all the bytes have been read in
+		if (offset < bytes.length) {
+			is.close();
+			throw new IOException("Impossibile leggere il file " + file.getName());
+		}
+		// Close the input stream and return bytes
+		is.close();
+		return bytes;
+	}
+    
+	public static void fromByteToFile(byte[] bytes,
+	                                  File file)
+	{
+		BufferedOutputStream bos = null;
+
+		try
+		{
+			//create an object of FileOutputStream
+			FileOutputStream fos = new FileOutputStream(file);
+			//create an object of BufferedOutputStream
+			bos = new BufferedOutputStream(fos);
+
+			/*
+			 * To write byte array to file use,
+			 * public void write(byte[] b) method of BufferedOutputStream
+			 * class.
+			 */
+			bos.write(bytes);
+		}
+		catch (FileNotFoundException fnfe)
+		{
+			fnfe.printStackTrace();
+		}
+		catch (IOException ioe)
+		{
+			ioe.printStackTrace();
+		}
+		finally
+		{
+			if (bos != null)
+			{
+				try
+				{
+					//flush the BufferedOutputStream
+					bos.flush();
+					//close the BufferedOutputStream
+					bos.close();
+				}
+				catch (Exception e)
+				{
+				}
+			}
+		}
+	}
+
+    //Elimina una cartella e le sue sottocartelle compresi i file
+    public static boolean deleteDir(File dir) {
+        if (dir.isDirectory()) {
+            String[] children = dir.list();
+            for (int i=0; i<children.length; i++) {
+                boolean success = deleteDir(new File(dir, children[i]));
+                if (!success) {
+                    return false;
+                }
+            }
+        }
+
+        // The directory is now empty so delete it
+        return dir.delete();
+    }
+
+    //Copia file
+    public static void copy(File source, File dest) throws IOException {
+        FileChannel in = null, out = null;
+        try {
+             in = new FileInputStream(source).getChannel();
+             out = new FileOutputStream(dest).getChannel();
+
+             in.transferTo( 0, in.size(), out);
+        } finally {
+             if (in != null)
+                 in.close();
+             if (out != null)
+                 out.close();
+        }
+   }
+    
+    public static String getFileNameFromPath(String path)
+    {
+ 	   File file = new File(path);
+ 	   return file.getName();
+    }
+    
+    public static String getExtension(String fileName)
+    {
+ 	   String ext = NullValue.STRING;
+ 	   if(!StringUtility.empty(fileName, true))
+ 		   ext = fileName.substring(fileName.lastIndexOf(".") + 1);
+ 	   return ext;
+    }
+    
+    public static String getContentType(String tipoFile)
+  	{
+  		if(tipoFile.equals("pdf"))
+  			return "application/pdf";
+  		else if(tipoFile.equals("zip"))
+  			return "application/zip";
+  		else if(tipoFile.equals("rar"))
+  			return "application/rar";
+  		else if(tipoFile.equals("doc"))
+  			return "application/msword";
+  		else if(tipoFile.equals("jpg"))
+  			return "image/jpg";
+  		else if(tipoFile.equals("jpeg"))
+  			return "image/jpeg";
+  		else if(tipoFile.equals("bmp"))
+  			return "imgae/bmp";
+  		else if(tipoFile.equals("tif"))
+  			return "image/tif";
+  		else if(tipoFile.equals("tiff"))
+  			return "imgae/tiff";
+  		else if(tipoFile.equals("gif"))
+  			return "image/gif";
+  		else if(tipoFile.equals("png"))
+  			return "imgae/png";
+  		else
+  			return "application/octet-stream";
+  	}
+    
+    public static byte[] resizeImage(File fileUploaded) throws IOException
+    {
+    	final int IMG_WIDTH = 130;
+    	final int IMG_HEIGHT = 130;
+    	BufferedImage originalImage = ImageIO.read(fileUploaded);
+		int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
+    	
+		BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
+    	Graphics2D g = resizedImage.createGraphics();
+    	g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
+    	g.dispose();
+     
+    	File file = new File(new Date().getTime() + "");
+    	ImageIO.write(resizedImage, "jpg", file); 
+    	
+    	return fromFileToByte(file.getAbsolutePath());
+        }
+}

+ 356 - 0
src/main/java/commons/utility/FormatUtility.java

@@ -0,0 +1,356 @@
+package commons.utility;
+
+import java.text.DecimalFormat;
+import java.text.DecimalFormatSymbols;
+import java.text.NumberFormat;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+import javax.xml.crypto.dsig.TransformException;
+
+import org.apache.commons.lang.StringUtils;
+
+import commons.utility.database.NullValue;
+
+/**
+ * @author basluc
+ *
+ *	Classe generica per le formattazioni
+ */
+public final class FormatUtility
+{
+	static public String formatText(String text)
+	{
+		return (null == text) ? "" : text;
+	}
+
+	static public String formatText(String text, int maxLength)
+	{
+		return (null == text) ? "" : text.length() <= maxLength ? text : text.substring(0,maxLength);
+	}
+
+	static public String formatValuta(int value)
+	{
+		DecimalFormatSymbols symbols = new DecimalFormatSymbols();
+		symbols.setGroupingSeparator('.');
+		symbols.setDecimalSeparator(',');
+		DecimalFormat nf = new DecimalFormat("#,##0.00", symbols);
+		return nf.format(value);
+	}
+
+	static public String formatValuta(double value)
+	{
+		DecimalFormatSymbols symbols = new DecimalFormatSymbols();
+		symbols.setGroupingSeparator('.');
+		symbols.setDecimalSeparator(',');
+		DecimalFormat nf = new DecimalFormat("#,##0.00", symbols);
+		return nf.format(value);
+	}
+
+    static public String formatValutaNoSeparator(double value)
+    {
+        DecimalFormatSymbols symbols = new DecimalFormatSymbols();
+        symbols.setDecimalSeparator(',');
+        symbols.setGroupingSeparator('.');
+        DecimalFormat nf = new DecimalFormat("#,##0.00", symbols);
+        return nf.format(value).replaceAll("\\.","");
+    }
+
+    static public String formatValutaNoSeparator(float value)
+    {
+        DecimalFormatSymbols symbols = new DecimalFormatSymbols();
+        symbols.setDecimalSeparator(',');
+        symbols.setGroupingSeparator('.');
+        DecimalFormat nf = new DecimalFormat("#,##0.00", symbols);
+        return nf.format(value).replaceAll("\\.","");
+    }
+
+    static public String formatValutaNoSeparator(int value)
+    {
+        DecimalFormat nf = new DecimalFormat("###");
+        return nf.format(value).replaceAll("\\.","");
+    }
+
+	static public String formatDecimalValue(int value)
+	{
+		DecimalFormatSymbols symbols = new DecimalFormatSymbols();
+		symbols.setGroupingSeparator('.');
+		symbols.setDecimalSeparator(',');
+		DecimalFormat nf = new DecimalFormat("#,##0", symbols);
+		return nf.format(value);
+	}
+
+
+	static public String formatValue(int value)
+	{
+
+		DecimalFormat nf = new DecimalFormat("###");
+		return nf.format(value);
+	}
+
+	static public String formatValue(double value)
+	{
+		DecimalFormatSymbols symbols = new DecimalFormatSymbols();
+		symbols.setDecimalSeparator(',');
+		DecimalFormat nf = new DecimalFormat("##0.00");
+		return nf.format(value);
+	}
+
+	static public String formatDate(Date date)
+	{
+		return new SimpleDateFormat("dd/MM/yyyy").format(date);
+	}
+
+	static public String formatDate(Date date, String pattern)
+	{
+		if(pattern == null)
+		{
+			pattern = "dd/MM/yyyy";
+		}
+		return new SimpleDateFormat(pattern).format(date);
+	}
+
+	static public String formatDateTime(Date date)
+	{
+		return new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(date);
+	}
+
+	static public String formatTime(Date date)
+	{
+		return new SimpleDateFormat("HH:mm:ss").format(date);
+	}
+
+	static public String formatTime(Date date, String separator)
+	{
+		String pattern = "HH:mm:ss";
+		if(separator != null)
+		{
+			pattern = pattern.replaceAll(":", separator);
+		}
+
+		return new SimpleDateFormat(pattern).format(date);
+	}
+
+	static public String formatBoolean(boolean b)
+	{
+		return Boolean.toString(b);
+	}
+	//
+	//	static public String formatDate(String date) {
+	//		try {
+	//			return formatDate(new SimpleDateFormat("dd/MM/yyyy").parse(date));
+	//		} catch (ParseException e) {
+	//			try {
+	//				return formatDate(new SimpleDateFormat().parse(date));
+	//			} catch (ParseException e1) {
+	//				return formatText(date);
+	//			}
+	//		}
+	//	}
+
+	public static String formatNumber2Dec(String sValue)
+	{
+		String model = "###,###,###,###,##0.00";
+		return formatNumberModel(sValue, model);
+	}
+
+	public static String formatNumberModel(String sValue, String model)
+	{
+		String formatVal = "";
+
+		if (sValue == null || sValue.equals(""))
+			return "";
+
+		DecimalFormatSymbols mySymbol = new DecimalFormatSymbols();
+		mySymbol.setDecimalSeparator(',');
+		mySymbol.setGroupingSeparator('.');
+		DecimalFormat myFormatter = new DecimalFormat(model, mySymbol);
+		myFormatter.setGroupingSize(3);
+
+		formatVal = myFormatter.format(new Double(sValue));
+
+		return formatVal;
+	}
+
+	public static String unformatNumber(String sValue)
+	{
+		try
+		{
+			String formatVal = "";
+
+			if (sValue == null || sValue.equals(""))
+				return "";
+
+			//sValue = StringUtility.ReplaceSubString(sValue,".","");
+			//sValue = StringUtility.ReplaceSubString(sValue,",",".");
+			sValue = sValue.replaceAll("\\.", "").replaceAll(",", ".");
+
+			DecimalFormatSymbols mySymbol = new DecimalFormatSymbols();
+			mySymbol.setDecimalSeparator('.');
+			String model = "################.################";
+			DecimalFormat myFormatter = new DecimalFormat(model, mySymbol);
+			myFormatter.setGroupingSize(16);
+
+			formatVal = myFormatter.format(new Double(sValue));
+
+			return formatVal;
+		}
+		catch (Exception e)
+		{
+			e.printStackTrace();
+			return "";
+		}
+	}
+
+	public static String formatPercentuale(double value) throws TransformException
+	{
+		DecimalFormatSymbols dfs = new DecimalFormatSymbols();
+		dfs.setDecimalSeparator(',');
+		NumberFormat format = new DecimalFormat("###.0###",dfs);
+		//imposto il numero di decimali per la formattazione
+		if(NullValue.NUMBER == 3)
+		{
+			format.setMaximumFractionDigits(3);
+			format.setMinimumFractionDigits(3);
+		}
+		else
+		{
+			format.setMaximumFractionDigits(3);
+			format.setMinimumFractionDigits(3);
+		}
+		format.setMaximumIntegerDigits(3);
+		format.setMinimumIntegerDigits(1);
+		format.setGroupingUsed(false);
+		String fValue = format.format(value);
+		//	Se il numero di decimali ? automatico...
+		if(NullValue.NUMBER == 3)
+		{
+			//	...elimina gli zero meno significativi
+			while(fValue.endsWith("0"))
+				fValue = fValue.substring(0,fValue.length()-1);
+			if(fValue.endsWith(","))
+				fValue = fValue.substring(0,fValue.length()-1);
+		}
+		return fValue;
+	}
+
+	public static String formatAliquota(double value) throws TransformException
+	{
+		DecimalFormatSymbols dfs = new DecimalFormatSymbols();
+		dfs.setDecimalSeparator(',');
+		NumberFormat format = new DecimalFormat("###.0####",dfs);
+		//imposto il numero di decimali per la formattazione
+		format.setMaximumFractionDigits(4);
+		format.setMinimumFractionDigits(4);
+		format.setMaximumIntegerDigits(3);
+		format.setMinimumIntegerDigits(1);
+		format.setGroupingUsed(false);
+		String fValue = format.format(value);
+		//	Se il numero di decimali ? automatico...
+		if(NullValue.NUMBER == 4)
+		{
+			//	...elimina gli zero meno significativi
+			while(fValue.endsWith("0"))
+				fValue = fValue.substring(0,fValue.length()-1);
+			if(fValue.endsWith(","))
+				fValue = fValue.substring(0,fValue.length()-1);
+		}
+		return fValue;
+	}
+
+	public static String formatSuperDouble(double value) throws TransformException
+	{
+		DecimalFormatSymbols dfs = new DecimalFormatSymbols();
+		dfs.setDecimalSeparator(',');
+		NumberFormat format = new DecimalFormat("###.0##########",dfs);
+		//imposto il numero di decimali per la formattazione
+		format.setMaximumFractionDigits(10);
+		format.setMinimumFractionDigits(10);
+		format.setMaximumIntegerDigits(1);
+		format.setMinimumIntegerDigits(1);
+		format.setGroupingUsed(false);
+		String fValue = format.format(value);
+//		//	Se il numero di decimali ? automatico...
+//		if(NullValue.NUMBER == 4)
+//		{
+//			//	...elimina gli zero meno significativi
+//			while(fValue.endsWith("0"))
+//				fValue = fValue.substring(0,fValue.length()-1);
+//			if(fValue.endsWith(","))
+//				fValue = fValue.substring(0,fValue.length()-1);
+//		}
+		return fValue;
+	}
+	/**	Versione 'semplice' di una sprintf
+	 * @param fmt la stringa di formattazione
+	 * @param params i parametri
+	 * @return la stringa formattata
+	 */
+	final static public String simpleSprintf(final String fmt, final Object ... params)
+	{
+		return String.format(fmt.replaceAll("\\{[0-9]*\\}", "\\%s"), params);
+	}
+	
+	/**
+	 * Restituisce un array di stringe divise secondo la lunghezza <len> massima
+	 * @param str
+	 * @param len
+	 * @return
+	 */
+	public static List<String> formatTextStrutturaPDF(String str, int len)
+	{
+		if(StringUtils.isEmpty(str) || len == 0)
+			return new ArrayList<String>();
+		final String SEPARATOR = ", ";
+		String[] aStr = str.split(SEPARATOR);
+		List<String> result = new ArrayList<String>();
+		for(int index = 0, size = aStr.length; index < size; index++)
+		{	
+			if(result.size() == 0)
+				result.add(aStr[index] + SEPARATOR);
+			else if(!StringUtils.isEmpty(aStr[index]))
+			{
+				String tmp = result.get(result.size()-1);
+				if((tmp.length() + aStr[index].length()) <= len)
+				{
+					result.remove(result.size()-1);
+					tmp = tmp.substring(0, tmp.length()-2);
+					result.add(tmp + SEPARATOR + aStr[index] + SEPARATOR);
+				}
+				else
+				{
+					result.add(aStr[index] + SEPARATOR);
+				}
+			}
+		}
+		if(result.size() > 0){
+			String tmp = result.get(result.size()-1);
+			tmp = tmp.substring(0, tmp.length()-2);
+			result.remove(result.size()-1);
+			result.add(tmp);
+		}	
+		return result;
+	}
+	
+	/**
+	 * Restituisce la Stringa passata come parametro troncata dopo #len caratteri
+	 * @param str
+	 * @param len
+	 * @return
+	 */
+	public static String trunkString(String str, int len)
+	{
+		if(StringUtils.isEmpty(str))
+			return NullValue.STRING;
+		str = str.trim();
+		if(str.length() <= len)
+			return formatText(str);
+		return formatText(str.substring(0, len))+"...";
+	}
+	
+	public static String formatNumeroTessera(int numeroTessera) {
+		return String.format("%07d", numeroTessera);  
+	}
+}

+ 76 - 0
src/main/java/commons/utility/GeoCode.java

@@ -0,0 +1,76 @@
+package commons.utility;
+
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.net.URLEncoder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.xpath.XPath;
+import javax.xml.xpath.XPathConstants;
+import javax.xml.xpath.XPathFactory;
+import org.w3c.dom.Document;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.xml.sax.InputSource;
+
+import java.io.IOException;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.xpath.XPathExpressionException;
+import org.xml.sax.SAXException;
+
+
+public class GeoCode {
+	
+	
+  // URL prefix to the geocoder
+  private static final String GEOCODER_REQUEST_PREFIX_FOR_XML = "http://maps.google.com/maps/api/geocode/xml";
+
+  
+  public static final void geocode (String address, Double lat, Double lng) throws IOException, XPathExpressionException, ParserConfigurationException, SAXException {
+
+    
+    // prepare a URL to the geocoder
+    URL url = new URL(GEOCODER_REQUEST_PREFIX_FOR_XML + "?address=" + URLEncoder.encode(address, "UTF-8") + "&sensor=false");
+
+    // prepare an HTTP connection to the geocoder
+    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
+
+    Document geocoderResultDocument = null;
+    try {
+      // open the connection and get results as InputSource.
+      conn.connect();
+      InputSource geocoderResultInputSource = new InputSource(conn.getInputStream());
+
+      // read result and parse into XML Document
+      geocoderResultDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(geocoderResultInputSource);
+    } finally {
+      conn.disconnect();
+    }
+
+    // prepare XPath
+    XPath xpath = XPathFactory.newInstance().newXPath();
+
+    // extract the result
+    NodeList resultNodeList = null;
+
+    // a) obtain the formatted_address field for every result
+    resultNodeList = (NodeList) xpath.evaluate("/GeocodeResponse/result/formatted_address", geocoderResultDocument, XPathConstants.NODESET);
+    for(int i=0; i<resultNodeList.getLength(); ++i) {
+      System.out.println(resultNodeList.item(i).getTextContent());
+    }
+
+    // b) extract the locality for the first result
+    resultNodeList = (NodeList) xpath.evaluate("/GeocodeResponse/result[1]/address_component[type/text()='locality']/long_name", geocoderResultDocument, XPathConstants.NODESET);
+    for(int i=0; i<resultNodeList.getLength(); ++i) {
+      System.out.println(resultNodeList.item(i).getTextContent());
+    }
+
+    // c) extract the coordinates of the first result
+    resultNodeList = (NodeList) xpath.evaluate("/GeocodeResponse/result[1]/geometry/location/*", geocoderResultDocument, XPathConstants.NODESET);
+    for(int i=0; i<resultNodeList.getLength(); ++i) {
+      Node node = resultNodeList.item(i);
+      if("lat".equals(node.getNodeName())) lat = Double.parseDouble(node.getTextContent());
+      if("lng".equals(node.getNodeName())) lng = Double.parseDouble(node.getTextContent());
+    }
+  }
+
+}

+ 10 - 0
src/main/java/commons/utility/IResetTransient.java

@@ -0,0 +1,10 @@
+package commons.utility;
+
+/**	Intf da utilizzare per impostare a null il valore degli oggetti
+ * 	con modificatore transient;questo ? necessario per poter effettuare
+ * 	correttamente il test per la serializzazione
+ */
+public interface IResetTransient
+{
+	public abstract void resetTransient();
+}

+ 27 - 0
src/main/java/commons/utility/JSon/CalendarSerializer.java

@@ -0,0 +1,27 @@
+package commons.utility.JSon;
+
+import java.lang.reflect.Type;
+import java.util.Calendar;
+
+import com.google.gson.JsonDeserializationContext;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonParseException;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.JsonSerializationContext;
+import com.google.gson.JsonSerializer;
+
+public class CalendarSerializer implements JsonSerializer<Calendar>, JsonDeserializer<Calendar>{
+
+	@Override
+	public JsonElement serialize(Calendar src, Type typeOfSrc,	JsonSerializationContext context) {
+		return new JsonPrimitive(src.getTimeInMillis());
+	}
+
+	@Override
+	public Calendar deserialize(JsonElement json, Type typeOfT,  JsonDeserializationContext context) throws JsonParseException {
+		Calendar cal = Calendar.getInstance();
+		cal.setTimeInMillis(json.getAsJsonPrimitive().getAsLong());
+		return cal;
+	}
+}

+ 306 - 0
src/main/java/commons/utility/JSon/GraphAdapterBuilder.java

@@ -0,0 +1,306 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package commons.utility.JSon;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.InstanceCreator;
+import com.google.gson.JsonElement;
+import com.google.gson.TypeAdapter;
+import com.google.gson.TypeAdapterFactory;
+import com.google.gson.internal.ConstructorConstructor;
+import com.google.gson.internal.ObjectConstructor;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonToken;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import java.lang.reflect.Type;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.IdentityHashMap;
+import java.util.LinkedList;
+import java.util.Map;
+import java.util.Queue;
+
+/**
+ * Writes a graph of objects as a list of named nodes.
+ */
+// TODO: proper documentation
+@SuppressWarnings("rawtypes")
+public final class GraphAdapterBuilder {
+  private final Map<Type, InstanceCreator<?>> instanceCreators
+      = new HashMap<Type, InstanceCreator<?>>();
+  private final ConstructorConstructor constructorConstructor = new ConstructorConstructor(instanceCreators, true, Collections.emptyList());
+
+  public GraphAdapterBuilder addType(Type type) {
+    final ObjectConstructor<?> objectConstructor = constructorConstructor.get(TypeToken.get(type));
+    InstanceCreator<Object> instanceCreator = new InstanceCreator<Object>() {
+      public Object createInstance(Type type) {
+        return objectConstructor.construct();
+      }
+    };
+    return addType(type, instanceCreator);
+  }
+
+  public GraphAdapterBuilder addType(Type type, InstanceCreator<?> instanceCreator) {
+    if (type == null || instanceCreator == null) {
+      throw new NullPointerException();
+    }
+    instanceCreators.put(type, instanceCreator);
+    return this;
+  }
+
+  public void registerOn(GsonBuilder gsonBuilder) {
+    Factory factory = new Factory(instanceCreators);
+    gsonBuilder.registerTypeAdapterFactory(factory);
+    for (Map.Entry<Type, InstanceCreator<?>> entry : instanceCreators.entrySet()) {
+      gsonBuilder.registerTypeAdapter(entry.getKey(), factory);
+    }
+  }
+
+  static class Factory implements TypeAdapterFactory, InstanceCreator {
+    private final Map<Type, InstanceCreator<?>> instanceCreators;
+    private final ThreadLocal<Graph> graphThreadLocal = new ThreadLocal<Graph>();
+
+    Factory(Map<Type, InstanceCreator<?>> instanceCreators) {
+      this.instanceCreators = instanceCreators;
+    }
+
+    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
+      if (!instanceCreators.containsKey(type.getType())) {
+        return null;
+      }
+
+      final TypeAdapter<T> typeAdapter = gson.getDelegateAdapter(this, type);
+      final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
+      return new TypeAdapter<T>() {
+        @Override public void write(JsonWriter out, T value) throws IOException {
+          if (value == null) {
+            out.nullValue();
+            return;
+          }
+
+          Graph graph = graphThreadLocal.get();
+          boolean writeEntireGraph = false;
+
+          /*
+           * We have one of two cases:
+           *  1. We've encountered the first known object in this graph. Write
+           *     out the graph, starting with that object.
+           *  2. We've encountered another graph object in the course of #1.
+           *     Just write out this object's name. We'll circle back to writing
+           *     out the object's value as a part of #1.
+           */
+
+          if (graph == null) {
+            writeEntireGraph = true;
+            graph = new Graph(new IdentityHashMap<Object, Element<?>>());
+          }
+
+          @SuppressWarnings("unchecked") // graph.map guarantees consistency between value and T
+          Element<T> element = (Element<T>) graph.map.get(value);
+          if (element == null) {
+            element = new Element<T>(value, graph.nextName(), typeAdapter, null);
+            graph.map.put(value, element);
+            graph.queue.add(element);
+          }
+
+          if (writeEntireGraph) {
+            graphThreadLocal.set(graph);
+            try {
+              out.beginObject();
+              Element<?> current;
+              while ((current = graph.queue.poll()) != null) {
+                out.name(current.id);
+                current.write(out);
+              }
+              out.endObject();
+            } finally {
+              graphThreadLocal.remove();
+            }
+          } else {
+            out.value(element.id);
+          }
+        }
+
+        @Override public T read(JsonReader in) throws IOException {
+          if (in.peek() == JsonToken.NULL) {
+            in.nextNull();
+            return null;
+          }
+
+          /*
+           * Again we have one of two cases:
+           *  1. We've encountered the first known object in this graph. Read
+           *     the entire graph in as a map from names to their JsonElements.
+           *     Then convert the first JsonElement to its Java object.
+           *  2. We've encountered another graph object in the course of #1.
+           *     Read in its name, then deserialize its value from the
+           *     JsonElement in our map. We need to do this lazily because we
+           *     don't know which TypeAdapter to use until a value is
+           *     encountered in the wild.
+           */
+
+          String currentName = null;
+          Graph graph = graphThreadLocal.get();
+          boolean readEntireGraph = false;
+
+          if (graph == null) {
+            graph = new Graph(new HashMap<Object, Element<?>>());
+            readEntireGraph = true;
+
+            // read the entire tree into memory
+            in.beginObject();
+            while (in.hasNext()) {
+              String name = in.nextName();
+              if (currentName == null) {
+                currentName = name;
+              }
+              JsonElement element = elementAdapter.read(in);
+              graph.map.put(name, new Element<T>(null, name, typeAdapter, element));
+            }
+            in.endObject();
+          } else {
+            currentName = in.nextString();
+          }
+
+          if (readEntireGraph) {
+            graphThreadLocal.set(graph);
+          }
+          try {
+            @SuppressWarnings("unchecked") // graph.map guarantees consistency between value and T
+            Element<T> element = (Element<T>) graph.map.get(currentName);
+            // now that we know the typeAdapter for this name, go from JsonElement to 'T'
+            if (element.value == null) {
+              element.typeAdapter = typeAdapter;
+              element.read(graph);
+            }
+            return element.value;
+          } finally {
+            if (readEntireGraph) {
+              graphThreadLocal.remove();
+            }
+          }
+        }
+      };
+    }
+
+    /**
+     * Hook for the graph adapter to get a reference to a deserialized value
+     * before that value is fully populated. This is useful to deserialize
+     * values that directly or indirectly reference themselves: we can hand
+     * out an instance before read() returns.
+     *
+     * <p>Gson should only ever call this method when we're expecting it to;
+     * that is only when we've called back into Gson to deserialize a tree.
+     */
+    @SuppressWarnings("unchecked")
+    public Object createInstance(Type type) {
+      Graph graph = graphThreadLocal.get();
+      if (graph == null || graph.nextCreate == null) {
+        throw new IllegalStateException("Unexpected call to createInstance() for " + type);
+      }
+      InstanceCreator<?> creator = instanceCreators.get(type);
+      Object result = creator.createInstance(type);
+      graph.nextCreate.value = result;
+      graph.nextCreate = null;
+      return result;
+    }
+  }
+
+  static class Graph {
+    /**
+     * The graph elements. On serialization keys are objects (using an identity
+     * hash map) and on deserialization keys are the string names (using a
+     * standard hash map).
+     */
+    private final Map<Object, Element<?>> map;
+
+    /**
+     * The queue of elements to write during serialization. Unused during
+     * deserialization.
+     */
+    private final Queue<Element> queue = new LinkedList<Element>();
+
+    /**
+     * The instance currently being deserialized. Used as a backdoor between
+     * the graph traversal (which needs to know instances) and instance creators
+     * which create them.
+     */
+    private Element nextCreate;
+
+    private Graph(Map<Object, Element<?>> map) {
+      this.map = map;
+    }
+
+    /**
+     * Returns a unique name for an element to be inserted into the graph.
+     */
+    public String nextName() {
+      return "0x" + Integer.toHexString(map.size() + 1);
+    }
+  }
+
+  /**
+   * An element of the graph during serialization or deserialization.
+   */
+  static class Element<T> {
+    /**
+     * This element's name in the top level graph object.
+     */
+    private final String id;
+
+    /**
+     * The value if known. During deserialization this is lazily populated.
+     */
+    private T value;
+
+    /**
+     * This element's type adapter if known. During deserialization this is
+     * lazily populated.
+     */
+    private TypeAdapter<T> typeAdapter;
+
+    /**
+     * The element to deserialize. Unused in serialization.
+     */
+    private final JsonElement element;
+
+    Element(T value, String id, TypeAdapter<T> typeAdapter, JsonElement element) {
+      this.value = value;
+      this.id = id;
+      this.typeAdapter = typeAdapter;
+      this.element = element;
+    }
+
+    void write(JsonWriter out) throws IOException {
+      typeAdapter.write(out, value);
+    }
+
+    void read(Graph graph) throws IOException {
+      if (graph.nextCreate != null) {
+        throw new IllegalStateException("Unexpected recursive call to read() for " + id);
+      }
+      graph.nextCreate = this;
+      value = typeAdapter.fromJsonTree(element);
+      if (value == null) {
+        throw new IllegalStateException("non-null value deserialized to null: " + element);
+      }
+    }
+  }
+}

+ 98 - 0
src/main/java/commons/utility/JSon/JSonBuilder.java

@@ -0,0 +1,98 @@
+package commons.utility.JSon;
+
+import java.lang.reflect.Type;
+import java.util.Calendar;
+import java.util.List;
+
+import net.sf.json.JSONObject;
+
+import com.google.gson.ExclusionStrategy;
+import com.google.gson.FieldAttributes;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonDeserializationContext;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParseException;
+import com.google.gson.JsonParser;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.JsonSerializationContext;
+import com.google.gson.JsonSerializer;
+
+public class JSonBuilder {
+
+	
+	public static String toJson(Object obj) {
+		GsonBuilder gsonBuilder = new GsonBuilder().registerTypeAdapter(Calendar.class, new CalendarSerializer());
+		Gson gson = gsonBuilder.setDateFormat("dd/MM/yyyy").serializeNulls().create();
+		return gson.toJson(obj);
+	}
+
+	
+   public static class Esclusioni implements ExclusionStrategy {
+
+        private Class<?> c;
+        private List<String> fieldNames;
+        public Esclusioni(List<String> fieldsToExclude) throws SecurityException, NoSuchFieldException, ClassNotFoundException
+        {
+//	        	if (fqfn.lastIndexOf(".")>0)
+//	        		c = Class.forName(fqfn.substring(0, fqfn.lastIndexOf(".")));
+//	        	else
+//        			c = null;
+            this.fieldNames = fieldsToExclude;// fqfn.substring(fqfn.lastIndexOf(".")+1);
+        }
+        public boolean shouldSkipClass(Class<?> arg0) {
+            return false;
+        }
+
+        public boolean shouldSkipField(FieldAttributes f) {
+        	return (fieldNames.indexOf(f.getName())>=0);
+            //return (f.getDeclaringClass() == c && f.getName().equals(fieldName));
+        }
+
+    }
+	   
+	public static String toJson(Object obj, List<String> fldToExclude) {
+		try {
+			GsonBuilder gsonBuilder = new GsonBuilder().registerTypeAdapter(Calendar.class, new CalendarSerializer());
+			Gson gson = gsonBuilder.setDateFormat("dd/MM/yyyy").setExclusionStrategies(new Esclusioni(fldToExclude)).serializeNulls().create();
+			return gson.toJson(obj);
+
+		} catch (SecurityException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		} catch (NoSuchFieldException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		} catch (ClassNotFoundException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		}
+		
+		return "";
+
+	
+	}
+
+
+	public static <T> T JsonToObj(String json, Type typeOfT) {
+		//JsonParser parser = new JsonParser();
+		//JsonObject obj = parser.parse(json).getAsJsonObject();
+
+
+		
+		GsonBuilder gsonBuilder = new GsonBuilder().registerTypeAdapter(Calendar.class, new CalendarSerializer());
+		Gson gson = gsonBuilder.setDateFormat("dd/MM/yyyy HH:mm").create();
+		T res = gson.fromJson(json,typeOfT);
+		return res;
+	}
+
+	public static JSONObject toJSONObject(String json) {
+		Gson gson = new GsonBuilder().setDateFormat("dd/MM/yyyy HH:mm").create();
+		return null;
+	}
+	
+
+	
+}

+ 39 - 0
src/main/java/commons/utility/JSon/JsonCalendarDeserializer.java

@@ -0,0 +1,39 @@
+package commons.utility.JSon;
+
+import java.io.IOException;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.DeserializationContext;
+import com.fasterxml.jackson.databind.JsonDeserializer;
+import org.springframework.stereotype.Component;
+
+@Component
+public class JsonCalendarDeserializer extends JsonDeserializer<Calendar> {
+	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
+
+	@Override
+	public Calendar deserialize(JsonParser jp, DeserializationContext ctxt)
+			throws IOException, JsonProcessingException {
+
+		String date = jp.getText();
+		
+		if (date==null||date.isEmpty())
+			return null;
+		
+        try {
+            Date data= dateFormat.parse(date);
+            Calendar res = new GregorianCalendar();
+            res.setTime(data);
+            return res;
+        } catch (ParseException e) {
+            throw new RuntimeException(e);
+        }
+
+	}
+}

+ 25 - 0
src/main/java/commons/utility/JSon/JsonCalendarSerializer.java

@@ -0,0 +1,25 @@
+package commons.utility.JSon;
+
+import java.io.IOException;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonSerializer;
+import com.fasterxml.jackson.databind.SerializerProvider;
+import org.springframework.stereotype.Component;
+
+@Component
+public class JsonCalendarSerializer extends JsonSerializer<Calendar> {
+	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
+	 
+    @Override
+    public void serialize(Calendar date, JsonGenerator gen, SerializerProvider provider)
+            throws IOException, JsonProcessingException {
+ 
+        String formattedDate = dateFormat.format(date.getTime());
+ 
+        gen.writeString(formattedDate);
+    }
+}

+ 121 - 0
src/main/java/commons/utility/Mail.java

@@ -0,0 +1,121 @@
+package commons.utility;
+
+// import the JavaMail packages
+import java.io.File;
+import java.util.Properties;
+
+import jakarta.activation.DataHandler;
+import jakarta.activation.FileDataSource;
+import jakarta.mail.Message;
+import jakarta.mail.MessagingException;
+import jakarta.mail.Part;
+import jakarta.mail.Session;
+import jakarta.mail.Transport;
+import jakarta.mail.internet.AddressException;
+import jakarta.mail.internet.InternetAddress;
+import jakarta.mail.internet.MimeBodyPart;
+import jakarta.mail.internet.MimeMessage;
+import jakarta.mail.internet.MimeMultipart;
+
+import commons.exception.ZMailException;
+
+public class Mail
+{
+	private String smtpServer;
+	private int port;
+	
+	public Mail(String smtp)
+	{
+		this.port = -1;
+		int portPos = smtp.lastIndexOf(":");
+		if (portPos >= 0) {
+			if ((portPos < (smtp.length()-1))) {
+				try {
+					this.port = Integer.parseInt(smtp.substring(portPos+1));
+				} catch (Exception e) {				
+				}
+			}
+			smtp = smtp.substring(0, portPos);
+		}
+		this.smtpServer = smtp;		
+	}
+
+	public Mail(String smtp, int port)
+	{
+		this.smtpServer = smtp;
+		this.port = port;
+	}
+
+	public boolean Send(String from, String[] to, String subject, String text, String[] attachments, String MIME_TYPE) throws ZMailException
+	{
+		// create some properties and get the default Session
+		try
+		{
+			Properties properties = new Properties();
+			properties.put("mail.smtp.host", this.smtpServer);
+			if (port > 0) properties.put("mail.smtp.port", Integer.toString(this.port));
+			Session session = Session.getInstance(properties, null);
+			// create a message
+			MimeMessage msg = new MimeMessage(session);
+			msg.setFrom(new InternetAddress(from));
+			
+			InternetAddress[] address = new InternetAddress[to.length]; 
+        	for (int i = 0; i < to.length; i++)
+            {
+				address[i] = new InternetAddress(to[i]);
+            }
+        
+			//InternetAddress[] address = { new InternetAddress(to)};
+			msg.setRecipients(Message.RecipientType.TO, address);
+			msg.setSubject(subject);
+			// create and fill the first message part
+			MimeMultipart mp = new MimeMultipart();
+			MimeBodyPart message = new MimeBodyPart();
+			message.setDisposition(Part.INLINE);
+			message.setContent(text, MIME_TYPE);
+			mp.addBodyPart(message);
+			if (attachments != null)
+			{
+				for (int i = 0; i < attachments.length; i++)
+				{
+				    if (attachments[i] != null) {
+					    MimeBodyPart file_part = new MimeBodyPart();
+						File file = new File(attachments[i]);
+						FileDataSource fds = new FileDataSource(file);
+						DataHandler dh = new DataHandler(fds);
+						file_part.setFileName(file.getName());
+						file_part.setDisposition(Part.ATTACHMENT);
+						file_part.setDescription("Attached file: " + file.getName());
+						file_part.setDataHandler(dh);
+						mp.addBodyPart(file_part);
+				    }
+				}
+			}
+			// add the Multipart to the message
+			msg.setContent(mp);
+			// send the message
+			Transport.send(msg);
+			return true;
+		}
+		catch (AddressException e)
+		{
+			throw new ZMailException(e);
+		}
+		catch (MessagingException e)
+		{
+			throw new ZMailException(e);
+		}
+	}
+	public boolean Send(String from, String[] to, String subject, String text, String[] attachments) throws ZMailException
+	{
+		return Send(from, to, subject, text, attachments, "text/plain; charset=iso-8859-1");
+	}
+	public boolean Send(String from, String to, String subject, String text, String[] attachments, String MIME_TYPE) throws ZMailException
+	{
+		return Send(from, new String[]{to}, subject, text, attachments, MIME_TYPE);
+	}
+	public boolean Send(String from, String to, String subject, String text, String[] attachments) throws ZMailException
+	{
+		return Send(from, to, subject, text, attachments, "text/plain; charset=iso-8859-1");
+	}
+}

+ 12 - 0
src/main/java/commons/utility/MutableHolder.java

@@ -0,0 +1,12 @@
+package commons.utility;
+
+public class MutableHolder<T> {
+    public T value;
+
+    public MutableHolder() {
+    }
+
+    public MutableHolder(T value) {
+        this.value = value;
+    }
+}

+ 203 - 0
src/main/java/commons/utility/NumberUtility.java

@@ -0,0 +1,203 @@
+package commons.utility;
+
+import java.math.BigDecimal;
+import java.text.DecimalFormat;
+import java.text.DecimalFormatSymbols;
+
+
+public class NumberUtility {
+
+	public static boolean isNumeric(String str)
+	{
+	  return str.matches("-?\\d+(\\.\\d+)?");  
+	}
+
+	
+	public static int arrotonda(double valore)
+	{
+		//valore = Math.round(valore);
+		//int ritorno = new Double(valore).intValue();
+		return arrotonda(valore,2);
+	}
+	public static int arrotonda(double valore,int precision)
+	{
+		BigDecimal value = new BigDecimal(valore);
+		if(valore > (double)0) {
+			value = value.setScale(2,BigDecimal.ROUND_HALF_UP);
+		}
+		else {
+			value = value.setScale(2,BigDecimal.ROUND_HALF_DOWN);
+		}
+		return new Double(Math.round(value.doubleValue())).intValue();
+	}
+
+	public static Double arrotondaDouble(double valore,int precision)
+	{
+		BigDecimal value = new BigDecimal(valore);
+		if(valore > (double)0)
+		{
+			value = value.setScale(precision,BigDecimal.ROUND_HALF_UP);
+		}
+		else
+		{
+			value = value.setScale(precision,BigDecimal.ROUND_HALF_DOWN);
+		}
+		return new Double(value.doubleValue());
+	}
+
+	public static double calcolaPercentuale(double importo, double percentuale)
+	{
+		return importo * percentuale / 100.0;
+	}
+
+	public static double dividi(double dividendo, double divisore)
+	{
+		if (divisore != 0)
+		{
+			return dividendo / divisore;
+		}
+		return 0;
+	}
+
+	/**
+	 * Tentativi falliti
+	 *  public static double truncateNumber(double value, int precision)
+		{
+			double x = 0;
+
+			try
+			{
+				BigDecimal b1 = new BigDecimal(value);
+				return b1.setScale(precision, BigDecimal.ROUND_DOWN).doubleValue();
+			}
+			catch (Exception e) {
+				System.out.println("Modifica truncate:");
+				e.printStackTrace();
+			}
+			return x;
+		}
+
+		public static double truncateNumber(double value,int precision)
+		{
+			double mult = Math.pow(10.0,precision);
+			double x = value > 0 ? Math.floor(value * mult) / mult : Math.ceil(value * mult) / mult;
+
+			return new Double(x).doubleValue();
+		}
+
+		public static double truncateNumber(double value, int precision)
+		{
+			double x = 0;
+
+			try
+			{
+				int parteIntera = (int) (value * Math.pow(10.0,precision));
+				return parteIntera / Math.pow(10.0, precision);
+			}
+			catch (Exception e) {
+				System.out.println("Modifica truncate:");
+				e.printStackTrace();
+			}
+			return x;
+		}
+
+	public static double truncateNumber(double value, int precision)
+	{
+		double x = arrotondaDouble(value, precision + 3);
+		String pattern = "0.0";
+
+		for(int i = 0 ; i < precision; i++)
+		{
+			pattern += "#";
+		}
+		DecimalFormatSymbols dfs = new DecimalFormatSymbols();
+		dfs.setDecimalSeparator('.');
+
+		String format = new DecimalFormat(pattern,dfs).format(value);
+		if(format.substring(format.indexOf(".") +1 ,format.length()).length() > precision)
+		{
+			format = format.substring(0,format.length() - 1);
+		}
+		return Double.parseDouble(format);
+	}
+	*/
+	/***
+	 * Da usare solo in liquidazione
+	 */
+//	public static double truncateNumber(double value, int precision)
+//	{
+//		String valore = Integer.toString((int)value) + ".";
+//		value -= (int)value;
+//		for(int i = 0; i < precision; i++)
+//		{
+//			value *= 10;
+//			valore += Integer.toString((int)value);
+//			value -= (int)value;
+//		}
+//
+//		return Double.parseDouble(valore);
+//	}
+
+	public static double truncateNumber(double value, int precision)
+	{
+		double valore = arrotondaDouble(value, precision + 3);
+		String pattern = "0.0";
+
+		for(int i = 0 ; i < precision + 3; i++)
+		{
+			pattern += "#";
+		}
+		DecimalFormatSymbols dfs = new DecimalFormatSymbols();
+		dfs.setDecimalSeparator('.');
+
+		String format = new DecimalFormat(pattern,dfs).format(valore);
+		if(format.substring(format.indexOf(".")+1 ,format.length()).length() > precision)
+		{
+			int lunghezza = format.indexOf(".") + precision + 1;
+			format = format.substring(0,Math.min(lunghezza,format.length()));
+		}
+		return Double.parseDouble(format);
+	}
+
+
+	public static int valoreAssoluto(int parziale)
+	{
+		return Math.abs(parziale);
+	}
+
+	/**
+	 * Arrotonda per eccesso un valore decimale.
+	 * @param value
+	 * @return valore intero arrotondato per eccesso
+	 */
+	public static int arrotondaPerEccesso(double value)
+	{
+		BigDecimal valRet = new BigDecimal(value);
+		//approssimo per eccesso
+		valRet = valRet.setScale(0, BigDecimal.ROUND_UP);
+		return valRet.intValue();
+	}
+	
+	/**
+	 * Arrotonda per difetto un valore decimale.
+	 * @param value
+	 * @return valore intero arrotondato per difetto
+	 */	
+	public static int arrotondaPerDifetto(double value)
+	{
+		BigDecimal valRet = new BigDecimal(value);
+		//approssimo per eccesso
+		valRet = valRet.setScale(0, BigDecimal.ROUND_DOWN);
+		return valRet.intValue();
+	}
+
+	public static double rapportaAiGiorni(double importo, int giorni)
+	{
+		return importo * giorni / 365;
+	}
+
+	public static double rapportaAiMesi(double importo, int mesi)
+	{
+		return importo * mesi / 12;
+	}
+}

+ 258 - 0
src/main/java/commons/utility/OutputZipFile.java

@@ -0,0 +1,258 @@
+package commons.utility;
+
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+import commons.exception.ZCompressException;
+
+/**	Gestione di un file zip in scrittura
+ */
+public class OutputZipFile
+{
+	public static final String ENTRY_SEPARATOR = "/";
+	public static final int BUFFER = 2048;
+	private ZipOutputStream out;
+	private List<String> entries = null;
+	
+	public OutputZipFile(ZipOutputStream outStream)
+	{
+		out = outStream;
+		entries = new ArrayList<String>();
+	}
+	
+	/**	Verifica se una entry esiste
+	 * @param entryName
+	 * @return
+	 */
+	private boolean checkEntry(String entryName)
+	{
+		return Collections.binarySearch(entries,entryName) >= 0;
+	}
+	
+	/**	Aggiunge una entry alla lista
+	 * @param entryName
+	 */
+	private void addEntry(String entryName)
+	{
+		entries.add(entryName);
+		Collections.sort(entries);
+	}
+	
+	/**	Forza la chiusura dell'entry corrente
+	 * @throws ZCompressException
+	 */
+	private void ensureCloseEntry() throws ZCompressException
+	{
+		try
+		{
+			out.closeEntry();
+		}
+		catch(IOException ioE)
+		{
+			throw new ZCompressException(ioE);
+		}		
+	}
+
+	/**	Normalizza il nome di una entry eliminando tutti i / all'inizio e 
+	 * 	rendendo i separatori tutti come /
+	 * @param entryName
+	 * @return
+	 */
+	private String normalizeEntry(String entryName)
+	{
+		String en = entryName.replace('\\',OutputZipFile.ENTRY_SEPARATOR.charAt(0));
+		while(en.length() > 0 && OutputZipFile.ENTRY_SEPARATOR.charAt(0) == en.charAt(0))
+		{
+			en = en.substring(1);
+		}
+		return en;
+	}
+	
+	/**	Forza,se non esiste,il / alla fine dell'entry
+	 * @param entryName
+	 * @return
+	 */
+	private String ensureSlash(String entryName)
+	{
+		String en = entryName;
+		if(!en.endsWith(OutputZipFile.ENTRY_SEPARATOR))
+			en += OutputZipFile.ENTRY_SEPARATOR.charAt(0);	
+		return en;
+	}
+	
+	/**	Aggiunge una dir al file
+	 * @param entryName
+	 * @throws ZCompressException
+	 */
+	private void addDirEntry(String entryName) throws ZCompressException
+	{
+		final String en = ensureSlash(normalizeEntry(entryName));
+		if(checkEntry(en))	return;
+		try
+		{
+			ZipEntry entry = new ZipEntry(en);
+			entry.setMethod(ZipEntry.STORED);
+			entry.setCompressedSize(0L);
+			entry.setSize(0L);
+			entry.setCrc(0L);
+			out.putNextEntry(entry);
+		}
+		catch(IOException ioE)
+		{
+			throw new ZCompressException(ioE);
+		}
+		finally
+		{
+			ensureCloseEntry();
+			addEntry(en);
+		}
+	}
+	
+	/**	Aggiunge un blocco usando come entryID un nome
+	 * @param inputfileName
+	 * @throws ZCompressException
+	 */
+	private void addBlock(byte[] data,String entryName) throws ZCompressException
+	{
+		final String en = normalizeEntry(entryName);
+		if(checkEntry(en))	return;
+		try
+		{
+			if(null == out)
+			{
+				throw new ZCompressException("File not open for write.");
+			}
+			ZipEntry entry = new ZipEntry(en);
+			entry.setMethod(ZipEntry.DEFLATED);
+			out.putNextEntry(entry);
+			out.write(data);
+		}
+		catch(IOException e)
+		{
+			throw new ZCompressException(e);
+		}
+		finally
+		{
+			ensureCloseEntry();
+			addEntry(en);
+		}
+	}
+	
+	private void addFile(File f,String entryName) throws ZCompressException
+	{
+		final String en = normalizeEntry(entryName);
+		if(checkEntry(en))	return;
+		if(null == out)
+		{
+			throw new ZCompressException("File not open for write.");
+		}
+		
+		BufferedInputStream inputfileStream = null;
+		try
+		{
+			inputfileStream = new BufferedInputStream(new FileInputStream(f));
+			ZipEntry entry = new ZipEntry(entryName);
+			entry.setMethod(ZipEntry.DEFLATED);
+			out.putNextEntry(entry);
+			byte[] buffer = new byte[BUFFER];
+			int count = 0;
+			while(-1 != (count = inputfileStream.read(buffer,0,buffer.length)))
+			{
+				out.write(buffer,0,count);
+			}
+		}
+		catch(IOException ioE)
+		{
+			throw new ZCompressException(ioE);
+		}
+		finally
+		{			
+			try
+			{
+				ensureCloseEntry();
+				addEntry(en);
+				if(null != inputfileStream)
+					inputfileStream.close();
+			}
+			catch(IOException ioE)
+			{
+				throw new ZCompressException(ioE);
+			}
+		}
+	}
+	
+	//	Public intf
+	public void addDirectory(String entryName) throws ZCompressException
+	{
+		addDirEntry(entryName);
+	}
+	
+	/**	Aggiunge un file allo zip
+	 * @param file
+	 * @param entryPath
+	 * @param addFullPath true per aggiungere come entry il nome completo dell'entry o solo l'ultima parte
+	 * @throws ZCompressException
+	 */
+	public void addFile(File file,String entryPath,boolean addFullPath) throws ZCompressException
+	{
+		String en = entryPath;
+		if(en.endsWith(OutputZipFile.ENTRY_SEPARATOR))
+			throw new ZCompressException("Entries must end with a /");
+		if(!addFullPath)
+		{
+			//	Check for dir path...
+			int lastSlashIndex = en.lastIndexOf(OutputZipFile.ENTRY_SEPARATOR);
+			if(-1 != lastSlashIndex)
+				en = en.substring(lastSlashIndex+1);
+		}		
+		addFile(file,en);
+	}
+
+	/**	Aggiunge un blocco di dati allo zip
+	 * @param file
+	 * @param entryPath
+	 * @param addFullPath true per aggiungere come entry il nome completo dell'entry o solo l'ultima parte
+	 * @throws ZCompressException
+	 */
+	public void addFile(byte[] data,String entryPath,boolean addFullPath) throws ZCompressException
+	{
+		String en = entryPath;
+		if(en.endsWith(OutputZipFile.ENTRY_SEPARATOR))
+			throw new ZCompressException("Entries must end with a /");
+		if(!addFullPath)
+		{
+			//	Check for dir path...
+			int lastSlashIndex = en.lastIndexOf(OutputZipFile.ENTRY_SEPARATOR);
+			if(-1 != lastSlashIndex)
+				en = en.substring(lastSlashIndex+1);
+		}		
+		
+		addBlock(data,en);		
+	}
+	
+	/**	Chiude il file zip
+	 * @throws ZCompressException
+	 */
+	public void close() throws ZCompressException
+	{
+		try
+		{
+			out.close();
+		}
+		catch (IOException e)
+		{
+			throw new ZCompressException(e);
+		}
+		finally
+		{
+			out = null;
+		}
+	}
+}

+ 24 - 0
src/main/java/commons/utility/PasswordCypher.java

@@ -0,0 +1,24 @@
+package commons.utility;
+
+public class PasswordCypher {
+
+	public static String cryptPassword(String pwd) {
+		if (pwd==null)
+			return "";
+		byte[] bPwd = pwd.getBytes();
+		for (byte i=0;i<bPwd.length;i++)
+			bPwd[i] = (byte) (bPwd[i] + (i + 1));
+		return new String(bPwd);
+	}
+
+	
+	public static String decryptPassword(String pwd) {
+		if (pwd==null)
+			return "";
+		byte[] bPwd = pwd.getBytes();
+		for (byte i=0;i<bPwd.length;i++)
+			bPwd[i] = (byte) (bPwd[i] -(i + 1) );
+		return new String(bPwd);
+	}
+	
+}

+ 41 - 0
src/main/java/commons/utility/ProxyInfo.java

@@ -0,0 +1,41 @@
+package commons.utility;
+
+import commons.utility.database.NullValue;
+
+public class ProxyInfo {
+
+	private String address = NullValue.STRING;
+	private int port = NullValue.NUMBER;
+	private String username = NullValue.STRING;
+	private String password = NullValue.STRING;
+	
+	public ProxyInfo() {
+		
+    }
+	public String getAddress() {
+    	return address;
+    }
+	public void setAddress(String address) {
+    	this.address = address;
+    }
+	public int getPort() {
+    	return port;
+    }
+	public void setPort(int port) {
+    	this.port = port;
+    }
+	public String getUsername() {
+    	return username;
+    }
+	public void setUsername(String username) {
+    	this.username = username;
+    }
+	public String getPassword() {
+    	return password;
+    }
+	public void setPassword(String password) {
+    	this.password = password;
+    }
+	
+	
+}

+ 205 - 0
src/main/java/commons/utility/SeparatedText.java

@@ -0,0 +1,205 @@
+package commons.utility;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * 	Gestisce una lista di oggetti come testo separato da un
+ * 	delimitatore
+ */
+public class SeparatedText
+{
+	static public class Factory
+	{
+		static public SeparatedText create(Object[] values,char delimiter)
+		{
+			SeparatedText st = new SeparatedText();
+			st.setDelimiter(delimiter);
+			st.setValues(Arrays.asList(values));
+			return st;
+		}
+
+		static public SeparatedText create(List values,char delimiter)
+		{
+			SeparatedText st = new SeparatedText();
+			st.setDelimiter(delimiter);
+			st.setValues(values);
+			return st;
+		}
+
+		static public SeparatedText create(Object[] values)
+		{
+			return create(values,',');
+		}
+
+		static public SeparatedText create(List values)
+		{
+			return create(values,',');
+		}
+
+		static public SeparatedText create(String textValues,char delimiter)
+		{
+			return new SeparatedText(textValues,delimiter);
+		}
+
+		static public SeparatedText create(String textValues)
+		{
+			return create(textValues,',');
+		}
+	}
+	
+	private String separatedText;
+	private char delimiter;
+	private List values;
+	
+	public SeparatedText()
+	{
+		super();
+		setDelimiter(',');
+	}
+
+	public SeparatedText(String text)
+	{
+		this(text,',');
+	}
+
+	public SeparatedText(String text,char delimiter)
+	{
+		super();
+		setDelimiter(delimiter);
+		setSeparatedText(text);
+	}
+	
+	public char getDelimiter()
+	{
+		return delimiter;
+	}
+
+	public String getSeparatedText()
+	{
+		return separatedText;
+	}
+
+	public void setDelimiter(char c)
+	{
+		delimiter = c;
+	}
+
+	public void setSeparatedText(String text)
+	{
+		separatedText = text;
+		values = split(text,getDelimiter());
+	}
+
+	public List getValues()
+	{
+		return values;
+	}
+
+	public void setValues(List values)
+	{
+		this.values = values;
+		separatedText = join(values,getDelimiter());
+	}
+
+	static public List split(String text,char delimiter)
+	{
+		List l = new ArrayList();
+		boolean inQuotes = false;
+		StringBuffer part = new StringBuffer();
+		
+		for(int i = 0;i < text.length();i++)
+		{
+			char ch = text.charAt(i);
+			
+			if(delimiter == ch || ' ' == ch)
+			{
+				//	Fine della stringa!
+				if(!inQuotes)
+				{
+					l.add(part.toString());
+					part.setLength(0);
+					continue;
+				}
+			}
+			else
+			{
+				if('\"' == ch)
+				{
+					//	Leggi il successivo...
+					if(i+1 < text.length())
+					{
+						//	Se il successivo non ? un " allora deve essere uno
+						//	spazio oppure un separatore
+						if(text.charAt(i+1) != '\"')
+						{
+							inQuotes = !inQuotes;
+							continue;
+						}
+						else
+						{
+							//	Questo " deve essere escluso...
+							++i;
+							//	...ed il prossimo carattere verr? inserito!
+						}
+					}
+					else
+					{
+						assert(inQuotes);
+						inQuotes = !inQuotes;
+						continue;
+					}
+				}
+			}
+			part.append(ch);
+		}
+		assert(inQuotes);
+		//	Aggiungi l'ultima stringa se non ? vuota oppure se ? vuota ma l'ultimo carattere
+		//	? un separatore
+		if(	part.length() > 0 ||
+			(0 == part.length() && text.length() > 0 && delimiter == text.charAt(text.length()-1))
+		)
+			l.add(part.toString());
+			
+		return l;
+	}
+	
+	static public String join(List values,char delimiter)
+	{
+		final StringBuffer ret = new StringBuffer();
+		boolean first = true;
+		for(Iterator i = values.iterator();i.hasNext();)
+		{
+			if(!first)	ret.append(delimiter);
+			first = false;
+			ret.append(createSDFText(i.next().toString(),delimiter));
+		}
+		return ret.toString();
+	}
+	
+	private static String createSDFText(String value,char delimiter)
+	{
+		final StringBuffer ret = new StringBuffer();
+		boolean needQuotes = false;
+		for(int i = 0;i < value.length();i++)
+		{
+			final char ch = value.charAt(i);
+			if(delimiter == ch || ' ' == ch)
+			{
+				needQuotes = true;
+			}
+			else
+			{
+				if('\"' == ch)
+				{
+					ret.append('\"');
+				}
+			}
+			ret.append(ch);
+		}
+		if(needQuotes)	ret.insert(0,'\"').append('\"');
+		return ret.toString();
+	}
+}

+ 190 - 0
src/main/java/commons/utility/StringUtility.java

@@ -0,0 +1,190 @@
+package commons.utility;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+import java.util.StringTokenizer;
+
+/**
+ * Classe di utilita&grave; per la gestione e la formattazione
+ * delle stringhe.
+ *
+ * @author olienr
+ */
+public class StringUtility {
+
+	/**
+	 * Splitta il testo in tante righe di lunghezza <tt>maxRowLen</tt>.
+	 * Il testo viene diviso inizialmente per i singoli token
+	 * secondo le politiche della classe <tt>StringTokenizer</tt>.
+	 * Se una parola supera la lunghezza massima viene messa tutta
+	 * sulla stessa riga.
+	 * Se il testo ? vuoto il metodo ritorna un array di stringhe
+	 * contenente solo la stringa vuota.
+	 *
+	 * @param testo - testo da splittare
+	 * @param maxRowLen - lunghezza massima consentita
+	 * @return - array di stringhe concatenate di lunghezza massima <tt>maxRowLen</tt>
+	 */
+	public static String[] split(String testo, int maxRowLen) {
+
+		List<String> righe = new ArrayList<String>();
+		StringTokenizer testoTkn = new StringTokenizer(testo);
+
+		String primoTkn;
+		/* se vuoto torno array stringa con un elemento: "" */
+		if (!empty(testo)){
+			primoTkn = testoTkn.nextToken();
+		}
+		else {
+			return new String [] {""};
+		}
+
+		int i = 0;
+		righe.add(i, primoTkn);
+
+		String tmp;
+		String oldToken;
+		while (testoTkn.hasMoreTokens()) {
+			tmp = testoTkn.nextToken();
+			oldToken = righe.get(i);
+			if ((oldToken + " " + tmp).length() > maxRowLen) {
+				i++;
+				righe.add(i, tmp);
+			}
+			else {
+				/*
+				 * non shifta elemento come add, ma
+				 * lo rimuove e lo inserisce.
+				 */
+				righe.set(i, oldToken + " " + tmp);
+			}
+		}
+
+		return righe.toArray(new String[righe.size()]);
+	}
+
+	/**
+	 * Verifica se una string e&grave; vuota o non esiste
+	 *
+	 * @param la stringa da contrllare
+	 * @return true se la stringa e&grave; vuota o non esiste
+	 */
+	public static boolean empty(String value) {
+		return (value == null || value.length() == 0);
+	}
+	
+	public static boolean empty(String value, boolean trim) {
+		String _value = value != null ? value : "";
+		_value = trim ? _value.trim() : _value;
+		return _value.length() == 0;
+		 
+	}
+
+	/**
+	 * Ritorna una stringa con la prima lettera maiuscola
+	 * @param value
+	 * @return
+	 */
+	public static String capitalize(String value) {
+		if( empty(value) ) return value;
+		String firstLetter = value.substring(0,1);
+	    String remainder   = value.substring(1);
+	    return firstLetter.toUpperCase() + remainder;
+	}
+	
+
+	
+/*FILLER STRING*/	
+	public enum FillerPosition {FILL_LEFT, FILL_RIGHT}
+	/**
+	 * Filla una stringa <code>value</code>, di default a dx, per una lunghezza pari a <code>length</code> 
+	 * usando il carattere <code>filler</code>
+	 * @param value
+	 * @param length
+	 * @param filler
+	 * @return
+	 */
+	public static String fillString(String value, final int length, final char filler){
+		return fillString(value, length, filler, FillerPosition.FILL_RIGHT);
+	}
+	/**
+	 * Filla una stringa <code>value</code> per una lunghezza pari a <code>length</code> 
+	 * usando il carattere <code>filler</code>
+	 * @param value
+	 * @param length
+	 * @param filler
+	 * @param position indica se fillare a destra o a sinistra del valore
+	 * @return
+	 */
+	public static String fillString(String value, final int length, final char filler, final FillerPosition position){
+		if (value.length() >= length) 
+			return value.substring(0,length);
+		char[] valoreIniziale = value.toCharArray();
+		char[] valoreFinale = new char[length];
+		Arrays.fill(valoreFinale, filler);
+		
+		int startPosFill = 0;
+		if (position == FillerPosition.FILL_LEFT){
+			startPosFill = valoreFinale.length -  valoreIniziale.length;
+		}
+		
+		for (int i = 0; i < valoreIniziale.length; i++){
+			valoreFinale[startPosFill + i] = valoreIniziale[i];
+		}
+		
+		return new String(valoreFinale);
+	}
+
+	/**
+	 * Converte una lista di stringhe separando i singoli elementi
+	 * con un separatore. 
+	 * @param lista di stinghe
+	 * @param token il separatore
+	 * @return
+	 */
+	public static String convertiInRiga(List<String> lista, String separatore) {
+		StringBuffer buf = new StringBuffer();
+		Iterator<String> i = lista.iterator();
+		boolean hasNext = i.hasNext();
+		while (hasNext) {
+			String o = i.next();
+			buf.append(o);
+			hasNext = i.hasNext();
+			if (hasNext)
+				buf.append(separatore);
+		}
+		return buf.toString();
+	}
+
+	/**
+	 * Resitituisce la parte più a sinistra di una stringa, controllando di non eccedere 
+	 * la capienza massima di caratteri
+	 * 
+	 * Simone 02.09.2008
+	 * @param string
+	 * @param maxlen
+	 * @return
+	 */
+	public static String leftString(String string, int maxlen){
+		
+		int max = string.length() >= maxlen ? maxlen : string.length(); 
+		
+		return string.substring(0,max);
+	}
+
+	
+	/**
+	 * 
+	 * @param string
+	 * @param fromPos
+	 * @param length
+	 * @return sottostringa di string che parte da posizione fromPos, lunga al max. length caratteri
+	 */
+	public static String EstraiSubstringa(String string, int fromPos, int length) {
+		return fillString(string, fromPos+length, ' ').substring(fromPos, fromPos + length);
+	}
+	
+	
+}

+ 704 - 0
src/main/java/commons/utility/UnproxyObject.java

@@ -0,0 +1,704 @@
+package commons.utility;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutput;
+import java.io.ObjectOutputStream;
+import java.io.Serializable;
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
+import org.hibernate.Hibernate;
+import org.hibernate.HibernateException;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.collection.spi.PersistentCollection;
+import org.hibernate.persister.entity.EntityPersister;
+import org.hibernate.proxy.HibernateProxy;
+import org.hibernate.proxy.LazyInitializer;
+import org.hibernate.type.Type;
+
+import commons.exception.ZSystemException;
+import commons.utility.database.hibernate.HibernateDatabase;
+
+/**	Funzioni di utilit? per eseguire una deep-copy di un oggetto legato
+ * 	alla sessione di Hibernate. L'oggetto risultante ? completamente
+ * 	libero da proxy!
+ */
+public final class UnproxyObject
+{
+	/**	La cache da utilizzare per comodo
+	 */
+	private class Cache
+	{
+		/**	Cache dei metadati raggruppati per classe	*/
+		private Map<Class<?>,EntityPersister> metadataClass = new HashMap<Class<?>, EntityPersister>();
+		/**	Lista degli oggetti replaced	*/
+		private Map<Object,Object> replacedObjects = new HashMap<Object, Object>();
+		/**	Lista delle collezioni replaced	*/
+		private Map<Object,Object> replacedCollections = new HashMap<Object, Object>();
+		
+		private Cache target;
+		
+		Cache()
+		{
+			target = this;
+		}
+		
+		Cache(final Cache target)
+		{
+			this.target = target;
+		}
+
+		@SuppressWarnings("unused")
+		private final Map<Class<?>, EntityPersister> getMetadataClass()
+		{
+			return target == null ? metadataClass : target.metadataClass;
+		}
+
+		private final Map<Object, Object> getNakedObjects()
+		{
+			return target == null ? replacedObjects : target.replacedObjects;
+		}
+
+		private final Map<Object, Object> getNakedCollections()
+		{
+			return target == null ? replacedCollections : target.replacedCollections;
+		}
+	}
+	
+	private SessionFactory sessionFactory;
+	/**	La lista delle collection che devono essere ricreate DOPO il processo
+	 * 	di unproxy.Da utilizzare quando le collection sono create da oggetti
+	 * 	creati parzialmente.
+	 */
+	private List<Object> rehashCollection;
+	/**	Cache con gli oggetti completamente costruiti (HibernateProxy -> nakedObject)
+	 */
+	private final Cache fullConstructedCache = new Cache();
+	/**	Cache con gli oggetti parzialmente costruiti (HibernateProxy -> nakedObject)
+	 */
+	private final Cache partiallyConstructedCache = new Cache();
+	
+	private UnproxyObject(final SessionFactory sessionFactory)
+	{
+		this.sessionFactory = sessionFactory;
+		rehashCollection = new ArrayList<Object>();
+	}
+	
+	/**	Instance a new empty object calling empty ctor
+	 * @param <T>
+	 * @param clazz
+	 * @return
+	 */
+	private final <T> T instance0(final Class<T> clazz)
+	{
+		try
+		{
+			return clazz.getConstructor().newInstance();
+		}
+		catch(Exception e)
+		{
+			throw new ZSystemException(e);
+		}
+	}
+	/**	Set the value of a field via reflection
+	 * @param f
+	 * @param target
+	 * @param value
+	 */
+	private final void setFieldValue(final Field f,final Object target,final Object value)
+	{
+		try
+		{
+			f.set(target, value);
+		}
+		catch(Exception e)
+		{
+			throw new ZSystemException(e);
+		}
+	}
+	/**	Get the value of a field via reflection
+	 * @param f
+	 * @param target
+	 * @param value
+	 */
+	private final Object getFieldValue(final Field f,final Object target)
+	{
+		try
+		{
+			return f.get(target);
+		}
+		catch(Exception e)
+		{
+			throw new ZSystemException(e);
+		}
+	}
+	/**	Verifica se un campo ? modificabile o meno (ovvero non ? final oppure static)
+	 * @param property il campo da controllare
+	 * @return
+	 */
+	private final boolean fieldIsModifiable(final Field property)
+	{
+		final int modifiers = property.getModifiers();
+		final boolean unmodifiable = Modifier.isFinal(modifiers) && Modifier.isStatic(modifiers);
+		return !unmodifiable;
+	}
+	/**	Estrazione di tutti i campi presenti in una classe e nelle sue superclassi
+	 * @param clazz
+	 * @return
+	 */
+	private final List<Field> retrieveFields(final Class<?> clazz)
+	{
+		final List<Field> fields = new ArrayList<Field>();
+		Class<?> currentClass = clazz;
+		do
+		{
+			fields.addAll(Arrays.asList(currentClass.getDeclaredFields()));
+			currentClass = currentClass.getSuperclass();
+		}	while(currentClass != null);
+		Collections.sort(fields, new Comparator<Field>(){
+			public int compare(Field o1, Field o2)
+			{
+				return o1.getName().compareTo(o2.getName());
+			}
+		});
+		return fields;
+	}
+	/**	Esegue la rimozione dei proxy di tutti gli oggetti di una collection
+	 * @param collectionClass l'implementazione reale della collection
+	 * @param collection la collection di origine
+	 * @return
+	 */
+	private final Collection<?> makeNakedCollection(final Class<?> collectionClass,final Collection<?> collection)
+	{
+		final Collection<Object> unproxiedCollection = (Collection<Object>) instance0(collectionClass);
+		for(final Object maybeProxy : collection)
+			unproxiedCollection.add(makeNakedObject(maybeProxy));
+		return unproxiedCollection;
+	}
+	/**	Esegue la rimozione dei proxy di un set ed eventualmente,nel caso gli oggetti aggiunti al Set
+	 * 	siano completati solo parzialmente,aggiunge la lista alle Collection da re-indicizzare
+	 * @param collectionClass
+	 * @param collection
+	 * @return
+	 */
+	private final Set<?> makeNakedSet(final Class<?> collectionClass,final Set<?> collection)
+	{
+		boolean rehashCollection = false;
+		//	Verifica se uno degli oggetti presenti nel Set ? solo parzialmente costruito!
+		for(final Iterator<?> maybeProxies = collection.iterator();!rehashCollection && maybeProxies.hasNext();)
+			rehashCollection = rehashCollection || null != getNakedObjectFromCache(partiallyConstructedCache, maybeProxies.next());
+		//	Ricrea la collection senza proxy
+		final Set<Object> unproxiedCollection = (Set<Object>) makeNakedCollection(collectionClass,collection);
+		//	Nel caso la collection fosse costruita su oggetti parzialmente costruiti allora
+		//	la collection ? da marcare per la re-indiicizzazione
+		if(rehashCollection)
+			addCollectionToRehasingList(unproxiedCollection);
+		return unproxiedCollection;
+	}
+	/**	Esegue la rimozione dei proxy di tutti gli oggetti di una map
+	 * @param collection la collection di origine
+	 * @return
+	 */
+	private final Map<?,?> makeNakedMap(final Map<?,?> collection)
+	{
+		boolean rehashCollection = false;
+		final Map<Object,Object> unproxiedMap = new HashMap<Object,Object>();
+		for(final Object key : collection.keySet())
+		{
+			//	Verifica se la chiave ? una
+			rehashCollection = rehashCollection || null != getNakedObjectFromCache(partiallyConstructedCache, key);
+			final Object maybeProxy = collection.get(key);
+			unproxiedMap.put(key,makeNakedObject(maybeProxy));
+		}
+		//	Nel caso la collection fosse costruita su oggetti parzialmente costruiti allora
+		//	la collection ? da marcare per la re-indiicizzazione
+		if(rehashCollection)
+			addCollectionToRehasingList(unproxiedMap);
+		return unproxiedMap;
+	}	
+	/**	Se una classe implementa {@link HibernateProxy} viene ritornato l'oggetto castato a HibernateProxy
+	 * @param maybeProxy
+	 * @return null se l'oggetto ? null oppure non ? un HibernateProxy
+	 */
+	private final HibernateProxy getHibernateProxy(final Object maybeProxy)
+	{
+		return maybeProxy instanceof HibernateProxy ? (HibernateProxy)maybeProxy : null;
+	}
+	/**	Controlla se un oggetto ? una {@link Collection} oppure una {@link Map}
+	 * @param maybeCollection
+	 * @return
+	 */
+	private final boolean isCollection(final Object maybeCollection)
+	{
+		return maybeCollection instanceof Collection || maybeCollection instanceof Map;
+	}
+	/**	Data una classe ritorna i metadati di mapping relativi
+	 * @param clazz
+	 * @return
+	 */
+	private final EntityPersister getClassMetadata(final Class<?> clazz)
+	{
+		EntityPersister value = null;
+		if(null != sessionFactory)
+			value = sessionFactory.unwrap(org.hibernate.engine.spi.SessionFactoryImplementor.class)
+				.getMappingMetamodel().getEntityDescriptor(clazz);
+		return value;
+	}
+	/**	Estrazione del mapping di Hibernate di una property.Per i component si una la
+	 * 	dot notation
+	 * @param entityPersister
+	 * @param propertyName
+	 * @return
+	 */
+	private final Type getHibernatePropertyType(final EntityPersister entityPersister,final String propertyName)
+	{
+		Type type = null;
+		if(null != entityPersister)
+		{
+			try
+			{
+				type = entityPersister.getPropertyType(propertyName);
+			}
+			catch(HibernateException e)
+			{
+			}
+		}
+		return type;
+	}
+	/**	Verifica se un oggetto richiede la rimozione del proxy
+	 * @param maybeProxy
+	 * @param propertyMapping
+	 * @return true se l'oggetto rispetta {@link UnproxyObject#getHibernateProxy(Object)} oppure
+	 * 	la mappatura riguarda un'associazione,un componente oppure una collection
+	 */
+	private final boolean objectShouldBeNaked(final Object maybeProxy,final Type propertyMapping)
+	{
+		return getHibernateProxy(maybeProxy) != null ||
+			(propertyMapping != null && (propertyMapping.isAssociationType() || propertyMapping.isComponentType() || propertyMapping.isCollectionType()));
+	}
+	/**	L'oggetto necessita di inizializzazione?
+	 * @param maybeProxy
+	 * @return
+	 */
+	private final boolean objectSholdBeInitialized(final Object maybeProxy)
+	{
+		return !Hibernate.isInitialized(maybeProxy);
+	}
+	/**	Dato un oggetto proxy viene ritornata la relativa versione
+	 * 	replace
+	 * @param La cache in cui fare la ricerca
+	 * @param proxyObject
+	 * @return null se non esiste nessun replace,il replace in caso contrario
+	 */
+	private final Object getNakedObjectFromCache(final Cache cache,final Object proxyObject)
+	{
+		if(cache.getNakedObjects().containsKey(proxyObject))
+			return cache.getNakedObjects().get(proxyObject);
+		if(cache.getNakedCollections().containsKey(proxyObject))
+			return cache.getNakedCollections().get(proxyObject);
+		return null;
+	}
+	/**	Associa ad un oggetto proxy la relativa implementazione naked
+	 * @param La cache a cui aggiungere l'oggetto
+	 * @param proxyObject
+	 * @param nakedObject
+	 */
+	private final void addNakedObjectToCache(final Cache cache,final Object proxyObject,final Object nakedObject)
+	{
+		if(isCollection(proxyObject))
+			cache.getNakedCollections().put(proxyObject, nakedObject);
+		else
+			cache.getNakedObjects().put(proxyObject, nakedObject);
+	}
+	/**	Rimuove un proxy da una cache
+	 * @param cache
+	 * @param proxyObject
+	 * @return
+	 */
+	private final Object removeNakedObjectFromCache(final Cache cache,final Object proxyObject)
+	{
+		if(isCollection(proxyObject))
+			return cache.getNakedCollections().remove(proxyObject);
+		else
+			return cache.getNakedObjects().remove(proxyObject);
+	}
+	/**	Aggiunge una {@link Collection} alla lista delle collection da re-indicizzare.
+	 * 	Senza duplicazioni (check tramite reference)
+	 * @param collection
+	 */
+	private void addCollectionToRehasingList(final Object collection)
+	{
+		for(final Object c : rehashCollection)
+			/*	Utilizza i reference e non {@link Object#equals(Object)} per i controlli
+			 * 	di identit? perch? gli hash degli oggetti nella collection potrebbero
+			 * 	cambiare durante la costruzione dell'oggetto!
+			 */
+			if(c == collection)
+				return;
+		rehashCollection.add(collection);
+	}	
+	/**	Elimina i proxy da un oggetto marcato come collection
+	 * @param proxyCollection
+	 * @return
+	 */
+	private final Object makeNakedCollection(final Object proxyCollection)
+	{
+		Class<?> impl = proxyCollection.getClass();
+		//	In caso di una PersistentCollection bisogna utilizzare una impl di default
+		if(proxyCollection instanceof PersistentCollection)
+		{
+			if(Map.class.isAssignableFrom(impl))
+				impl = HashMap.class;
+			if(List.class.isAssignableFrom(impl))
+				impl = ArrayList.class;
+			if(Set.class.isAssignableFrom(impl))
+				impl = HashSet.class;
+		}
+		//	Map (non deriva da Collection)
+		if(Map.class.isAssignableFrom(impl))
+			return makeNakedMap((Map<?,?>) proxyCollection);
+		if(Set.class.isAssignableFrom(impl))
+			return makeNakedSet(impl,(Set<?>) proxyCollection);
+		//	Collection generica
+		if(Collection.class.isAssignableFrom(impl))
+			return makeNakedCollection(impl,(Collection<?>) proxyCollection);
+		throw new ZSystemException(new ClassCastException(proxyCollection.getClass().getName() + " must be a assignable from " + PersistentCollection.class.getName()));
+	}
+	/**	Elimina i proxy da un oggetto marcato come component. I component non hanno cache perch? sono 'annegati'
+	 * 	all'interno dell'oggetto ospitante
+	 * @param componentEntity il componente da lavorare
+	 * @param parentComponentName il nome della propriet? del componente nell'oggetto parent
+	 * @param parentProxyObject l'entit? che contiene il component
+	 * @param parentProxyObjectClassMetadata le info di mapping del parent
+	 * @return
+	 * @throws ZSystemException
+	 */
+	private final Object makeNakedComponent(final Object componentEntity,final String parentComponentName,final Object parentProxyObject,final EntityPersister parentProxyObjectEntityPersister) throws ZSystemException
+	{
+		//	La vera classe dell'oggetto (in caso di proxy)
+		final Class<?> componentEntityClass = Hibernate.getClass(componentEntity);
+		final Object nakedComponent = instance0(componentEntityClass);
+		//	Il valore di una property
+		Object componentPropertyValue;
+		Object nakedPropertyValue;
+		Type propertyMappingType;
+		
+		//	Il lavoro va fatto su tutti i campi dell'entity da hidratare!
+		for(final Field propertyField : retrieveFields(componentEntityClass))
+		{
+			if(!fieldIsModifiable(propertyField))	continue;
+			final String propertyName = propertyField.getName();
+			//	Rendilo accessibile e leggi il valore
+			boolean propertyFieldAccessible = propertyField.isAccessible();
+			try
+			{
+				propertyField.setAccessible(true);
+				//	Leggi il valore della property!
+				if(null != (nakedPropertyValue = componentPropertyValue = getFieldValue(propertyField, componentEntity)))
+				{
+					//	Potrebbe essere necessaria l'inizializzazione!
+					if(objectSholdBeInitialized(componentPropertyValue))
+						Hibernate.initialize(componentPropertyValue);
+					
+					//	Nel caso sia un oggetto di mappato con Hibernate estraine le informazioni:per i component le informazioni utilizzano
+					//	la dot notation per accedere ai nomi dei campi!
+					final String dottedComponentPropertyName = new StringBuffer(parentComponentName).append('.').append(propertyName).toString();
+					if(null != (propertyMappingType = getHibernatePropertyType(parentProxyObjectEntityPersister, dottedComponentPropertyName)))
+					{
+						//	Solo gli oggetti rimappati vanno gestiti!
+						//	Per esempio le collection che non sono mapped non conterranno,di
+						//	sicuro,degli oggetti rimappati!
+						if(objectShouldBeNaked(nakedPropertyValue, propertyMappingType))
+						{	
+							if(isCollection(componentPropertyValue))
+							{
+								nakedPropertyValue = makeNakedCollection(componentPropertyValue);
+								addNakedObjectToCache(fullConstructedCache, componentPropertyValue, nakedPropertyValue);
+							}
+							else
+							{
+								if(propertyMappingType.isComponentType())
+									nakedPropertyValue = makeNakedComponent(componentPropertyValue, dottedComponentPropertyName, parentProxyObject, parentProxyObjectEntityPersister);
+								else
+									nakedPropertyValue = makeNakedObject(componentPropertyValue);
+							}
+						}
+					}
+					else
+					{
+						//	Un oggetto di cui non sono riuscito ad estrarre le info,ma che
+						//	? un proxy di hibernate: gli devo dare una chance!
+						if(getHibernateProxy(componentPropertyValue) != null)
+							nakedPropertyValue = makeNakedObject(componentPropertyValue);
+					}
+				}
+				//	Rimpiazza il valore della property nell'oggetto copia
+				setFieldValue(propertyField, nakedComponent, nakedPropertyValue);
+			}
+			catch(ZSystemException e)
+			{
+				final boolean isIllegalAccess = e.getCause() instanceof IllegalAccessException;
+				if(isIllegalAccess)
+				{
+					//	I campi che non sono modificabili possono generare l'errore,? normale!
+					if(!fieldIsModifiable(propertyField))
+						throw e;
+				}
+			}
+			finally
+			{
+				propertyField.setAccessible(propertyFieldAccessible);
+			}
+		}
+		return nakedComponent;
+	}	
+	/**	Esegue una deep-copy di un oggetto 
+	 * @param <T>
+	 * @param proxyObject L'oggetto sorgente
+	 * @return il parametro replaceEntity
+	 * @throws ZSystemException
+	 */
+	private final Object makeNakedObject(final Object proxyObject) throws ZSystemException
+	{
+		//	Gli oggetti null tornano null!
+		if(null == proxyObject)
+			return null;
+		
+		//	Per prima cosa verifica nella cache se esiste l'oggetto! (prima in quelli parziali,che sono meno...
+		Object nakedObject = getNakedObjectFromCache(partiallyConstructedCache,proxyObject);
+		if(null == nakedObject)
+			//	...e poi eventualmente in quelli completi!
+			nakedObject = getNakedObjectFromCache(fullConstructedCache,proxyObject);
+		if(null != nakedObject)
+			return nakedObject;
+		
+		//	Gestione dei proxy!
+		final HibernateProxy proxy = getHibernateProxy(proxyObject);
+		final LazyInitializer li = proxy != null ? proxy.getHibernateLazyInitializer() : null;
+		//	La vera classe dell'oggetto (in caso di proxy)
+		final Class<?> nakedObjectClass = li != null ? li.getPersistentClass() : proxyObject.getClass();
+		//	Il valore di una property
+		Object proxyPropertyValue = null;
+		Object nakedPropertyValue = null;
+		final EntityPersister proxyObjectMetadata = getClassMetadata(nakedObjectClass);
+		Type propertyMappingType = null;
+		
+		//	L'oggetto da utilizzare come rimpiazzo!
+		nakedObject = instance0(nakedObjectClass);
+		//	Subito mettilo nella cache dei parziali cosi chiunque potr? accedervi mentre lo inizializzo!
+		addNakedObjectToCache(partiallyConstructedCache, proxyObject, nakedObject);
+		
+		//	Il lavoro va fatto su tutti i campi dell'entity da hidratare!
+		for(final Field propertyField : retrieveFields(nakedObjectClass))
+		{			
+			if(!fieldIsModifiable(propertyField))	continue;
+			final String propertyName = propertyField.getName();
+			//	Rendilo accessibile e leggi il valore
+			boolean propertyFieldAccessible = propertyField.isAccessible();
+			try
+			{
+				propertyField.setAccessible(true);
+				//	Leggi il valore della property!
+				if(null != (nakedPropertyValue = proxyPropertyValue = getFieldValue(propertyField, li != null ? li.getImplementation() : proxyObject)))
+				{
+					//	Potrebbe essere necessaria l'inizializzazione!
+					if(objectSholdBeInitialized(proxyPropertyValue))
+						Hibernate.initialize(proxyPropertyValue);
+					
+					//	Nel caso sia un oggetto di mappato con Hibernate estraine le informazioni...
+					if(null != (propertyMappingType = getHibernatePropertyType(proxyObjectMetadata, propertyName)))
+					{
+						//	Solo gli oggetti rimappati vanno gestiti!
+						//	Per esempio le collection che non sono mapped non conterranno,di
+						//	sicuro,degli oggetti rimappati!
+						if(objectShouldBeNaked(nakedPropertyValue, propertyMappingType))
+						{	
+							if(isCollection(proxyPropertyValue))
+							{
+								nakedPropertyValue = makeNakedCollection(proxyPropertyValue);
+								addNakedObjectToCache(fullConstructedCache, proxyPropertyValue, nakedPropertyValue);
+							}
+							else
+							{
+								if(propertyMappingType.isComponentType())
+									nakedPropertyValue = makeNakedComponent(proxyPropertyValue, propertyName, nakedObject, proxyObjectMetadata);
+								else
+									nakedPropertyValue = makeNakedObject(proxyPropertyValue);
+							}
+						}
+					}
+					else
+					{
+						//	Un oggetto di cui non sono riuscito ad estrarre le info,ma che
+						//	? un proxy di hibernate: gli devo dare una chance!
+						if(getHibernateProxy(proxyPropertyValue) != null)
+							nakedPropertyValue = makeNakedObject(proxyPropertyValue);
+					}
+				}
+				//	Rimpiazza il valore della property nell'oggetto copia
+				setFieldValue(propertyField, nakedObject, nakedPropertyValue);
+			}
+			catch(ZSystemException e)
+			{
+				final boolean isIllegalAccess = e.getCause() instanceof IllegalAccessException;
+				if(isIllegalAccess)
+				{
+					//	I campi che non sono modificabili possono generare l'errore,? normale!
+					if(!fieldIsModifiable(propertyField))
+						throw e;
+				}
+			}
+			finally
+			{
+				propertyField.setAccessible(propertyFieldAccessible);
+			}
+		}
+		//	Sposta l'oggetto dalla cache dei parzialmente a quelli dei completamente costruiti!
+		addNakedObjectToCache(fullConstructedCache, proxyObject, removeNakedObjectFromCache(partiallyConstructedCache, proxyObject));
+		return nakedObject;
+	}
+	/**	Re-indicizzazione di un {@link Set}
+	 * @param c
+	 */
+	private void rehashSet(final Set<Object> c)
+	{
+		final Object[] all = c.toArray();
+		c.clear();
+		for(final Object o : all)
+			c.add(o);
+	}
+	/**	Re-indicizzazione di una {@link Map}
+	 * @param c
+	 */
+	@SuppressWarnings("unchecked")
+	private void rehashMap(final Map<Object,Object> c)
+	{
+		/*	E' necessario fare una copia delle chiavi,
+		 * 	svuotare la collection e reinserire gli oggetti
+		 * 	in modo che siano re-indicizzati completamente!
+		 */
+		final Entry[] entries = c.entrySet().toArray(new Entry[c.size()]);
+		c.clear();
+		for(final Entry entry : entries)
+			c.put(entry.getKey(),entry.getValue());
+	}
+	/**	Postprocessing sulle collection di cui effettuarne il rehash perch?
+	 * 	costruite,in origine,su oggetti parzialmente costruiti!
+	 */
+	private void rehashCollection()
+	{
+		for(final Object c : rehashCollection)
+		{
+			if(Set.class.isAssignableFrom(c.getClass()))
+				rehashSet((Set<Object>) c);
+			if(Map.class.isAssignableFrom(c.getClass()))
+				rehashMap((Map<Object,Object>) c);
+		}
+	}
+	
+	/** Esegue l'unproxy di un oggetto utilizzando degli oggetti nuovi. Esegue una deep-copy rimuovendo
+	 * 	tutti i proxy presenti.
+	 * 	Gli oggetti proxy che non sono presenti nella lista delle proprties da aggiornare vengono
+	 * 	azzerati
+	 * @param <T>
+	 * @param entity
+	 * @return
+	 * @throws ZSystemException
+	 */
+	public final static <T> T deepCopyObject(final T entity,final SessionFactory sessionFactory) throws ZSystemException
+	{
+		if(null == entity)	return null;
+		UnproxyObject impl = new UnproxyObject(sessionFactory);
+		try
+		{
+			return (T) impl.makeNakedObject(entity);
+		}
+		finally
+		{
+			impl.rehashCollection();
+			impl = null;
+		}
+	}
+	
+	@Deprecated
+	public final static <T> T deepCopyObject(final T entity) throws ZSystemException
+	{
+		return deepCopyObject(entity, (SessionFactory)null);
+	}
+	public final static <T> T deepCopyObject(final T entity,final HibernateDatabase hibernateDatabase) throws ZSystemException
+	{
+		SessionFactory sessionFactory = null;
+		if(null != hibernateDatabase)
+			sessionFactory = hibernateDatabase.getHibernateSession().getSessionFactory();
+		return deepCopyObject(entity, sessionFactory);
+	}
+	public final static <T> T deepCopyObject(final T entity,final Session session) throws ZSystemException
+	{
+		SessionFactory sessionFactory = null;
+		if(null != session)
+			sessionFactory = session.getSessionFactory();
+		return deepCopyObject(entity, sessionFactory);
+	}
+	/**	Clona un oggetto tramite serializzazione!
+	 * @param <T>
+	 * @param entity
+	 * @return
+	 * @throws ZSystemException
+	 */
+	public final static <T extends Serializable> T cloneObject(final T entity) throws ZSystemException
+	{
+		ByteArrayOutputStream baos = null;
+		ObjectOutput oo = null;
+		ObjectInput oi = null;
+		try
+		{
+			baos = new ByteArrayOutputStream(4096);
+			oo = new ObjectOutputStream(baos);
+			oo.writeObject(entity);
+			oo.close();
+			
+			oi = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
+			return (T)oi.readObject();
+		}
+		catch(Exception e)
+		{
+			throw new ZSystemException(e);
+		}
+		finally
+		{
+			try
+			{
+				if(null != baos)
+					baos.close();
+				if(null != oo)
+					oo.close();
+				if(null != oi)
+					oi.close();
+				baos = null;
+				oo = null;
+				oi = null;
+			}
+			catch(IOException e)
+			{
+				throw new ZSystemException(e);
+			}
+		}
+	}
+}

+ 290 - 0
src/main/java/commons/utility/WebUtility.java

@@ -0,0 +1,290 @@
+package commons.utility;
+
+import java.io.File;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.List;
+import java.util.StringTokenizer;
+
+import jakarta.servlet.ServletContext;
+import jakarta.servlet.http.Cookie;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+
+import org.hibernate.Hibernate;
+
+import commons.exception.ZSystemException;
+import commons.utility.database.NullValue;
+import commons.exception.ZCryptoException;
+import commons.utility.field.BinaryBooleanWebField;
+
+
+public class WebUtility
+{
+	public static String riceviRealPath(ServletContext context, String percorsoFileSystemCondiviso)
+	{
+		if (percorsoFileSystemCondiviso != null && !percorsoFileSystemCondiviso.equalsIgnoreCase(NullValue.STRING))
+		    return percorsoFileSystemCondiviso;
+
+	    String returnValue = context.getRealPath("/");
+	    if (null == returnValue)
+	    		return NullValue.STRING;
+		if (!String.valueOf(returnValue.charAt(returnValue.length() - 1)).equalsIgnoreCase(File.separator))
+			returnValue += File.separator;
+		return returnValue;
+	}
+
+	public static String riceviRealPathHBM(ServletContext context)
+	{
+	    String returnValue = context.getRealPath("/");
+		if (!String.valueOf(returnValue.charAt(returnValue.length() - 1)).equalsIgnoreCase(File.separator))
+			returnValue += File.separator;
+		return returnValue;
+	}
+
+	public static void clearAuthCookie(HttpServletRequest req, HttpServletResponse res, String cookieName)
+	{
+		//cancellazione eventuale cookie di autenticazione
+		Cookie[] cookies = req.getCookies();
+		if (cookies != null)
+		{
+			for (int i = 0; i < cookies.length; i++)
+			{
+				Cookie thisCookie = cookies[i];
+				if (thisCookie.getName().equals(cookieName))
+				{
+					thisCookie.setValue("");
+					thisCookie.setMaxAge(0);
+					res.addCookie(thisCookie);
+				}
+			}
+		}
+	}
+
+
+	public static void writeAuthCookie(HttpServletResponse res, String cf, String cookieName) throws ZCryptoException
+	{
+		Cookie ck = new Cookie(cookieName, Crypto.encrypt(cf));
+		res.addCookie(ck);
+	}
+
+
+	/**
+	 * Cancella un cookie
+	 * @param res
+	 * @param cf
+	 * @param cookieName - nome del cookie
+	 * @param percoso
+	 * @throws ZCryptoException
+	 */
+	public static void writeAuthCookie(HttpServletResponse res, String cf, String cookieName, String path) throws ZCryptoException
+	{
+		Cookie ck = new Cookie(cookieName, Crypto.encrypt(cf));
+		ck.setPath(path);
+		res.addCookie(ck);
+	}
+
+	
+	/**
+	 * Cancella un cookie
+	 * @param res
+	 * @param cf
+	 * @param cookieName - nome del cookie
+	 * @throws ZCryptoException
+	 */
+	public static void deleteCookie(HttpServletRequest req, HttpServletResponse res, String cookieName)
+	{
+		//cancellazione eventuale cookie di autenticazione
+		Cookie[] cookies = req.getCookies();
+		if (cookies != null)
+		{
+			for (int i = 0; i < cookies.length; i++)
+			{
+				Cookie thisCookie = cookies[i];
+				if (thisCookie.getName().equals(cookieName))
+				{
+					thisCookie.setValue("");
+					thisCookie.setMaxAge(0);
+					res.addCookie(thisCookie);
+				}
+			}
+		}
+	}
+
+	/**
+	 * Legge un cookie con propriet? VALUE CRIPTATA. Il cookie viene ritornato con la propriet? VALUE DECRIPTATO
+	 * @param req
+	 * @param cookieName
+	 * @return
+	 */
+	public static Cookie readCookie(HttpServletRequest req, String cookieName)
+	{
+		try
+        {
+            Cookie[] cookies = req.getCookies();
+    		if (cookies != null)
+    		{
+    			for (int i = 0; i < cookies.length; i++)
+    			{
+    				Cookie thisCookie = cookies[i];
+    				if (thisCookie.getName().equals(cookieName))
+    				{
+    					//thisCookie.setValue(Crypto.decrypt(thisCookie.getValue()));
+    					return new CryptedCookie(thisCookie);
+    				}
+    			}
+    		}
+    		return null;
+        }
+        catch (Exception ex)
+        {
+            return null;
+        }
+	}
+
+	/**
+	 * Scrive un cookie CRIPTANDONE la propriet? value
+	 * @param res
+	 * @param cookieName
+	 * @param testo
+	 * @throws ZCryptoException
+	 */
+	public static void writeCookie(HttpServletResponse res, String cookieName, String testo) throws ZCryptoException
+	{
+		try
+        {
+			CryptedCookie cryptoC = new CryptedCookie(cookieName, testo);
+    		cryptoC.setMaxAge(31536000);
+    		Cookie writeCk = new Cookie(cookieName, cryptoC.getCk().getValue());
+    		writeCk.setMaxAge(cryptoC.getMaxAge());
+    		res.addCookie(writeCk);
+        }
+		catch (Exception ex)
+		{
+		    return;
+		}
+	}
+
+	//	Campo di comodo per le conversioni
+	private static BinaryBooleanWebField booleanConv = new BinaryBooleanWebField(null,false);
+	/**	Converte un valore string nel relativo valore boolean
+	 * @param value Il valore del boolean in formato stringa 0/1
+	 * @return Il valore boolean (false come default)
+	 */
+	public final static boolean convertBinaryBoolean(final String value)
+	{
+		booleanConv.setFormattedText(value);
+		return booleanConv.getBoolean();
+	}
+	
+	
+	/**	Inizializza le properties di una rootEntity mappata con Hibernate
+	 * @param <T>
+	 * @param rootEntity L'entit? connessa alla sessione
+	 * @param properties La lista di property nella forma prop1.prop11.prop111,prop2.prop22... etc
+	 * @return L'oggetto con le property specificate inizializzate!
+	 */
+	public final static <T> T initEntityProperties(final T rootEntity,final String...properties)
+	{
+		if(null != rootEntity)
+		{
+			for(final String property : properties)
+			{
+				Object currentProperty = rootEntity;
+				{
+					final StringTokenizer strtok = new StringTokenizer(property,".");
+					while(strtok.hasMoreTokens())
+					{
+						//	Verifica se la property ? stata inizializzata!
+						final String token = strtok.nextToken();
+						//	L'oggetto corrente va letto!
+						final String getMethodName = "get" + token.substring(0,1).toUpperCase() + token.substring(1);
+						try
+						{
+							final Method getMethod = currentProperty.getClass().getMethod(getMethodName);
+							boolean getMethodAccessible = getMethod.isAccessible();
+							try
+							{
+								getMethod.setAccessible(true);
+								currentProperty = getMethod.invoke(currentProperty);
+							}
+							catch (Throwable e)
+							{
+								throw new ZSystemException(e);
+							}
+							finally
+							{
+								getMethod.setAccessible(getMethodAccessible);
+							}
+						}
+						catch (SecurityException e)
+						{
+							throw new ZSystemException(e);
+						}
+						catch (NoSuchMethodException e)
+						{
+							//	Accesso tramite field!
+							try
+							{
+								Field propertyField = currentProperty.getClass().getDeclaredField(token);
+								boolean propertyFieldAccessible = propertyField.isAccessible();
+								try
+								{
+									propertyField.setAccessible(true);
+									currentProperty = propertyField.get(currentProperty);
+								}
+								catch (Throwable e2)
+								{
+									throw new ZSystemException(e2);
+								}
+								finally
+								{
+									propertyField.setAccessible(propertyFieldAccessible);
+								}
+							}
+							catch (SecurityException e1)
+							{
+								throw new ZSystemException(e);
+							}
+							catch (NoSuchFieldException e1)
+							{
+								break;
+							}
+						}
+						
+						//	Se non ? stata inizializzata...
+						if(!Hibernate.isInitialized(currentProperty))
+						{
+							//	allora ? da fare!
+							Hibernate.getClass(currentProperty);
+						}					
+					}
+				}
+			}
+		}		
+		return rootEntity;
+	}
+	
+	/**	Inizializza le properties di una lista di entity mappate con Hibernate
+	 * @param <T>
+	 * @param rootEntities la lista di oggetto
+	 * @param properties la lista di properties da inizializzare
+	 * @return
+	 */
+	public final static <T> List<T> initEntitiesProperties(final List<T> rootEntities,final String...properties)
+	{
+		if(null != rootEntities)
+		{
+			for(final T rootEntity : rootEntities)
+				initEntityProperties(rootEntity, properties);
+		}
+		
+		return rootEntities;
+	}
+	
+	public static String traduciPathPerJsp(String path)
+	{
+		return path.replaceAll("\\\\", "\\\\\\\\") ;
+	}
+	
+}

+ 11 - 0
src/main/java/commons/utility/bean/DatiAbilitazioni.java

@@ -0,0 +1,11 @@
+package commons.utility.bean;
+
+import java.io.Serializable;
+
+public class DatiAbilitazioni implements Serializable 
+{
+
+	private static final long serialVersionUID = 1L;
+	
+	
+}

+ 164 - 0
src/main/java/commons/utility/dao/AliasToBeanResultTransformerEnanced.java

@@ -0,0 +1,164 @@
+package commons.utility.dao;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.hibernate.query.TupleTransformer;
+
+import commons.exception.ZSystemException;
+
+/**
+ * Result transformer che permette di trasformare un resultSet in una
+ * classe specifica definita dall'utente popolata via setter.
+ * Per popolare la classe vengono utilizzati gli alias. Viene supportata la dotNotation.
+ */
+public class AliasToBeanResultTransformerEnanced implements TupleTransformer {
+
+    private static final String THIS = "this";
+
+    private static final long serialVersionUID = 1L;
+
+    private final Class resultClass;
+
+    public AliasToBeanResultTransformerEnanced(Class resultClass) {
+        if(resultClass==null) throw new IllegalArgumentException("resultClass cannot be null");
+        this.resultClass = resultClass;
+    }
+
+    public Object transformTuple(Object[] tuple, String[] aliases) {
+        Map<String,Tuplizer> firstLevelObject = new HashMap<String,Tuplizer>();
+
+        for (int i = 0; i < aliases.length; i++)
+        {
+            if(tuple[i] == null || aliases[i] == null) continue;
+            String alias = aliases[i];
+            String key = THIS;
+            if(alias != null && alias.indexOf(".") != -1) {
+                key = alias.substring(0,alias.indexOf("."));
+                alias = alias.substring(alias.indexOf(".") + 1);
+            }
+
+            Tuplizer myList = null;
+            if(firstLevelObject.containsKey(key)) {
+                myList = firstLevelObject.get(key);
+            } else {
+                myList = new Tuplizer();
+                firstLevelObject.put(key,myList);
+            }
+            myList.addTupla(tuple[i]);
+            myList.addAlias(alias);
+        }
+
+        Tuplizer tuplizer = firstLevelObject.remove(THIS);
+        Object mainObj = buildBean(this.resultClass, tuplizer.getTuple(), tuplizer.getAliases());
+
+        Iterator<String> keys = firstLevelObject.keySet().iterator();
+        while (keys.hasNext())
+        {
+            String property = keys.next();
+            Field declaredField = null;
+            try
+            {
+                try {
+                    declaredField = resultClass.getDeclaredField(property);
+                } catch (NoSuchFieldException e) {
+                    declaredField = resultClass.getSuperclass().getDeclaredField(property);
+                }
+
+                declaredField.setAccessible(true);
+
+                AliasToBeanResultTransformerEnanced beanTransPlus;
+                if (declaredField.getGenericType() instanceof ParameterizedType)
+                {
+                    Type[] tipi = ((ParameterizedType) declaredField.getGenericType()).getActualTypeArguments();
+                    beanTransPlus = new AliasToBeanResultTransformerEnanced((Class<?>) tipi[0]);
+                    Tuplizer t = firstLevelObject.get(property);
+                    Object propertyObj = beanTransPlus.transformTuple(t.getTuple(),t.getAliases());
+                    declaredField.set(mainObj,propertyObj);
+                }
+                else
+                {
+                    beanTransPlus = new AliasToBeanResultTransformerEnanced(declaredField.getType());
+                    Tuplizer t = firstLevelObject.get(property);
+                    Object propertyObj = beanTransPlus.transformTuple(t.getTuple(),t.getAliases());
+                    declaredField.set(mainObj,propertyObj);
+                }
+            }
+            catch (SecurityException e)
+            {
+                throw new ZSystemException(e);
+            }
+            catch (NoSuchFieldException e)
+            {
+                throw new ZSystemException(e);
+            }
+            catch (IllegalArgumentException e)
+            {
+                throw new ZSystemException(e);
+            }
+            catch (IllegalAccessException e)
+            {
+                throw new ZSystemException(e);
+            }
+            finally
+            {
+                declaredField.setAccessible(false);
+            }
+        }
+
+        return mainObj;
+    }
+
+    private Object buildBean(Class clazz, Object[] tuple, String[] aliases) {
+        try {
+            Object bean = clazz.getDeclaredConstructor().newInstance();
+            for (int i = 0; i < aliases.length; i++) {
+                if (tuple[i] == null || aliases[i] == null) continue;
+                try {
+                    Field field = clazz.getDeclaredField(aliases[i]);
+                    field.setAccessible(true);
+                    field.set(bean, tuple[i]);
+                } catch (NoSuchFieldException e) {
+                    // ignore
+                }
+            }
+            return bean;
+        } catch (Exception e) {
+            throw new ZSystemException(e);
+        }
+    }
+
+    class Tuplizer {
+
+        List<Object> tuple = null;
+        List<String> aliases = null;
+
+        public Tuplizer() {
+            tuple = new ArrayList<Object>();
+            aliases = new ArrayList<String>();
+        }
+
+        public void addTupla(Object obj) {
+            tuple.add(obj);
+        }
+
+        public void addAlias(String alias) {
+            aliases.add(alias);
+        }
+
+        public Object[] getTuple() {
+            return tuple.toArray();
+        }
+
+        public String[] getAliases() {
+            return aliases.toArray(new String[aliases.size()]);
+        }
+    }
+
+}

+ 328 - 0
src/main/java/commons/utility/dao/GenericDAO.java

@@ -0,0 +1,328 @@
+package commons.utility.dao;
+
+import java.beans.PropertyDescriptor;
+import java.io.BufferedReader;
+import java.io.Reader;
+import java.io.Serializable;
+
+import org.apache.commons.beanutils.PropertyUtils;
+import org.hibernate.Hibernate;
+import org.hibernate.HibernateException;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.proxy.HibernateProxy;
+import org.hibernate.proxy.LazyInitializer;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Repository;
+
+import commons.utility.UnproxyObject;
+
+import java.lang.reflect.Array;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.ParameterizedType;
+import java.sql.Clob;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+public class GenericDAO<T, ID extends Serializable>
+        implements IDAO<T, ID> {
+
+    public final static int K_ORDER_ASC = 0;
+    public final static int K_ORDER_DESC = 1;
+    public final static String K_ELIMINATO = "X";
+    public final static String K_NUOVO = "N";
+    public final static String K_ESPORTATO = "T";
+    public final static String K_TRASMESSO = "T";
+
+
+    protected boolean transactionStartedByMe = false;
+
+    @Autowired
+    protected SessionFactory sessionFactory;
+    protected Class<T> persistentClass;
+
+    private String LastError = "";
+
+    @SuppressWarnings("unchecked")
+    public GenericDAO() {
+        this.persistentClass = (Class<T>) ((ParameterizedType) getClass()
+                .getGenericSuperclass()).getActualTypeArguments()[0];
+    }
+
+    public Session currentSession() {
+        return sessionFactory.getCurrentSession();
+    }
+
+    @SuppressWarnings("unchecked")
+    public T read(ID id) {
+        return read(id, false);
+    }
+
+    @SuppressWarnings("unchecked")
+    public T read(ID id, boolean forceLoadRelatedData) {
+        boolean tx = startTransaction();
+        T entity = (T) sessionFactory.getCurrentSession().get(persistentClass,
+                id);
+        if (forceLoadRelatedData)
+            Hibernate.initialize(entity);
+        if (tx)
+            commit();
+        return entity;
+    }
+
+    @SuppressWarnings("unchecked")
+    public T readNoTransaction(ID id) {
+        T entity = (T) sessionFactory.getCurrentSession().get(persistentClass,
+                id);
+        return entity;
+    }
+
+    public T saveOrUpdate(T entity) throws Exception {
+        boolean tx = startTransaction();
+        try {
+            currentSession().saveOrUpdate(entity);
+            if (tx)
+                commit();
+        } catch (Exception ex) {
+            setLastError(ex.getMessage());
+            if (tx)
+                rollback();
+            throw ex;
+        }
+        return entity;
+    }
+
+    public T saveOrUpdateNoTransaction(T entity) throws Exception {
+        boolean tx = startTransaction();
+        currentSession().saveOrUpdate(entity);
+        if (tx)
+            commit();
+        return entity;
+    }
+
+    public T merge(T entity) throws Exception {
+        boolean tx = startTransaction();
+        try {
+            currentSession().merge(entity);
+            if (tx)
+                commit();
+        } catch (Exception ex) {
+            setLastError(ex.getMessage());
+            if (tx)
+                rollback();
+            throw ex;
+        }
+        return entity;
+    }
+
+    public boolean startTransaction() {
+        if (!currentSession().getTransaction().isActive()) {
+            transactionStartedByMe = true;
+            currentSession().beginTransaction();
+            return true;
+        } else
+            return false;
+    }
+
+    public void commit() {
+        if (currentSession().getTransaction().isActive()) {
+            currentSession().getTransaction().commit();
+            transactionStartedByMe = false;
+        }
+    }
+
+    public void rollback() {
+        if (transactionStartedByMe)
+            currentSession().getTransaction().rollback();
+    }
+
+    public void delete(T entity) {
+        startTransaction();
+        currentSession().delete(entity);
+        commit();
+    }
+
+    public void flush() {
+        currentSession().flush();
+    }
+
+    @SuppressWarnings("unchecked")
+    public List<T> listAll() {
+        return listAll(false);
+    }
+
+    public List<T> listAll(boolean forceLoadRelatedData) {
+        startTransaction();
+        String hql = "from " + persistentClass.getSimpleName() + " t";
+        List<T> res = currentSession().createQuery(hql, persistentClass).list();
+        if (forceLoadRelatedData)
+            for (T elemento : res)
+                Hibernate.initialize(elemento);
+        commit();
+        return res;
+    }
+
+    public List<T> listAll(String orderBy, int ascDesc) {
+        startTransaction();
+        String dir = ascDesc == K_ORDER_ASC ? "asc" : "desc";
+        String hql = "from " + persistentClass.getSimpleName() + " t order by t." + orderBy + " " + dir;
+        List<T> res = currentSession().createQuery(hql, persistentClass).list();
+        commit();
+        return res;
+    }
+
+    public String getLastError() {
+        return LastError;
+    }
+
+    public void setLastError(String lastError) {
+        LastError = lastError;
+    }
+
+    public String ClobToString(Clob cl) {
+        try {
+            Reader stream = cl.getCharacterStream();
+            BufferedReader reader = new BufferedReader(stream);
+            StringBuffer sb = new StringBuffer();
+            String line = null;
+            while ((line = reader.readLine()) != null) {
+                sb.append(line);
+            }
+            stream.close();
+            if (sb.length() > 0) {
+                return sb.toString();
+            }
+            return "";
+        } catch (Exception ex) {
+            return "Error retrieving data: " + ex.getMessage();
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    public static <T> T initializeAndUnproxy(T entity) {
+        if (entity == null) {
+            return null;
+        }
+        if (entity instanceof HibernateProxy) {
+            Hibernate.initialize(entity);
+            entity = (T) ((HibernateProxy) entity).getHibernateLazyInitializer().getImplementation();
+        }
+        return entity;
+    }
+
+    @SuppressWarnings("unchecked")
+    public T unproxy(T proxied) {
+        return deepDeproxy(proxied);
+    }
+
+    public List<T> unproxy(List<T> proxied) {
+        List<T> unproxied = new ArrayList<T>();
+        for (T element : proxied)
+            unproxied.add(UnproxyObject.deepCopyObject(element));
+        return unproxied;
+    }
+
+    public T deepDeproxy(final Object maybeProxy) throws ClassCastException {
+        if (maybeProxy == null)
+            return null;
+        T ret = deepDeproxy(maybeProxy, new HashSet<Object>());
+        return ret;
+    }
+
+    private T deepDeproxy(final Object maybeProxy, final HashSet<Object> visited)
+            throws ClassCastException {
+        if (maybeProxy == null)
+            return null;
+        Class clazz;
+        Hibernate.initialize(maybeProxy);
+        if (maybeProxy instanceof HibernateProxy) {
+            HibernateProxy proxy = (HibernateProxy) maybeProxy;
+            LazyInitializer li = proxy.getHibernateLazyInitializer();
+            clazz = li.getImplementation().getClass();
+        } else {
+            clazz = maybeProxy.getClass();
+        }
+        T ret = (T) deepDeproxy(maybeProxy, clazz);
+        if (visited.contains(ret))
+            return ret;
+        visited.add(ret);
+        for (PropertyDescriptor property : PropertyUtils
+                .getPropertyDescriptors(ret)) {
+            try {
+                String name = property.getName();
+                if (!"owner".equals(name) && property.getWriteMethod() != null) {
+                    Object value = PropertyUtils.getProperty(ret, name);
+                    boolean needToSetProperty = false;
+                    if (value instanceof HibernateProxy) {
+                        value = deepDeproxy(value, visited);
+                        needToSetProperty = true;
+                    }
+                    if (value instanceof Object[]) {
+                        Object[] valueArray = (Object[]) value;
+                        Object[] result = (Object[]) Array.newInstance(
+                                value.getClass(), valueArray.length);
+                        for (int i = 0; i < valueArray.length; i++) {
+                            result[i] = deepDeproxy(valueArray[i], visited);
+                        }
+                        value = result;
+                        needToSetProperty = true;
+                    }
+                    if (value instanceof Set) {
+                        Set valueSet = (Set) value;
+                        Set result = new HashSet();
+                        for (Object o : valueSet) {
+                            result.add(deepDeproxy(o, visited));
+                        }
+                        value = result;
+                        needToSetProperty = true;
+                    }
+                    if (value instanceof Map) {
+                        Map valueMap = (Map) value;
+                        Map result = new HashMap();
+                        for (Object o : valueMap.keySet()) {
+                            result.put(deepDeproxy(o, visited),
+                                    deepDeproxy(valueMap.get(o), visited));
+                        }
+                        value = result;
+                        needToSetProperty = true;
+                    }
+                    if (value instanceof List) {
+                        List valueList = (List) value;
+                        List result = new ArrayList(valueList.size());
+                        for (Object o : valueList) {
+                            result.add(deepDeproxy(o, visited));
+                        }
+                        value = result;
+                        needToSetProperty = true;
+                    }
+                    if (needToSetProperty)
+                        PropertyUtils.setProperty(ret, name, value);
+                }
+            } catch (java.lang.IllegalAccessException e) {
+                e.printStackTrace();
+            } catch (InvocationTargetException e) {
+                e.printStackTrace();
+            } catch (NoSuchMethodException e) {
+                e.printStackTrace();
+            }
+        }
+        return ret;
+    }
+
+    private <T> T deepDeproxy(Object maybeProxy, Class<T> baseClass)
+            throws ClassCastException {
+        if (maybeProxy == null)
+            return null;
+        if (maybeProxy instanceof HibernateProxy) {
+            return baseClass.cast(((HibernateProxy) maybeProxy)
+                    .getHibernateLazyInitializer().getImplementation());
+        } else {
+            return baseClass.cast(maybeProxy);
+        }
+    }
+
+}

+ 209 - 0
src/main/java/commons/utility/dao/GenericHibernateDaoSupport.java

@@ -0,0 +1,209 @@
+package commons.utility.dao;
+
+import java.io.Serializable;
+import java.lang.reflect.ParameterizedType;
+import java.util.List;
+
+import org.hibernate.HibernateException;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.dao.DataAccessException;
+
+import commons.exception.ZSystemException;
+
+public abstract class GenericHibernateDaoSupport<T, ID extends Serializable> implements IGenericHibernateDaoSupport<T, ID>
+{
+
+	@Autowired
+	private SessionFactory sessionFactory;
+
+	private Class<T> persistentClass;
+
+	@SuppressWarnings("unchecked")
+	public GenericHibernateDaoSupport()
+	{
+		this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
+	}
+
+	public Session currentSession() {
+		return sessionFactory.getCurrentSession();
+	}
+
+	@SuppressWarnings("unchecked")
+	public T get(ID id) throws ZDAOException
+	{
+		try
+		{
+			return (T) currentSession().get(getPersistentClass(), id);
+		}
+		catch (HibernateException e)
+		{
+			throw new ZDAOException(e);
+		}
+	}
+
+	public T save(T entity) throws ZDAOException
+	{
+		try
+		{
+			currentSession().saveOrUpdate(entity);
+			return entity;
+		}
+		catch (HibernateException e)
+		{
+			throw new ZDAOException(e);
+		}
+	}
+
+	public void delete(T entity) throws ZDAOException
+	{
+		try
+		{
+			currentSession().delete(entity);
+		}
+		catch (HibernateException e)
+		{
+			throw new ZDAOException(e);
+		}
+	}
+
+	public void delete(ID id) throws ZDAOException
+	{
+		try
+		{
+			T entity = get(id);
+			if (entity != null) {
+				currentSession().delete(entity);
+			}
+		}
+		catch (HibernateException e)
+		{
+			throw new ZDAOException(e);
+		}
+	}
+
+	public List<T> getElenco() throws ZDAOException
+	{
+		try
+		{
+			String hql = "from " + getPersistentClass().getSimpleName();
+			return currentSession().createQuery(hql, getPersistentClass()).list();
+		}
+		catch (HibernateException e)
+		{
+			throw new ZDAOException(e);
+		}
+	}
+
+	protected Class<T> getPersistentClass()
+	{
+		return this.persistentClass;
+	}
+
+	static public interface InternalHibernateCallback
+	{
+		public Object doInHibernate(Session session) throws DataAccessException;
+	}
+
+	protected Object execute(final InternalHibernateCallback internalHibernateCallback) throws ZDAOException
+	{
+		try
+		{
+			return internalHibernateCallback.doInHibernate(currentSession());
+		}catch(DataAccessException e)
+		{
+			throw new ZDAOException(e);
+		}
+	}
+	protected Object execute(final InternalHibernateCallback internalHibernateCallback, boolean exposeNativeSession) throws ZDAOException
+	{
+		try
+		{
+			return internalHibernateCallback.doInHibernate(currentSession());
+		}catch(DataAccessException e)
+		{
+			throw new ZDAOException(e);
+		}
+	}
+
+    @SuppressWarnings("unchecked")
+	protected List executeFind(final InternalHibernateCallback internalHibernateCallback) throws ZDAOException
+    {
+    	try
+		{
+			return (List) internalHibernateCallback.doInHibernate(currentSession());
+		}catch(DataAccessException e)
+		{
+			throw new ZDAOException(e);
+		}
+	}
+
+	static public class ZDAOHibernateException extends RuntimeException
+	{
+		private static final long serialVersionUID = 1L;
+
+		public ZDAOHibernateException()
+		{
+			super("");
+		}
+
+		public ZDAOHibernateException(String message)
+		{
+			super(message);
+		}
+
+		public ZDAOHibernateException(Exception e)
+		{
+			super(e);
+		}
+
+		public ZDAOHibernateException(Throwable e)
+		{
+			super(e);
+		}
+
+	}
+
+	static public class ZDAOHibernateMaxRowLimitException extends ZDAOHibernateException
+	{
+		private static final long serialVersionUID = 1L;
+
+		private Object struct = null;
+
+		public ZDAOHibernateMaxRowLimitException(Object struct)
+		{
+			this.struct = struct;
+		}
+
+		public Object getObject()
+		{
+			return this.struct;
+		}
+	}
+
+	static public class ZDAOHibernateNonUniqueResultException extends ZDAOHibernateException
+	{
+		private static final long serialVersionUID = 1L;
+
+		public ZDAOHibernateNonUniqueResultException()
+		{
+			super("");
+		}
+
+		public ZDAOHibernateNonUniqueResultException(String message)
+		{
+			super(message);
+		}
+
+		public ZDAOHibernateNonUniqueResultException(Exception e)
+		{
+			super(e);
+		}
+
+		public ZDAOHibernateNonUniqueResultException(Throwable e)
+		{
+			super(e);
+		}
+	}
+}

+ 16 - 0
src/main/java/commons/utility/dao/IDAO.java

@@ -0,0 +1,16 @@
+package commons.utility.dao;
+
+import java.io.Serializable;
+import java.util.List;
+
+public interface IDAO<T, ID extends Serializable> {
+	T read(ID id);
+	T saveOrUpdate(T entity) throws Exception;
+	T merge(T entity) throws Exception;
+	T saveOrUpdateNoTransaction(T entity)  throws Exception;;
+	boolean startTransaction();
+	void commit();
+	void rollback();
+	void delete(T entity);
+	List<T> listAll();
+}

+ 48 - 0
src/main/java/commons/utility/dao/IGenericHibernateDaoSupport.java

@@ -0,0 +1,48 @@
+package commons.utility.dao;
+
+import java.io.Serializable;
+import java.util.List;
+
+/**
+ * Interface generica per i DAO. L'implementazione si basa su HibernateDaoSupport
+ * Dichiara i metodi comuni a tutti i DAO
+ *
+ * @param <T>	classe persistente
+ * @param <ID>	classe della chiave primaria
+ */
+public interface IGenericHibernateDaoSupport<T,ID extends Serializable>
+{
+	/**
+	 * Get generico
+	 * @param id
+	 * @return la struttura o null se non esiste
+	 */
+	public abstract T get(ID id) throws ZDAOException;
+
+	/**
+	 * Lista senza filtro della struttura
+	 * @return
+	 */
+	public abstract List<T> getElenco() throws ZDAOException;
+
+	/**
+	 * Metodo generico per salvare/aggiornare la struttura
+	 * @param entity
+	 * @return
+	 */
+	public abstract T save(T entity) throws ZDAOException;
+
+	/**
+	 * Metodo generico per cancellare una struttura
+	 * @param entity
+	 * @param hd
+	 */
+	public abstract void delete(T entity) throws ZDAOException;
+
+	/**
+	 * Metodo generico per cancellare una struttura dato l'id
+	 * @param id
+	 * @param hd
+	 */
+	public abstract void delete(ID id) throws ZDAOException;
+}

+ 30 - 0
src/main/java/commons/utility/dao/ZDAOException.java

@@ -0,0 +1,30 @@
+package commons.utility.dao;
+
+public class ZDAOException extends Exception {
+	
+	private static final long serialVersionUID = 1L;
+
+	public ZDAOException()
+	{
+		super();
+	}
+	
+	public ZDAOException(String message)
+	{
+		super(message);
+	}
+	
+	public ZDAOException(Exception e)
+	{
+		super(e);
+	}
+	
+	public ZDAOException(Throwable e)
+	{
+		super(e);
+	}
+	public ZDAOException(String message, Throwable e)
+	{
+		super(message, e);
+	}
+}

Niektoré súbory nie sú zobrazené, pretože je v týchto rozdielových dátach zmenené mnoho súborov