Utilities.java

  1. /*
  2.  * GovWay - A customizable API Gateway
  3.  * https://govway.org
  4.  *
  5.  * Copyright (c) 2005-2025 Link.it srl (https://link.it).
  6.  *
  7.  * This program is free software: you can redistribute it and/or modify
  8.  * it under the terms of the GNU General Public License version 3, as published by
  9.  * the Free Software Foundation.
  10.  *
  11.  * This program is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.  * GNU General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU General Public License
  17.  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  18.  *
  19.  */



  20. package org.openspcoop2.utils;


  21. import java.io.ByteArrayInputStream;
  22. import java.io.ByteArrayOutputStream;
  23. import java.io.File;
  24. import java.io.IOException;
  25. import java.io.InputStream;
  26. import java.io.InputStreamReader;
  27. import java.io.OutputStream;
  28. import java.io.SequenceInputStream;
  29. import java.io.StringWriter;
  30. import java.lang.reflect.Field;
  31. import java.net.URL;
  32. import java.nio.file.Files;
  33. import java.nio.file.Path;
  34. import java.nio.file.attribute.FileAttribute;
  35. import java.nio.file.attribute.PosixFilePermission;
  36. import java.nio.file.attribute.PosixFilePermissions;
  37. import java.text.MessageFormat;
  38. import java.util.ArrayList;
  39. import java.util.HashMap;
  40. import java.util.Iterator;
  41. import java.util.List;
  42. import java.util.Map;
  43. import java.util.Properties;
  44. import java.util.Set;
  45. import java.util.concurrent.Callable;
  46. import java.util.concurrent.ConcurrentHashMap;
  47. import java.util.concurrent.ConcurrentMap;
  48. import java.util.concurrent.ExecutionException;
  49. import java.util.concurrent.ExecutorService;
  50. import java.util.concurrent.Executors;
  51. import java.util.concurrent.Future;
  52. import java.util.concurrent.TimeUnit;
  53. import java.util.concurrent.TimeoutException;

  54. import org.apache.commons.lang.StringUtils;
  55. import org.apache.commons.lang.SystemUtils;
  56. import org.apache.commons.lang.WordUtils;
  57. import org.slf4j.Logger;


  58. /**
  59.  * Libreria contenente metodi utili generale.
  60.  *
  61.  *
  62.  * @author Poli Andrea (apoli@link.it)
  63.  * @author $Author$
  64.  * @version $Rev$, $Date$
  65.  */

  66. public class Utilities {

  67.     private Utilities() {}
  68.    
  69.    
  70.     // ** Thread Sleep **
  71.     public static void sleep(long ms) {
  72.         try {
  73.             Thread.sleep(ms);
  74.         }catch(InterruptedException t) {
  75.             // ignore
  76.             Thread.currentThread().interrupt();
  77.         }
  78.     }
  79.    
  80.     @SuppressWarnings("unchecked")
  81.     public static <T> T execute(int secondsTimeout, Callable<?> callable) throws TimeoutException, UtilsException {
  82.         ExecutorService executor = Executors.newSingleThreadExecutor();
  83.         try {
  84.             Future<?> future = executor.submit(callable);
  85.             return (T) future.get(secondsTimeout, TimeUnit.SECONDS); //timeout is in 2 seconds
  86.         } catch (TimeoutException e) {
  87.             throw e;
  88.         } catch (InterruptedException e) {
  89.             Thread.currentThread().interrupt();
  90.             throw new UtilsException(e.getMessage(),e);
  91.         } catch (ExecutionException e) {
  92.             throw new UtilsException(e.getMessage(),e);
  93.         }finally {
  94.             executor.shutdownNow();
  95.         }
  96.     }
  97.    
  98.    
  99.    
  100.    
  101.     // Class.newInstance() is deprecated in Java 1++
  102.     @SuppressWarnings("unchecked")
  103.     public static <T> T newInstance(String className) throws UtilsException {
  104.         if(className!=null && !StringUtils.isEmpty(className)) {
  105.             try {
  106.                 return  (T) newInstance(Class.forName(className));
  107.             }catch(Exception e) {
  108.                 throw new UtilsException(e.getMessage(), e);
  109.             }
  110.         }
  111.         return null;
  112.     }
  113.     public static <T> T newInstance(Class<T> classType) throws UtilsException {
  114.         if(classType!=null) {
  115.             try {
  116.                 return  classType.getConstructor().newInstance();
  117.             }catch(Exception e) {
  118.                 throw new UtilsException(e.getMessage(), e);
  119.             }
  120.         }
  121.         return null;
  122.     }
  123.    
  124.     public static <T> T newInstanceThrowInstantiationException(String className) throws InstantiationException {
  125.         try {
  126.             return newInstance(className);
  127.         }catch(Exception e) {
  128.             throw new InstantiationException(e.getMessage());
  129.         }
  130.     }
  131.     public static <T> T newInstanceThrowInstantiationException(Class<T> classType) throws InstantiationException {
  132.         try {
  133.             return newInstance(classType);
  134.         }catch(Exception e) {
  135.             throw new InstantiationException(e.getMessage());
  136.         }
  137.     }
  138.    
  139.    
  140.     public static boolean equalsClass(Object o1, Object o2) {
  141.         if(o1==null || o2==null) {
  142.             return false;
  143.         }
  144.         //return o1.getClass().getName().equals(o2.getClass().getName()); sonar java:S1872
  145.         return o1.getClass().equals(o2.getClass());
  146.     }
  147.    


  148.     /** ArrayBuffer utilizzato per la lettura */
  149.     public static final int DIMENSIONE_BUFFER = 65536;
  150.    
  151.    
  152.     /** String with charset Processing */
  153.     public static String getAsString(URL url,String charsetName) throws UtilsException{
  154.         return getAsString(url, charsetName, true);
  155.     }
  156.     public static String getAsString(URL url,String charsetName,boolean throwExceptionInputStreamEmpty) throws UtilsException{
  157.         try{
  158.             String content = null;
  159.             try (InputStream openStream = url.openStream();){
  160.                 content = Utilities.getAsString(openStream,charsetName,throwExceptionInputStreamEmpty);
  161.             }
  162.             return content;
  163.         }
  164.         catch (UtilsException e) {
  165.             throw e;
  166.         }
  167.         catch (java.lang.Exception e) {
  168.             throw new UtilsException("Utilities.getAsString error "+e.getMessage(),e);
  169.         }
  170.     }
  171.     public static String getAsString(InputStream is,String charsetName) throws UtilsException{
  172.         return getAsString(is,charsetName,true);
  173.     }
  174.     public static String getAsString(InputStream is,String charsetName,boolean throwExceptionInputStreamEmpty) throws UtilsException{
  175.         try{
  176.             StringBuilder sb = Utilities.getAsInputStreamReader(is,charsetName,throwExceptionInputStreamEmpty);
  177.             if(sb==null){
  178.                 /** se si entra qua throwExceptionInputStreamEmpty e' per forza false
  179.                 if(throwExceptionInputStreamEmpty){
  180.                     throw new UtilsException("getAsInputStreamReader is null");
  181.                 }
  182.                 else{*/
  183.                 return null;
  184.             }
  185.             return sb.toString();          
  186.         }
  187.         catch (UtilsException e) {
  188.             throw e;
  189.         }
  190.         catch (java.lang.Exception e) {
  191.             throw new UtilsException("Utilities.getAsString error "+e.getMessage(),e);
  192.         }
  193.     }
  194.     public static StringBuilder getAsInputStreamReader(InputStream isParam,String charsetName) throws UtilsException{
  195.         return getAsInputStreamReader(isParam, charsetName, true);
  196.     }
  197.     public static StringBuilder getAsInputStreamReader(InputStream isParam,String charsetName,boolean throwExceptionInputStreamEmpty) throws UtilsException{
  198.        
  199.         InputStream is = null;
  200.         try{
  201.             if(isParam==null){
  202.                 if(throwExceptionInputStreamEmpty){
  203.                     throw new UtilsException("InputStream is null");
  204.                 }
  205.                 else{
  206.                     return null;
  207.                 }
  208.             }
  209.            
  210.             is = normalizeStream(isParam, throwExceptionInputStreamEmpty);
  211.             if(is==null) {
  212.                 // nel caso serva l'eccezione, viene lanciata nel normalizeStream.
  213.                 // NOTA: al metodo normalizeStream viene passato per forza un oggetto non null, altrimenti si entra nel controllo precedente
  214.                 return null;
  215.             }
  216.         } catch (Exception e) {
  217.             throw parseException(e, "getAsInputStreamReader");
  218.         }
  219.        
  220.         try (InputStreamReader isr = new InputStreamReader(is, charsetName);){
  221.            
  222.             StringWriter writer = new StringWriter();
  223.             CopyCharStream.copy(isr, writer);
  224.             return new StringBuilder(writer.toString());
  225.            
  226.         } catch (Exception e) {
  227.             throw parseException(e, "getAsInputStreamReader");
  228.         }
  229.     }
  230.     private static UtilsException parseException(Exception e, String method) {
  231.         if(e instanceof java.io.IOException){
  232.             if(!isEmpytMessageException(e)){
  233.                 return new UtilsException(e.getMessage(),e);
  234.             }
  235.         }
  236.         else if(existsInnerException(e, java.io.IOException.class)){
  237.             Throwable tInternal = getInnerException(e, java.io.IOException.class);
  238.             if(!isEmpytMessageException(tInternal)){
  239.                 return new UtilsException(tInternal.getMessage(),e);
  240.             }
  241.         }

  242.         Throwable tInternal = getInnerNotEmptyMessageException(e);
  243.         if(tInternal!=null){
  244.             return new UtilsException(tInternal.getMessage(),e);
  245.         }
  246.         else{
  247.             return new UtilsException("Utilities."+method+" error",e);
  248.         }
  249.     }
  250.    
  251.    
  252.     /** RawBinary Processing */
  253.     public static byte[] getAsByteArray(URL url) throws UtilsException{
  254.         return getAsByteArray(url, true);
  255.     }
  256.     public static byte[] getAsByteArray(URL url,boolean throwExceptionInputStreamEmpty) throws UtilsException{
  257.         try{
  258.             byte[] content = null;
  259.             try (InputStream openStream = url.openStream();){
  260.                 content = Utilities.getAsByteArray(openStream,throwExceptionInputStreamEmpty);
  261.             }
  262.             return content;
  263.         }
  264.         catch (UtilsException e) {
  265.             throw e;
  266.         }
  267.         catch (java.lang.Exception e) {
  268.             throw new UtilsException("Utilities.readBytes error "+e.getMessage(),e);
  269.         }
  270.     }
  271.     public static byte[] getAsByteArray(InputStream is) throws UtilsException{
  272.         return getAsByteArray(is,true);
  273.     }
  274.     public static byte[] getAsByteArray(InputStream is,boolean throwExceptionInputStreamEmpty) throws UtilsException{
  275.         try{
  276.             byte[] returnNull = null;
  277.             ByteArrayOutputStream bout = Utilities.getAsByteArrayOuputStream(is,throwExceptionInputStreamEmpty);
  278.             if(bout!=null) {
  279.                 return bout.toByteArray();
  280.             }
  281.             else {
  282.                 return returnNull; // puo' succedere solo se throwExceptionInputStreamEmpty e' false
  283.             }
  284.         }
  285.         catch (UtilsException e) {
  286.             throw e;
  287.         }
  288.         catch (java.lang.Exception e) {
  289.             throw new UtilsException("Utilities.readBytes error "+e.getMessage(),e);
  290.         }
  291.     }
  292.     public static ByteArrayOutputStream getAsByteArrayOuputStream(InputStream isParam) throws UtilsException{
  293.         return getAsByteArrayOuputStream(isParam, true);
  294.     }
  295.     public static void writeAsByteArrayOuputStream(ByteArrayOutputStream bout, InputStream isParam) throws UtilsException{
  296.         writeAsByteArrayOuputStream(bout, isParam, true);
  297.     }
  298.     public static ByteArrayOutputStream getAsByteArrayOuputStream(InputStream isParam,boolean throwExceptionInputStreamEmpty) throws UtilsException{
  299.         ByteArrayOutputStream bout = new ByteArrayOutputStream();
  300.         writeAsByteArrayOuputStream(bout, isParam, throwExceptionInputStreamEmpty);
  301.         if(bout.size()>0) {
  302.             return bout;
  303.         }else {
  304.             return null;
  305.         }
  306.     }
  307.     public static void writeAsByteArrayOuputStream(OutputStream bout, InputStream isParam,boolean throwExceptionInputStreamEmpty) throws UtilsException{
  308.         try{
  309.             if(isParam==null){
  310.                 if(throwExceptionInputStreamEmpty){
  311.                     throw new UtilsException("InputStream is null");
  312.                 }
  313.                 else{
  314.                     return;
  315.                 }
  316.             }
  317.            
  318.             InputStream is = normalizeStream(isParam, throwExceptionInputStreamEmpty);
  319.             if(is==null) {
  320.                 // nel caso serva l'eccezione, viene lanciata nel normalizeStream.
  321.                 // NOTA: al metodo normalizeStream viene passato per forza un oggetto non null, altrimenti si entra nel controllo precedente
  322.                 return;
  323.             }          
  324.            
  325.             CopyStream.copy(CopyStreamMethod.AUTO, is, bout);
  326.            
  327.         } catch (java.lang.Exception e) {
  328.             throw parseException(e, "writeAsByteArrayOuputStream");
  329.         }
  330.     }


  331.     public static InputStream normalizeStream(InputStream is, boolean throwExceptionInputStreamEmpty) throws UtilsException {
  332.         try {
  333.             if(is!=null){
  334.                 byte[] buffer = new byte[2]; // UTF-16
  335.                 int letti = is.read(buffer);
  336.                 if( letti <=0 ) {
  337.                     if(throwExceptionInputStreamEmpty){
  338.                         throw new UtilsException("InputStream is empty (class:"+is.getClass().getName()+")");
  339.                     }
  340.                     else{
  341.                         return null;
  342.                     }
  343.                 } else {
  344.                     // Metodo alternativo: java.io.PushbackInputStream
  345.                     byte [] b = null;
  346.                     if(letti==2) {
  347.                         b = buffer;
  348.                     }
  349.                     else {
  350.                         b = new byte[1]; // e' per forza 1
  351.                         b[0] = buffer[0];
  352.                     }
  353.                     return new SequenceInputStream(new ByteArrayInputStream(b),is);
  354.                 }
  355.             }
  356.             return is; // null
  357.         }catch(Exception e){
  358.             throw new UtilsException(e.getMessage(),e);
  359.         }
  360.     }
  361.    
  362.    
  363.    
  364.     /** Copy Stream */
  365.    
  366.     public static void copy(InputStream is,OutputStream os) throws UtilsException{
  367.         try{
  368.             CopyStream.copy(CopyStreamMethod.AUTO, is, os);
  369.         }catch(Exception e){
  370.             throw new UtilsException(e.getMessage(),e);
  371.         }
  372.     }
  373.    
  374.    


  375.     /** Properties */
  376.    
  377.     public static java.util.Properties getAsProperties(InputStream is) throws UtilsException{
  378.         try{
  379.             if(is==null){
  380.                 throw new UtilsException("Utilities.getAsProperties error: InputStream is null");
  381.             }
  382.             Properties p = new Properties();
  383.             p.load(is);
  384.             return p;
  385.         }catch(Exception e){
  386.             throw new UtilsException(e.getMessage(),e);
  387.         }
  388.     }
  389.    
  390.     public static java.util.Properties getAsProperties(byte[] content) throws UtilsException{
  391.         if(content==null){
  392.             throw new UtilsException("Utilities.getAsProperties error: Content is null");
  393.         }
  394.         try (ByteArrayInputStream bin = new ByteArrayInputStream(content);){
  395.             return getAsProperties(bin);
  396.         }catch(Exception e){
  397.             throw new UtilsException(e.getMessage(),e);
  398.         }
  399.     }
  400.    
  401.     public static java.util.Properties getAsProperties(URL url) throws UtilsException{
  402.         InputStream is = null;
  403.         try{
  404.             if(url==null){
  405.                 throw new UtilsException("Utilities.getAsProperties error: URL is null");
  406.             }
  407.             is = url.openStream();
  408.             return getAsProperties(is);
  409.         }catch(Exception e){
  410.             throw new UtilsException(e.getMessage(),e);
  411.         }
  412.         finally{
  413.             try{
  414.                 if(is!=null){
  415.                     is.close();
  416.                 }
  417.             }catch(Exception eClose){
  418.                 // close
  419.             }
  420.         }
  421.     }

  422.     /**
  423.      * Legge le proprieta' che possiedono un nome che inizia con un determinato prefisso
  424.      *
  425.      * @param prefix
  426.      * @param sorgente java.util.Properties
  427.      * @return java.util.Properties
  428.      * @throws UtilsException
  429.      */
  430.     public static java.util.Properties readProperties (String prefix,java.util.Properties sorgente)throws UtilsException{
  431.         java.util.Properties prop = new java.util.Properties();
  432.         try{
  433.             java.util.Enumeration<?> en = sorgente.propertyNames();
  434.             while (en.hasMoreElements()) {
  435.                 String property = (String) en.nextElement();
  436.                 if(property.startsWith(prefix)){
  437.                     String key = (property.substring(prefix.length()));
  438.                     if(key != null)
  439.                         key = key.trim();
  440.                     String value = sorgente.getProperty(property);
  441.                     if(value!=null)
  442.                         value = value.trim();
  443.                     if(key!=null && value!=null)
  444.                         prop.setProperty(key,value);
  445.                 }
  446.             }
  447.             return prop;
  448.         }catch(java.lang.Exception e) {
  449.             throw new UtilsException("Utilities.readProperties Riscontrato errore durante la lettura delle proprieta' con prefisso ["+prefix+"]: "+e.getMessage(),e);
  450.         }  
  451.     }
  452.     /**
  453.      * Legge le proprieta' che possiedono un nome che inizia con un determinato prefisso
  454.      *
  455.      * @param prefix
  456.      * @param key Array di chiavi
  457.      * @param name Array di nomi
  458.      * @return java.util.Properties
  459.      * @throws UtilsException
  460.      */
  461.     public static java.util.Properties readProperties (String prefix,String[]key,String[] name)throws UtilsException{
  462.         java.util.Properties sorgente = new java.util.Properties();
  463.         if(key!=null && name!=null && key.length==name.length){
  464.             for(int i=0; i<key.length; i++){
  465.                 sorgente.put(key[i], name[i]);
  466.             }
  467.         }  
  468.         return Utilities.readProperties(prefix,sorgente);
  469.     }




  470.     /**
  471.      * Converte unix_timestamp in stringa
  472.      *
  473.      * @param time unix_timestamp
  474.      * @param millisecondiCheck Se true verranno indicati anche i millisecondi
  475.      * @return String unix_timestamp
  476.      */
  477.     public static String convertSystemTimeIntoStringMillisecondi(long time,boolean millisecondiCheck){
  478.         return convertSystemTimeIntoStringMillisecondi(time, millisecondiCheck, true, ":",".","");
  479.     }
  480.     public static String convertSystemTimeIntoStringMillisecondi(long time,boolean millisecondiCheck, boolean printZeroValues,
  481.             String separatorUnit,String separatorMs, String separatorValue){
  482.         /**System.out.println("VALORE PASSATO: ["+time+"]");*/
  483.         long millisecondi = time % 1000;
  484.         /**System.out.println("Millisecondi (Valore%1000): ["+millisecondi+"]");*/
  485.         long diff = (time)/1000;
  486.         /**System.out.println("Diff... (valore/1000) ["+diff+"]");*/
  487.         long ore = diff/3600;
  488.         /**System.out.println("Ore... (diff/3600) ["+ore+"]");*/
  489.         long minuti = (diff%3600) / 60;
  490.         /**System.out.println("Minuti... (diff%3600) / 60 ["+minuti+"]");*/
  491.         long secondi = (diff%3600) % 60;
  492.         /**System.out.println("Secondi... (diff%3600) % 60 ["+secondi+"]");*/
  493.         StringBuilder bf = new StringBuilder();

  494.         long giorni = ore/24;
  495.         long oreRimaste = ore%24;

  496.         if(giorni>0){
  497.             bf.append(giorni);
  498.             bf.append(separatorValue);
  499.             bf.append("d");
  500.         }
  501.         else{
  502.             // Nothing
  503.         }

  504.         if(giorni>0){
  505.             if(oreRimaste>0){
  506.                 if(bf.length()>0){
  507.                     bf.append(separatorUnit);
  508.                 }
  509.                 bf.append(oreRimaste);
  510.                 bf.append(separatorValue);
  511.                 bf.append("h");
  512.             }else{
  513.                 if(printZeroValues && bf.length()>0){
  514.                     bf.append(separatorUnit);
  515.                     bf.append("0");
  516.                     bf.append(separatorValue);
  517.                     bf.append("h");
  518.                 }
  519.             }
  520.         }
  521.         else{
  522.             if(ore>0){
  523.                 if(bf.length()>0){
  524.                     bf.append(separatorUnit);
  525.                 }
  526.                 bf.append(ore);
  527.                 bf.append(separatorValue);
  528.                 bf.append("h");
  529.             }else{
  530.                 if(printZeroValues && bf.length()>0){
  531.                     bf.append(separatorUnit);
  532.                     bf.append("0");
  533.                     bf.append(separatorValue);
  534.                     bf.append("h");
  535.                 }
  536.             }
  537.         }


  538.         if(minuti>0){
  539.             if(bf.length()>0){
  540.                 bf.append(separatorUnit);
  541.             }
  542.             bf.append(minuti);
  543.             bf.append(separatorValue);
  544.             bf.append("m");
  545.         }else{
  546.             if(printZeroValues && bf.length()>0){
  547.                 bf.append(separatorUnit);
  548.                 bf.append("0");
  549.                 bf.append(separatorValue);
  550.                 bf.append("m");
  551.             }
  552.         }

  553.         if(secondi>0){
  554.             if(bf.length()>0){
  555.                 bf.append(separatorUnit);
  556.             }
  557.             bf.append(secondi);
  558.             bf.append(separatorValue);
  559.             bf.append("s");
  560.         }
  561.         else{
  562.             if(printZeroValues && bf.length()>0){
  563.                 bf.append(separatorUnit);
  564.                 bf.append("0");
  565.                 bf.append(separatorValue);
  566.                 bf.append("s");
  567.             }
  568.         }

  569.         if(millisecondiCheck){
  570.             if(millisecondi>0 || (millisecondi==0 && printZeroValues)){
  571.                 if(bf.length()>0){
  572.                     bf.append(separatorMs);
  573.                 }
  574.                 bf.append(millisecondi);
  575.                 bf.append(separatorValue);
  576.                 bf.append("ms");
  577.             }
  578.             else{
  579.                 if(printZeroValues && bf.length()>0){
  580.                     bf.append(separatorMs);
  581.                     bf.append("0");
  582.                     bf.append(separatorValue);
  583.                     bf.append("ms");
  584.                 }
  585.             }
  586.         }


  587.         if(bf.length()==0){
  588.             bf.append("conversione non riuscita");
  589.         }

  590.         return bf.toString();
  591.     }
  592.    
  593.     public static long convertSystemTimeInNumeroOre(long time){
  594.         if(time < 0)
  595.             time = 0;
  596.                
  597.         // tempo in millisecondi diviso mille -> tempo in secondi
  598.         long diff = (time)/1000;
  599.         // tempo in ore = tempo in secondi / 60 * 60
  600.         long ore = diff/3600;
  601.        
  602.         // controllo che non ci siano parti di ora residue
  603.         if((diff%3600) != 0)
  604.             ore ++;
  605.            
  606.         return ore;
  607.     }
  608.    
  609.     public static long convertSystemTimeInNumeroGiorni(long time){
  610.         if(time < 0)
  611.             time = 0;
  612.                
  613.         // tempo in millisecondi diviso mille -> tempo in secondi
  614.         long diff = (time)/1000;
  615.         // tempo in ore = tempo in secondi / 60 * 60
  616.         long ore = diff/3600;
  617.        
  618.         // controllo che non ci siano parti di ora residue
  619.         if((diff%3600) != 0)
  620.             ore ++;
  621.        
  622.         long giorni = ore/24;
  623.         long oreRimaste = ore%24;
  624.        
  625.         if(oreRimaste != 0)
  626.             giorni ++;
  627.        
  628.         return giorni;
  629.     }
  630.    


  631.     private static final double KB = 1024;
  632.     private static final double MB = 1048576;
  633.     private static final double GB = 1073741824;
  634.     public static String convertBytesToFormatString(long value) {
  635.         return convertBytesToFormatString(value, false, "");
  636.     }
  637.     public static String convertBytesToFormatString(long value, boolean upperCase, String separator) {

  638.         MessageFormat mf = new MessageFormat("{0,number,#.##}");
  639.         Double len = null;
  640.         String res = "";
  641.         //il valore e' in byte
  642.         len = Long.valueOf((value+"")).doubleValue();
  643.         long d = Math.round(len/Utilities.KB);
  644.         if(d<=1){
  645.             //byte
  646.             Object[] objs = {len};
  647.             res = mf.format(objs);
  648.             res +=separator;
  649.             res += "b";
  650.         }else if(d>1 && d<1000){
  651.             //kilo byte
  652.             Object[] objs = {len/Utilities.KB};
  653.             res = mf.format(objs);
  654.             res +=separator;
  655.             res += "kb";
  656.         }else  if (d >= 1000 && d < 1000000){
  657.             //mega byte
  658.             Object[] objs = {len/Utilities.MB};
  659.             res = mf.format(objs);
  660.             res +=separator;
  661.             res += "mb";
  662.         }
  663.         else{
  664.             // giga byte
  665.             Object[] objs = { len/Utilities.GB };
  666.             res = mf.format(objs);
  667.             res +=separator;
  668.             res +="gb";
  669.         }

  670.         if(upperCase){
  671.             res = res.toUpperCase();
  672.         }
  673.        
  674.         return res;
  675.     }




  676.     /* STRING UTILS NORMALIZE NAME */
  677.    
  678.     public static String convertNameToSistemaOperativoCompatible(String nome,boolean convertCharNotPermitted,Character charJollyCharNotPermitted,
  679.             List<Character> permit, boolean addUniqueSuffixIfFoundCharNotPermitted){
  680.         StringBuilder bf = new StringBuilder();
  681.         boolean charNotPermittedFound = false;
  682.         for (int i = 0; i < nome.length(); i++) {
  683.             if(Character.isLetterOrDigit(nome.charAt(i))){
  684.                 bf.append(nome.charAt(i));
  685.             }
  686.             else {
  687.                 if(permit!=null){
  688.                     // check che sia nella lista dei caratteri permessi
  689.                     boolean found = false;
  690.                     for (char charPermit : permit) {
  691.                         if(charPermit == nome.charAt(i)){
  692.                             found = true;
  693.                             break;
  694.                         }
  695.                     }
  696.                     if(found){
  697.                         bf.append(nome.charAt(i));
  698.                         continue;
  699.                     }
  700.                 }
  701.                
  702.                 // Se non e' nella lista dei caratteri permessi, se e' abilitata la conversione, converto il carattere non permesso nel carattere jolly
  703.                 // altrimenti lo "brucio"
  704.                 if(convertCharNotPermitted){
  705.                     // sostituisco tutto con il carattere jolly
  706.                     bf.append(charJollyCharNotPermitted);
  707.                 }
  708.                 charNotPermittedFound = true;
  709.             }
  710.         }
  711.         if(charNotPermittedFound && addUniqueSuffixIfFoundCharNotPermitted){
  712.             bf.append("_");
  713.             bf.append(getNextCounterFile());
  714.         }
  715.         return bf.toString();
  716.     }
  717.     private static int counterFileNameWithCharNotPermitted = 0;
  718.     private static synchronized int getNextCounterFile(){
  719.         if(counterFileNameWithCharNotPermitted==Integer.MAX_VALUE){
  720.             counterFileNameWithCharNotPermitted = 0;
  721.         }
  722.         counterFileNameWithCharNotPermitted++;
  723.         return counterFileNameWithCharNotPermitted;
  724.     }
  725.    
  726.    
  727.     public static String camelCase(String value) {
  728.         char [] delimiters = new char[] {'.' , '_' , '-' , ':' , ';' , ',' , ' ' };
  729.         return camelCase(delimiters, value);
  730.     }
  731.     public static String camelCase(char [] delimiters, String value) {
  732.                
  733.         String s = WordUtils.capitalizeFully(value, delimiters);
  734.         for (int i = 0; i < delimiters.length; i++) {
  735.             String c = delimiters[i]+"";
  736.             while(s.contains(c)) {
  737.                 s = s.replace(c, "");
  738.             }
  739.         }
  740.        
  741.         return s;
  742.     }
  743.    
  744.    
  745.    
  746.    
  747.    
  748.     /* STRING UTILS CON ESCAPE */
  749.    
  750.     public static String[] split(String value, char separator) throws UtilsException{
  751.        
  752.         StringBuilder bf = new StringBuilder();
  753.         List<String> splitResults = new ArrayList<>();
  754.         if(value==null || value.length()<=0){
  755.             throw new UtilsException("Valore non fornito");
  756.         }
  757.         for (int i = 0; i < value.length(); i++) {
  758.             if(value.charAt(i) == separator){
  759.                
  760.                 if(
  761.                         (i>0 && (value.charAt(i-1) != '\\'))
  762.                                 ||
  763.                         (i==0)
  764.                 ){
  765.                     splitResults.add(bf.toString());
  766.                     bf.delete(0, bf.length());
  767.                 }
  768.                 else{
  769.                     bf.append(value.charAt(i));
  770.                 }
  771.             }
  772.             else{
  773.                 bf.append(value.charAt(i));
  774.             }
  775.         }
  776.        
  777.         splitResults.add(bf.toString());
  778.         return splitResults.toArray(new String[1]);
  779.     }

  780.    

  781.    
  782.    




  783.     // Metodi per il logging dell'heap space

  784.     private static boolean freeMemoryLog = false;
  785.     public static boolean isFreeMemoryLog() {
  786.         return freeMemoryLog;
  787.     }
  788.     public static void setFreeMemoryLog(boolean freeMemoryLog) {
  789.         Utilities.freeMemoryLog = freeMemoryLog;
  790.     }
  791.     private static Logger log;
  792.     public static void setLog(Logger log) {
  793.         Utilities.log = log;
  794.     }
  795.     public static final Runtime s_runtime = Runtime.getRuntime ();
  796.     public static final long INITIAL_SIZE = Utilities.s_runtime.freeMemory();
  797.     public static void printFreeMemory(String descr){
  798.         if(Utilities.freeMemoryLog){
  799.             long currentSize = Utilities.s_runtime.freeMemory();
  800.             String msg = "[Free Memory Space]" + "[CURRENT: " + Utilities.convertBytesToFormatString(currentSize) + "] [DIFF: " + Utilities.convertBytesToFormatString(Utilities.INITIAL_SIZE - Utilities.s_runtime.freeMemory()) + "] " + descr;
  801.             Utilities.log.debug(msg);
  802.         }
  803.     }






  804.     // Gestione eccezioni
  805.    
  806.     public static String readFirstErrorValidMessageFromException(Throwable e) {
  807.         if(e instanceof NullPointerException) {
  808.              return "NullPointerException";
  809.         }else {
  810.             Throwable inner = Utilities.getInnerNotEmptyMessageException(e);
  811.             if(inner!=null) {
  812.                 return inner.getMessage();
  813.             }
  814.             else {
  815.                 if(Utilities.isEmpytMessageException(e)) {
  816.                     return e.toString();
  817.                 }
  818.                 else {
  819.                     return e.getMessage();
  820.                 }
  821.             }
  822.         }
  823.     }
  824.    
  825.     public static boolean isEmpytMessageException(Throwable e){
  826.         return e==null || e.getMessage()==null ||
  827.                 "".equals(e.getMessage()) ||
  828.                 "null".equalsIgnoreCase(e.getMessage());
  829.     }
  830.    
  831.     public static boolean existsInnerInstanceException(Throwable e,Class<?> found){
  832.         if(found.isInstance(e) ){
  833.             return true;
  834.         }else{
  835.             if(e.getCause()!=null){
  836.                 return Utilities.existsInnerInstanceException(e.getCause(), found);
  837.             }
  838.             else{
  839.                 return false;
  840.             }
  841.         }
  842.     }
  843.     public static boolean existsInnerInstanceException(Throwable e,String found) throws ClassNotFoundException{
  844.         return Utilities.existsInnerInstanceException(e,Class.forName(found));
  845.     }
  846.    
  847.     public static Throwable getInnerInstanceException(Throwable e,Class<?> found, boolean last){
  848.         if(found.isInstance(e) ){
  849.            
  850.             if(last) {
  851.                 if(e.getCause()!=null && existsInnerInstanceException(e.getCause(), found)) {
  852.                     return Utilities.getInnerInstanceException(e.getCause(), found, last);
  853.                 }
  854.                 else {
  855.                     return e;
  856.                 }
  857.             }
  858.             else {
  859.                 return e;
  860.             }
  861.         }else{
  862.             if(e.getCause()!=null){
  863.                 return Utilities.getInnerInstanceException(e.getCause(), found, last);
  864.             }
  865.             else{
  866.                 return null;
  867.             }
  868.         }
  869.     }
  870.     public static Throwable getInnerInstanceException(Throwable e,String found, boolean last) throws ClassNotFoundException{
  871.         return Utilities.getInnerInstanceException(e,Class.forName(found), last);
  872.     }
  873.    
  874.     public static boolean existsInnerException(Throwable e,Class<?> found){
  875.         return Utilities.existsInnerException(e,found.getName());
  876.     }
  877.     public static boolean existsInnerException(Throwable e,String found){
  878.         if(e.getClass().getName().equals(found) ){
  879.             return true;
  880.         }else{
  881.             if(e.getCause()!=null){
  882.                 return Utilities.existsInnerException(e.getCause(), found);
  883.             }
  884.             else{
  885.                 return false;
  886.             }
  887.         }
  888.     }

  889.     public static Throwable getInnerException(Throwable e,Class<?> found){
  890.         return Utilities.getInnerException(e,found.getName());
  891.     }
  892.     public static Throwable getInnerException(Throwable e,String found){
  893.         if(e.getClass().getName().equals(found) ){
  894.             return e;
  895.         }else{
  896.             if(e.getCause()!=null){
  897.                 return Utilities.getInnerException(e.getCause(), found);
  898.             }
  899.             else{
  900.                 return null;
  901.             }
  902.         }
  903.     }

  904.     public static Throwable getLastInnerException(Throwable e){
  905.         if(e.getCause()==null){
  906.             return e;
  907.         }
  908.         else{
  909.             return Utilities.getLastInnerException(e.getCause());
  910.         }
  911.     }

  912.     public static boolean existsInnerMessageException(Throwable e,String msg,boolean contains){
  913.         boolean search = false;
  914.         if(contains){
  915.             search = e.getMessage()!=null && e.getMessage().contains(msg);
  916.         }else{
  917.             search = e.getMessage()!=null && e.getMessage().equals(msg);
  918.         }
  919.         if( search ){
  920.             return true;
  921.         }else{
  922.             if(e.getCause()!=null){
  923.                 return Utilities.existsInnerMessageException(e.getCause(), msg, contains);
  924.             }
  925.             else{
  926.                 return false;
  927.             }
  928.         }
  929.     }

  930.     public static Throwable getInnerMessageException(Throwable e,String msg,boolean contains){
  931.         boolean search = false;
  932.         if(contains){
  933.             search = e.getMessage()!=null && e.getMessage().contains(msg);
  934.         }else{
  935.             search = e.getMessage()!=null && e.getMessage().equals(msg);
  936.         }
  937.         if( search ){
  938.             return e;
  939.         }else{
  940.             if(e.getCause()!=null){
  941.                 return Utilities.getInnerMessageException(e.getCause(), msg, contains);
  942.             }
  943.             else{
  944.                 return null;
  945.             }
  946.         }
  947.     }


  948.     public static Throwable getInnerNotEmptyMessageException(Throwable e){
  949.         if(e.getMessage()!=null && !"".equals(e.getMessage()) && !"null".equalsIgnoreCase(e.getMessage())){
  950.             return e;
  951.         }

  952.         if(e.getCause()!=null){
  953.             return Utilities.getInnerNotEmptyMessageException(e.getCause());
  954.         }
  955.         else{
  956.             return e; // sono nella foglia, ritorno comunque questa eccezione
  957.         }
  958.     }


  959.     public static boolean isExceptionInstanceOf(Class<?> c,Throwable t){
  960.         return isExceptionInstanceOf(c.getName(), t);
  961.     }
  962.     public static boolean isExceptionInstanceOf(String className,Throwable t){
  963.         if(t.getClass().getName().equals(className)){
  964.             return true;
  965.         }
  966. /**     else if(t.getClass().getSuperclass()!=null && t.getClass().getSuperclass().equals(className)){
  967.             return true;
  968.         }*/
  969.         else{
  970.             try{
  971.                 Class<?> c = Class.forName(className);
  972.                 return c.isInstance(t);
  973.             }catch(Exception tException){
  974.                 return false;
  975.             }
  976.         }
  977.     }







  978.     // ** Elimina un attributo xml che contiene la keyword indicata nel secondo parametro */

  979.     public static String eraserXmlAttribute(String tmp,String keyword){
  980.         int indexOfValueWrong = tmp.indexOf(keyword);
  981.         while(indexOfValueWrong>0){

  982.             StringBuilder bf = new StringBuilder();
  983.             int index = indexOfValueWrong-1;
  984.             while(tmp.charAt(index) != ' '){
  985.                 bf.append(tmp.charAt(index));
  986.                 index--;
  987.             }

  988.             StringBuilder replaceString = new StringBuilder();
  989.             for (int i = (bf.toString().length()-1); i >=0; i--) {
  990.                 replaceString.append(bf.toString().charAt(i));
  991.             }
  992.             replaceString.append(keyword);

  993.             index = indexOfValueWrong+keyword.length();
  994.             while( (tmp.charAt(index) != ' ') && (tmp.charAt(index) != '>') ){
  995.                 replaceString.append(tmp.charAt(index));
  996.                 index++;
  997.             }

  998.             tmp = StringUtils.replace(tmp, replaceString.toString(), "");

  999.             indexOfValueWrong = tmp.indexOf(keyword);
  1000.         }
  1001.         return tmp;
  1002.     }










  1003.     // ** Traduce in String un byte[] se il testo è visualizzabile **
  1004.     public static String getErrorMessagePrintableTextMaxLength(int length, int maxLength) {
  1005.         return "Visualizzazione non riuscita: la dimensione del pacchetto fornito ("+Utilities.convertBytesToFormatString(length)+") supera il limite consentito ("+Utilities.convertBytesToFormatString(maxLength)+")";
  1006.     }
  1007.     public static String convertToPrintableText(byte [] b,int maxBytes) throws UtilsException{
  1008.         try (ByteArrayOutputStream bout = new ByteArrayOutputStream();){

  1009.             if(b.length>maxBytes){
  1010.                 throw new UtilsException(getErrorMessagePrintableTextMaxLength(b.length,maxBytes));
  1011.             }

  1012.             for (int i = 0; i < b.length; i++) {
  1013.                 if(!Utilities.isPrintableChar((char)b[i])){
  1014.                     throw new UtilsException("Visualizzazione non riuscita: il documento contiene caratteri non visualizzabili");
  1015.                 }
  1016.             }

  1017.             bout.write(b);
  1018.             bout.flush();
  1019.             return bout.toString();
  1020.            
  1021.         }
  1022.         catch(UtilsException e){
  1023.             throw e;
  1024.         }
  1025.         catch(Exception e){
  1026.             throw new UtilsException("Visualizzazione non riuscita: Documento binario?",e);
  1027.         }

  1028.     }

  1029.     public static boolean isPrintableChar( char c ) {
  1030.         return Character.isDefined(c);
  1031.     }
  1032.    
  1033.    
  1034.    
  1035.    
  1036.    
  1037.    
  1038.    
  1039.    
  1040.    
  1041.    
  1042.     // ** Locale **
  1043.    
  1044.     public static String toString(java.util.Locale locale){
  1045.         return toString(locale,"\n");
  1046.     }
  1047.     public static String toString(java.util.Locale locale, String separator){
  1048.         StringBuilder bf = new StringBuilder();
  1049.         toString(locale,bf,separator);
  1050.         return bf.toString();
  1051.     }
  1052.     public static void toString(java.util.Locale locale, StringBuilder bf, String separator){
  1053.        
  1054.         bf.append(locale.getDisplayName());
  1055.         bf.append(separator);
  1056.        
  1057.         addLanguage(locale, bf, separator);
  1058.        
  1059.         addCountry(locale, bf, separator);
  1060.                
  1061.         bf.append("Script: ");
  1062.         if(locale.getScript()!=null && !"".equals(locale.getScript().trim())){
  1063.             bf.append(locale.getScript());
  1064.             bf.append(" (");
  1065.             bf.append(locale.getDisplayScript());
  1066.             bf.append(")");
  1067.         }
  1068.         else{
  1069.             bf.append("-");
  1070.         }
  1071.         bf.append(separator);
  1072.        
  1073.         bf.append("Variant: ");
  1074.         if(locale.getVariant()!=null && !"".equals(locale.getVariant().trim())){
  1075.             bf.append(locale.getVariant());
  1076.             bf.append(" (");
  1077.             bf.append(locale.getDisplayVariant());
  1078.             bf.append(")");
  1079.         }
  1080.         else{
  1081.             bf.append("-");
  1082.         }
  1083.         bf.append(separator);
  1084.        
  1085.         /**Iterator<String> it = locale.getUnicodeLocaleAttributes().iterator();
  1086.         while (it.hasNext()) {
  1087.             String attribute = (String) it.next();
  1088.             bf.append("Attribute["+attribute+"]");
  1089.             bf.append(separator);
  1090.         }
  1091.        
  1092.         Iterator<Character> itC = locale.getExtensionKeys().iterator();
  1093.         while (itC.hasNext()) {
  1094.             Character character = (Character) itC.next();
  1095.             bf.append("Extension["+character+"]=["+locale.getExtension(character)+"]");
  1096.             bf.append(separator);
  1097.         }
  1098.        
  1099.         it = locale.getUnicodeLocaleKeys().iterator();
  1100.         while (it.hasNext()) {
  1101.             String key = (String) it.next();
  1102.             bf.append("Key["+key+"]=["+locale.getUnicodeLocaleType(key)+"]");
  1103.             bf.append(separator);
  1104.         }*/
  1105.    
  1106.     }
  1107.     private static void addLanguage(java.util.Locale locale, StringBuilder bf, String separator) {
  1108.         bf.append("Language: ");
  1109.         if(locale.getLanguage()!=null && !"".equals(locale.getLanguage().trim())){
  1110.             bf.append(locale.getLanguage());
  1111.             bf.append(" (");
  1112.             bf.append(locale.getDisplayLanguage());
  1113.             bf.append(") [ISO3:");
  1114.             try{
  1115.                 if(locale.getISO3Language()!=null){
  1116.                     bf.append(locale.getISO3Language());
  1117.                 }
  1118.                 else{
  1119.                     bf.append("-");
  1120.                 }
  1121.             }catch(Exception e){
  1122.                 bf.append(e.getMessage());
  1123.             }
  1124.             bf.append("]");
  1125.         }
  1126.         else{
  1127.             bf.append("-");
  1128.         }
  1129.         bf.append(separator);
  1130.     }
  1131.     private static void addCountry(java.util.Locale locale, StringBuilder bf, String separator) {
  1132.         bf.append("Country: ");
  1133.         if(locale.getCountry()!=null && !"".equals(locale.getCountry().trim())){
  1134.             bf.append(locale.getCountry());
  1135.             bf.append(" (");
  1136.             bf.append(locale.getDisplayCountry());
  1137.             bf.append(") [ISO3:");
  1138.             try{
  1139.                 if(locale.getISO3Language()!=null){
  1140.                     bf.append(locale.getISO3Country());
  1141.                 }
  1142.                 else{
  1143.                     bf.append("-");
  1144.                 }
  1145.             }catch(Exception e){
  1146.                 bf.append(e.getMessage());
  1147.             }
  1148.             bf.append("]");
  1149.         }
  1150.         else{
  1151.             bf.append("-");
  1152.         }
  1153.         bf.append(separator);
  1154.     }
  1155.    
  1156.    
  1157.    
  1158.     // ** TimeZone **
  1159.    
  1160.     public static String toString(java.util.TimeZone timeZone){
  1161.         return toString(timeZone,false);
  1162.     }
  1163.     public static String toString(java.util.TimeZone timeZone, boolean allInfo){
  1164.         StringBuilder bf = new StringBuilder();
  1165.         toString(timeZone,bf,allInfo);
  1166.         return bf.toString();
  1167.     }
  1168.     public static void toString(java.util.TimeZone timeZone, StringBuilder bf, boolean allInfo){
  1169.         bf.append(timeZone.getID());
  1170.         bf.append(" (");
  1171.         bf.append(timeZone.getDisplayName());
  1172.         bf.append(")");
  1173.         if(allInfo){
  1174.             bf.append(" DSTSaving:");
  1175.             bf.append(timeZone.getDSTSavings());
  1176.             bf.append(" RawOffset:");
  1177.             bf.append(timeZone.getRawOffset());
  1178.         }
  1179.     }
  1180.    
  1181.    
  1182.     // ** URL **
  1183.    
  1184.     public static String buildUrl(String prefix, String contesto) {
  1185.         String url = prefix;
  1186.         if(contesto!=null && !"".equals(contesto)) {
  1187.             if(!url.endsWith("/")) {
  1188.                 if(!contesto.startsWith("/")) {
  1189.                     url = url +"/";
  1190.                 }
  1191.             }
  1192.             else {
  1193.                 if(contesto.startsWith("/") && contesto.length()>1) {
  1194.                     contesto = contesto.substring(1);
  1195.                 }
  1196.             }
  1197.             url = url + contesto;
  1198.         }
  1199.         return url;
  1200.     }
  1201.    
  1202.    
  1203.     // ** ConcurrentHashMap **
  1204.    
  1205.     public static ConcurrentMap<String, String> convertToConcurrentHashMap(Properties map) {
  1206.         ConcurrentMap<String, String> mapReturnNull = null;
  1207.         if(map==null || map.isEmpty()) {
  1208.             return mapReturnNull;
  1209.         }
  1210.         ConcurrentHashMap<String, String> newMap = new ConcurrentHashMap<>();
  1211.         Iterator<Object> it = map.keySet().iterator();
  1212.         while (it.hasNext()) {
  1213.             Object k = it.next();
  1214.             if(k instanceof String) {
  1215.                 String key = (String)k;
  1216.                 newMap.put(key, map.getProperty(key));
  1217.             }
  1218.         }
  1219.         return newMap;
  1220.     }
  1221.     public static <K,V> ConcurrentMap<K, V> convertToConcurrentHashMap(Map<K, V> map) {
  1222.         ConcurrentMap<K,V> mapReturnNull = null;
  1223.         if(map==null || map.isEmpty()) {
  1224.             return mapReturnNull;
  1225.         }
  1226.         ConcurrentHashMap<K, V> newMap = new ConcurrentHashMap<>();
  1227.         Iterator<K> it = map.keySet().iterator();
  1228.         while (it.hasNext()) {
  1229.             K k = it.next();
  1230.             newMap.put(k, map.get(k));
  1231.         }
  1232.         return newMap;
  1233.     }
  1234.    
  1235.     // ** HashMap **
  1236.    
  1237.     public static Map<String, String> convertToHashMap(Properties map) {
  1238.         Map<String, String> mapReturnNull = null;
  1239.         if(map==null || map.isEmpty()) {
  1240.             return mapReturnNull;
  1241.         }
  1242.         HashMap<String, String> newMap = new HashMap<>();
  1243.         Iterator<Object> it = map.keySet().iterator();
  1244.         while (it.hasNext()) {
  1245.             Object k = it.next();
  1246.             if(k instanceof String) {
  1247.                 String key = (String)k;
  1248.                 newMap.put(key, map.getProperty(key));
  1249.             }
  1250.         }
  1251.         return newMap;
  1252.     }
  1253.    
  1254.    
  1255.    
  1256.    
  1257.    
  1258.    
  1259.    
  1260.     // ** S.O. **
  1261.    
  1262.     public static boolean isOSUnix() {
  1263.         return SystemUtils.IS_OS_UNIX;
  1264.     }
  1265.     public static boolean isOSWindows() {
  1266.         return SystemUtils.IS_OS_WINDOWS;
  1267.     }
  1268.     public static boolean isOSMac() {
  1269.         return SystemUtils.IS_OS_MAC;
  1270.     }
  1271.    
  1272.    
  1273.    
  1274.    
  1275.     // ** File temporaneo **
  1276.    
  1277.     public static Path createTempPath(String prefix, String suffix) throws IOException{
  1278.         return createTempPath(null, prefix, suffix);
  1279.     }
  1280.     public static Path createTempPath(Path dir, String prefix, String suffix) throws IOException{
  1281.         // Make sure publicly writable directories are used safely here.
  1282.         // Using publicly writable directories is security-sensitivejava:S5443
  1283.         if(SystemUtils.IS_OS_UNIX) {
  1284.             FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------"));
  1285.             return dir!=null ? Files.createTempFile(dir, prefix, suffix, attr) : Files.createTempFile(prefix, suffix, attr);
  1286.         }
  1287.         else {
  1288.             final File f = dir!=null ? Files.createTempFile(dir, prefix, suffix).toFile() : Files.createTempFile(org.apache.commons.io.FileUtils.getTempDirectory().toPath(), prefix, suffix).toFile();
  1289.             if(!f.setReadable(true, true)) {
  1290.                 // ignore
  1291.             }
  1292.             if(!f.setWritable(true, true)) {
  1293.                 // ignore
  1294.             }
  1295.             if(!f.setExecutable(true, true)) {
  1296.                 // ignore
  1297.             }
  1298.             return f.toPath();
  1299.         }
  1300.     }
  1301.    
  1302.    
  1303.    
  1304.    
  1305.     // ** ENV **
  1306.    
  1307.     public static void setEnvProperty(String key, String value) throws UtilsException {
  1308.         try {
  1309.             Map<String, String> env = System.getenv();
  1310.             Class<?> c = env.getClass();
  1311.             Field field = c.getDeclaredField("m");
  1312.             field.setAccessible(true);
  1313.             @SuppressWarnings("unchecked")
  1314.             Map<String, String> wEnv = (Map<String, String>) field.get(env);
  1315.             wEnv.put(key, value);
  1316.         } catch (Exception e) {
  1317.             throw new UtilsException("setEnvProperty '"+key+"' failed: "+e.getMessage(), e);
  1318.         }
  1319.     }
  1320. }