View Javadoc
1   /*
2    * This file is part of Waarp Project (named also Waarp or GG).
3    *
4    *  Copyright (c) 2019, Waarp SAS, and individual contributors by the @author
5    *  tags. See the COPYRIGHT.txt in the distribution for a full listing of
6    * individual contributors.
7    *
8    *  All Waarp Project is free software: you can redistribute it and/or
9    * modify it under the terms of the GNU General Public License as published by
10   * the Free Software Foundation, either version 3 of the License, or (at your
11   * option) any later version.
12   *
13   * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY
14   * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15   * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16   *
17   *  You should have received a copy of the GNU General Public License along with
18   * Waarp . If not, see <http://www.gnu.org/licenses/>.
19   */
20  package org.waarp.common.utility;
21  
22  import com.google.common.io.Files;
23  import org.dom4j.Node;
24  import org.waarp.common.exception.FileTransferException;
25  import org.waarp.common.exception.InvalidArgumentException;
26  import org.waarp.common.logging.WaarpLogger;
27  import org.waarp.common.logging.WaarpLoggerFactory;
28  
29  import java.io.File;
30  import java.io.IOException;
31  import java.nio.charset.Charset;
32  import java.sql.Timestamp;
33  import java.text.DateFormat;
34  import java.text.ParseException;
35  import java.text.SimpleDateFormat;
36  import java.util.Arrays;
37  import java.util.Calendar;
38  import java.util.Date;
39  import java.util.GregorianCalendar;
40  import java.util.TimeZone;
41  import java.util.regex.Pattern;
42  
43  /**
44   * Various utilities for reading files, transforming dates, ...
45   */
46  public final class WaarpStringUtils {
47    /**
48     * Internal Logger
49     */
50    private static final WaarpLogger logger =
51        WaarpLoggerFactory.getLogger(WaarpStringUtils.class);
52  
53    public static final String UTF_8 = "UTF-8";
54    /**
55     * Format used for Files
56     */
57    public static final Charset UTF8 = Charset.forName(UTF_8);
58  
59    public static final String BLANK_REGEX = "\\s+";
60    public static final Pattern BLANK = Pattern.compile(BLANK_REGEX);
61    private static final TimeZone z = TimeZone.getTimeZone("GMT");
62  
63    private WaarpStringUtils() {
64    }
65  
66    /**
67     * Read a file and return its content in String format
68     *
69     * @param filename
70     *
71     * @return the content of the File in String format
72     *
73     * @throws InvalidArgumentException for File not found
74     * @throws FileTransferException for reading exception
75     */
76    public static String readFileException(final String filename)
77        throws FileTransferException {
78      final File file = new File(filename);
79      // Check for size of file
80      if (file.length() > Integer.MAX_VALUE) {
81        throw new FileTransferException(
82            "File is too big for this convenience method (" + file.length() +
83            " bytes).");
84      }
85      try {
86        return Files.asCharSource(file, UTF8).read();
87      } catch (final IOException e) {
88        logger.error("Error on File while trying to read: " + filename + ": {}",
89                     e.getMessage());
90        throw new FileTransferException("Error on File while trying to read", e);
91      }
92    }
93  
94    /**
95     * Read file and return "" if an error occurs
96     *
97     * @param filename
98     *
99     * @return the string associated with the file, or "" if an error occurs
100    */
101   public static String readFile(final String filename) {
102     try {
103       return readFileException(filename);
104     } catch (final FileTransferException e) {
105       logger.error("Error while trying to read: " + filename + ": {}",
106                    e.getMessage());
107       return "";
108     }
109   }
110 
111   /**
112    * Get a date in String and return the corresponding Timestamp
113    *
114    * @param date
115    *
116    * @return the corresponding Timestamp
117    */
118   public static Timestamp fixDate(final String date) {
119     Timestamp tdate = null;
120     if (date == null) {
121       return null;
122     }
123     String ndate = date.replaceAll("/|:|\\.|\\s|-", "");
124     if (!ndate.isEmpty()) {
125       if (ndate.length() < 15) {
126         final int len = ndate.length();
127         ndate += "000000000000000".substring(len);
128       }
129       final SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
130       try {
131         final Date ddate = format.parse(ndate);
132         tdate = new Timestamp(ddate.getTime());
133       } catch (final ParseException e) {
134         logger.debug("start {}", e.getMessage());
135       }
136     }
137     return tdate;
138   }
139 
140   /**
141    * From a date in String format and a Timestamp, return the Timestamp as
142    * :<br>
143    * if before = null as date<br>
144    * if before != null and before < date, as date<br>
145    * if before != null and before >= date, as before end of day
146    * (23:59:59:9999)
147    *
148    * @param date
149    * @param before
150    *
151    * @return the end date
152    */
153   public static Timestamp fixDate(final String date, final Timestamp before) {
154     Timestamp tdate = null;
155     if (date == null) {
156       return null;
157     }
158     String ndate = date.replaceAll("/|:|\\.|\\s|-", "");
159     if (!ndate.isEmpty()) {
160       if (ndate.length() < 15) {
161         final int len = ndate.length();
162         ndate += "000000000000000".substring(len);
163       }
164       final SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
165       try {
166         Date ddate = format.parse(ndate);
167         if (before != null) {
168           final Date bef = new Date(before.getTime());
169           if (bef.compareTo(ddate) >= 0) {
170             ddate = new Date(bef.getTime() + 1000 * 3600 * 24 - 1);
171           }
172         }
173         tdate = new Timestamp(ddate.getTime());
174       } catch (final ParseException e) {
175         logger.debug("start {}", e.getMessage());
176       }
177     }
178     return tdate;
179   }
180 
181   public static Timestamp getTodayMidnight() {
182     final GregorianCalendar calendar = new GregorianCalendar();
183     calendar.set(Calendar.HOUR_OF_DAY, 0);
184     calendar.set(Calendar.MINUTE, 0);
185     calendar.set(Calendar.SECOND, 0);
186     calendar.set(Calendar.MILLISECOND, 0);
187     return new Timestamp(calendar.getTimeInMillis());
188   }
189 
190   /**
191    * Read a boolean value (0,1,true,false) from a node
192    *
193    * @param node
194    *
195    * @return the corresponding value
196    */
197   public static boolean getBoolean(final Node node) {
198     final String val = node.getText();
199     boolean bval;
200     try {
201       final int ival = Integer.parseInt(val);
202       bval = ival == 1;
203     } catch (final NumberFormatException e) {
204       bval = Boolean.parseBoolean(val);
205     }
206     return bval;
207   }
208 
209   /**
210    * Read an integer value from a node
211    *
212    * @param node
213    *
214    * @return the corresponding value
215    *
216    * @throws InvalidArgumentException
217    */
218   public static int getInteger(final Node node)
219       throws InvalidArgumentException {
220     if (node == null) {
221       throw new InvalidArgumentException("Node empty");
222     }
223     final String val = node.getText();
224     final int ival;
225     try {
226       ival = Integer.parseInt(val);
227     } catch (final NumberFormatException e) {
228       throw new InvalidArgumentException("Incorrect value");
229     }
230     return ival;
231   }
232 
233   /**
234    * Make a replacement of first "find" string by "replace" string into the
235    * StringBuilder
236    *
237    * @param builder
238    * @param find
239    * @param replace
240    *
241    * @return True if one element is found
242    */
243   public static boolean replace(final StringBuilder builder, final String find,
244                                 final String replace) {
245     if (find == null) {
246       return false;
247     }
248     final int start = builder.indexOf(find);
249     if (start == -1) {
250       return false;
251     }
252     final int end = start + find.length();
253     if (replace != null) {
254       builder.replace(start, end, replace);
255     } else {
256       builder.replace(start, end, "");
257     }
258     return true;
259   }
260 
261   /**
262    * Make replacement of all "find" string by "replace" string into the
263    * StringBuilder
264    *
265    * @param builder
266    * @param find
267    * @param replace
268    */
269   public static void replaceAll(final StringBuilder builder, final String find,
270                                 final String replace) {
271     while (replace(builder, find, replace)) {
272       // nothing
273     }
274   }
275 
276   /**
277    * Build a String with count chars using fillChar
278    *
279    * @param fillChar
280    * @param count
281    *
282    * @return the String of length count filled with fillChar
283    */
284   public static String fillString(final char fillChar, final int count) {
285     final char[] chars = new char[count];
286     Arrays.fill(chars, fillChar);
287     return new String(chars);
288   }
289 
290   /**
291    * Clean the String that could contain '\n' or '\r' into something
292    * compatible with HTML
293    *
294    * @param json
295    *
296    * @return the cleaned String
297    */
298   public static String cleanJsonForHtml(final String json) {
299     return json.replaceAll("([^\\\\])\\\\n", "$1")
300                .replaceAll("([^\\\\])\\\\r", "$1");
301   }
302 
303   public static DateFormat getDateFormat() {
304     final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd z");
305     dateFormat.setTimeZone(z);
306     return dateFormat;
307   }
308 
309   public static DateFormat getTimeFormat() {
310     final DateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
311     timeFormat.setTimeZone(z);
312     return timeFormat;
313   }
314 
315   public static DateFormat getTimestampFormat() {
316     final DateFormat timestampFormat =
317         new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
318     timestampFormat.setTimeZone(z);
319     return timestampFormat;
320   }
321 }