View Javadoc

1   /*
2    * Utilities.java
3    *
4    * Created on 28 de Março de 2007, 16:10
5    *
6    * To change this template, choose Tools | Template Manager
7    * and open the template in the editor.
8    */
9   
10  package tempcontroller.base;
11  
12  import java.io.BufferedInputStream;
13  import java.io.BufferedOutputStream;
14  import java.io.File;
15  import java.io.FileInputStream;
16  import java.io.FileOutputStream;
17  import java.io.IOException;
18  import java.io.ObjectInputStream;
19  import java.io.ObjectOutputStream;
20  import java.io.Serializable;
21  import java.text.DecimalFormat;
22  import java.util.regex.Matcher;
23  import java.util.regex.Pattern;
24  
25  /**
26   * Classe utilitária.
27   */
28  public class Utilities {
29      /**
30       * Um segundo em milisegundos.
31       */
32      public static final long SEGUNDO = 1000;
33  
34      /**
35       * Um minuto em milisegundos.
36       */
37      public static final long MINUTO = SEGUNDO * 60;
38      
39      /**
40       * Uma hora em milisegundos.
41       */
42      public static final long HORA = MINUTO * 60;
43      
44      
45      /**
46       * A instância atual desta classe.
47       */
48      private static Utilities singleton;
49      
50      /**
51       * Grava um objeto serializável em um arquivo.
52       * @param f Arquivo que será gravado.
53       * @param obj Objeto serializável.
54       * @throws IOException Caso haja algum erro de IO.
55       */
56      public void gravaSerializable(final File f, final Serializable obj)
57      throws IOException {
58          ObjectOutputStream oos = null;
59          try {
60              oos = new ObjectOutputStream(
61                      new BufferedOutputStream(new FileOutputStream(f)));
62              oos.writeObject(obj);
63          } finally {
64              if (oos != null) {
65                  oos.close();
66              }
67          }
68      }
69      
70      /**
71       * Lê os objetos serializados dentro de um arquivo.
72       * @param f Arquivo com o objeto gravado.
73       * @return Objeto lido do arquivo.
74       * @throws IOException Caso haja algum erro de IO.
75       * @throws ClassNotFoundException Caso o arquivo não tenha
76       * nenhuma classe gravada, ou a classe gravada não esteja no Classpath.
77       */
78      public Serializable leSerializable(final File f)
79      throws IOException, ClassNotFoundException {
80          ObjectInputStream ois = null;
81          Serializable toReturn = null;
82          try {
83              ois = new ObjectInputStream(
84                      new BufferedInputStream(new FileInputStream(f)));
85              toReturn = (Serializable) ois.readObject();
86              ois.close();
87          } finally {
88              if (ois != null) {
89                  ois.close();
90              }
91          }
92          
93          return toReturn;
94      }
95      
96      /**
97       * Obtém uma instância desta classe.
98       * Por padrão, esta instância é única.
99       * @return Uma instância desta classe.
100      */
101     public static Utilities getUtilities() {
102         synchronized (Utilities.class) {
103             if (singleton == null) {
104                 singleton = new Utilities();
105             }
106         }
107         
108         return singleton;
109     }
110     
111     private static Pattern patternTemperatura = 
112             Pattern.compile("(-?\\d*\\.?,?\\d*)?( +)?([CKF])?");
113     private static DecimalFormat decimalFormat = 
114             new DecimalFormat("###,###.#");
115     public static final int KELVIN_DELTA = 273;
116     public static final int KELVIN_LIMIAR = 200;
117     
118     public double parseTemperatura(String s) {
119         double toReturn = Double.NaN;
120         
121         try {
122             Matcher m = patternTemperatura.matcher(s);
123             
124             if(m.matches()) {
125                 String parteDecimal = m.group(1);
126                 
127                 toReturn = decimalFormat.parse(s).doubleValue();
128                 String indicadorEscala = m.group(3);
129                 
130                 if("C".equals(indicadorEscala)) {
131                     toReturn = toReturn + KELVIN_DELTA;
132                 }
133             }
134         } catch(Exception e) {}
135         
136         return toReturn;
137     }
138     
139     public String formatTemperatura(final double temperatura) {
140         if(Double.isNaN(temperatura)) {
141             return "Ambiente";
142         }
143         
144         StringBuilder builder = new StringBuilder();
145         double auxTemperatura = temperatura;
146         String indicadorEscala = " K";
147         
148         if(temperatura > KELVIN_LIMIAR) {
149             auxTemperatura = temperatura - KELVIN_DELTA;
150             indicadorEscala = " C";
151         }
152         
153         builder.append(decimalFormat.format(auxTemperatura));
154         builder.append(indicadorEscala);
155         
156         return builder.toString();
157     }
158     
159     private static Pattern patternTempo = 
160             Pattern.compile("(\\d\\d):(\\d\\d):(\\d\\d)");
161     
162     public long parseTempo(String s) {
163         long toReturn = 0L;
164         
165         try {
166             Matcher m = patternTempo.matcher(s);
167             
168             if(m.matches()) {
169                 String horasStr = m.group(1);
170                 String minutosStr = m.group(2);
171                 String segundosStr = m.group(3);
172                 int horas = Integer.parseInt(horasStr);
173                 int minutos = Integer.parseInt(minutosStr);
174                 int segundos = Integer.parseInt(segundosStr);
175                 
176                 toReturn = SEGUNDO * segundos + MINUTO * minutos + HORA * horas;
177             }
178         } catch(Exception e) {}
179         
180         return toReturn;
181     }
182     
183     public String formatTempo(final long tempo) {
184         if(tempo <= SEGUNDO) {
185             return "00:00:00";
186         }
187         
188         long tempoAux = tempo;
189         long horas = tempoAux / HORA;
190         tempoAux = tempoAux % HORA;
191         long minutos = tempoAux / MINUTO;
192         tempoAux = tempoAux % MINUTO;
193         long segundos = tempoAux / SEGUNDO;
194         
195         StringBuilder builder = new StringBuilder();
196         
197         if(horas >= 10) {
198             builder.append(horas);
199         } else {
200             builder.append('0');
201             builder.append(horas);
202         }
203         
204         builder.append(':');
205         
206         if(minutos >= 10) {
207             builder.append(minutos);
208         } else {
209             builder.append('0');
210             builder.append(minutos);
211         }
212         
213         builder.append(':');
214         
215         if(segundos >= 10) {
216             builder.append(segundos);
217         } else {
218             builder.append(0);
219             builder.append(segundos);
220         }
221         
222         return builder.toString();
223     }
224     
225     public double fromCelsiusToKelvin(double celsius) {
226         return celsius + KELVIN_DELTA;
227     }
228     
229     public double fromKelvinToCelsius(double kelvin) {
230         return kelvin - KELVIN_DELTA;
231     }
232 }