API Overview API Index Package Overview Direct link to this page
JavaOnTracks 0.1.2
  net.jot.utils. JOTUtilities View Javadoc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799

/*
------------------------------------
JavaOnTracks          Thibaut Colar
tcolar-jot AT colar DOT net
Artistic Licence 2.0
http://www.javaontracks.net
------------------------------------
 */
package net.jot.utils;

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.math.BigInteger;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletResponse;

import net.jot.logger.JOTLogger;
import net.jot.web.filebrowser.JOTFileComparators;

/**
 * Collection of small utilities which aren't worth having their own class :-)
 *
 *@author     tcolar
 *@created    September 28, 2001
 */
public class JOTUtilities {

	/**
	 * Sorting types for the sort method
	 */
	public static final int SORT_BY_NAME_ASC = 1;
	public static final int SORT_BY_NAME_DESC = -1;
	public static final int SORT_BY_SIZE_ASC = 2;
	public static final int SORT_BY_SIZE_DESC = -2;
	public static final int SORT_BY_TSTAMP_ASC = 3;
	public static final int SORT_BY_TSTAMP_DESC = -3;

	/**
	 * endode a cell of data into CVS format.
	 */
	public static String encodeCSVEntry(String s)
	{
		//quotes need to be doubled
		s = s.replaceAll("\"", "\"\"");
		// wrap in quotes to take care of line feeds and commas in the data.
		return "\"" + s + "\"";
	}

	/**
	 * get a directory size (recursively)
	 *
	 *@param  folder  Description of the Parameter
	 *@return         The folderSize value
	 */
	public static int getFolderSize(File folder)
	{
		int size = 0;
		File[] content = folder.listFiles();
		if (content != null)
		{
			for (int i = 0; i != content.length; i++)
			{
				if (content[i].isDirectory())
				{
					getFolderSize(content[i]);
				} else
				{
					size += content[i].length();
				}
			}
		}
		return size;
	}

	/**
	 * copy a file ...
	 *
	 *@param  dest                       Description of Parameter
	 *@param  src                        Description of Parameter
	 *@exception  FileNotFoundException  Description of Exception
	 *@exception  IOException            Description of Exception
	 *@since
	 */
	public static void copyFile(java.io.File dest, java.io.File src)
			throws FileNotFoundException, IOException
	{
		byte buffer[] = new byte[100000]; //100k
		FileInputStream input = null;
		FileOutputStream output = null;
		try
		{
			if (dest.getAbsolutePath().equals(src.getAbsolutePath()))
			{
				return;
				// avoid overwritting itself
			}

			input = new FileInputStream(src);
			output = new FileOutputStream(dest);

			int nbRead = 0;
            while ((nbRead = input.read(buffer)) > -1)
			{
				output.write(buffer, 0, nbRead);
			}
		} finally
		{
			if (input != null)
			{
				input.close();
			}

			if (output != null)
			{
				output.flush();
				output.close();
			}
		}
	}

	/**
	 * Fornat a string to a specific length by truncating or padding with
	 * spaces as needed.
	 *
	 *@param  str     Description of Parameter
	 *@param  length  Description of Parameter
	 *@return         Description of the Returned Value
	 *@since
	 */
	public static String formatString(String str, int length)
	{
		if (str == null)
		{
			str = "";
		}
		String result = "";
		if (str.length() >= length)
		{
			result = str.substring(0, length);
		} else
		{
			result = str;
			while (result.length() < length)
			{
				result += ' ';
			}
		}
		return result;
	}

	/**
	 *Description of the Method
	 *
	 *@param  str  Description of Parameter
	 *@return      Description of the Returned Value
	 */
	public static String firstLine(String str)
	{
		int i = str.indexOf("\n");
		if (i != -1)
		{
			str = str.substring(0, i);
		}
		return str;
	}

	/**
	 * Return a folder path with the trailing slah
	 *
	 *@param  str  Description of Parameter
	 *@return      Description of the Returned Value
	 */
	public static String endWithSlash(String str)
	{
		if (str != null && !str.endsWith(File.separator))
		{
			str += File.separator;
		}
		return str;
	}

	public static String endWithForwardSlash(String str)
	{
		if (str != null && !str.endsWith("/"))
		{
			str += "/";
		}
		return str;
	}

	/**
	 * Move a filke to a new location
	 * Note that is does a copy then a delete, as actaully "moving"
	 * the file does not always work right in my  experience
	 *
	 *@param  dest                       Description of Parameter
	 *@param  src                        Description of Parameter
	 *@exception  FileNotFoundException  Description of Exception
	 *@exception  IOException            Description of Exception
	 */
	public static void moveFile(java.io.File dest, java.io.File src)
			throws FileNotFoundException, IOException
	{
		if (dest.getAbsolutePath().equals(src.getAbsolutePath()))
		{
			return;
		}
		// avoid overwritting itself

		copyFile(dest, src);
		src.delete();
	}

	/**
	 *  Delete a folder recursively
	 *
	 *@param  folder  Description of the Parameter
	 */
	public static void deleteFolder(File folder)
	{
		deleteFolderContent(folder);
		folder.delete();
	}

	/**
	 * Recursively delete all the content of a folder (but not the folder itself)
	 *
	 *@param  root  Description of Parameter
	 */
	public static void deleteFolderContent(File root)
	{
		File[] content = root.listFiles();
		if (content != null)
		{
			for (int i = 0; i != content.length; i++)
			{
				if (content[i].isDirectory())
				{
					deleteFolderContent(content[i]);
				} else
				{
					content[i].delete();
				}
			}
		}
		root.delete();
	}

	/**
	 * recursively copy the content of oldfolder into a newfolder
	 *
	 *@param  newFolder      Description of Parameter
	 *@param  oldFolder      Description of Parameter
	 *@exception  Exception  Description of the Exception
	 */
	public static void copyFolderContent(File newFolder, File oldFolder, boolean recurse)
			throws Exception
	{
		File[] content = oldFolder.listFiles();
		if (content != null)
		{
			for (int i = 0; i != content.length; i++)
			{
				String targetPath;
				File newFile;

				targetPath = newFolder.getAbsolutePath() + File.separator + content[i].getName();
				newFile = new File(targetPath);

				if (content[i].isDirectory())
				{
					System.out.println("DIR " + content[i].getAbsolutePath() + " -> " + newFile.getAbsolutePath());
					if (recurse)
					{
						newFile.mkdirs();
						copyFolderContent(newFile, content[i], recurse);
					}
				} else
				{
					System.out.println(content[i].getAbsolutePath() + " -> " + newFile.getAbsolutePath());
					copyFile(newFile, content[i]);
				}
			}
		}
	}

	/**
	 * Recursively moving all the content of oldfolder into newfolder
	 * It does a copy then delete rather than a real move
	 *
	 *@param  newFolder  Description of Parameter
	 *@param  oldFolder  Description of Parameter
	 */
	public static void moveFolderContent(File newFolder, File oldFolder)
	{
		File[] content = oldFolder.listFiles();
		if (content != null)
		{
			for (int i = 0; i != content.length; i++)
			{
				if (content[i].isDirectory())
				{
					File folder = new File(newFolder.getAbsolutePath() + File.separator + content[i].getName());
					folder.mkdirs();
					moveFolderContent(folder, content[i]);
				} else
				{
					//System.out.println("moving "+content[i].getAbsolutePath()+" to "+newFolder.getAbsolutePath()+File.separator+content[i].getName());
					content[i].renameTo(new File(newFolder.getAbsolutePath() + File.separator + content[i].getName()));
				}
			}
		}
	}

	/**
	 * Recursively zip the content of a folder into a stream / file
	 *
	 *@param  zos              Description of Parameter
	 *@param  root             Description of Parameter
	 *@param  folder           Description of Parameter
	 *@exception  IOException  Description of Exception
	 */
	public static void zipFolder(ZipOutputStream zos, String root, File folder) throws IOException
	{
		//System.out.println("zipFolder(" + folder.getAbsolutePath() + ")");
		File[] content = folder.listFiles();
		if (content != null)
		{
			for (int i = 0; i != content.length; ++i)
			{
				if (content[i].isDirectory())
				{
					zipFolder(zos, root, content[i]);
				} else
				{
					zos.putNextEntry(new ZipEntry(content[i].getAbsolutePath().substring(root.length())));
					int fileLength = (int) content[i].length();
					InputStream input = new FileInputStream(content[i]);
					byte buffer[] = new byte[fileLength];
					input.read(buffer, 0, fileLength);
					zos.write(buffer, 0, fileLength);
					zos.closeEntry();
				}
			}
		}
	}

	/**
	 *  Unzip a zip file in the given folder (recursively);
	 *  Retrieve is use as this
	 * if retrieve is set to ".swf", the last file found
	 * ending by .swf will be returned.
	 *
	 *@param  tmpdir         Description of the Parameter
	 *@param  retrieve       Description of the Parameter
	 *@param  filename       Description of the Parameter
	 *@return                Description of the Return Value
	 *@exception  Exception  Description of the Exception
	 */
	public static String unzip(String filename, String tmpdir, String retrieve) throws Exception
	{
		File f = new File(filename);
		String result = null;
		ZipFile zip = new ZipFile(f);

		for (Enumeration e = zip.entries(); e.hasMoreElements();)
		{
			ZipEntry ze = (ZipEntry) e.nextElement();
			if (ze.isDirectory())
			{
				String entryName = ze.getName();
				entryName = entryName.replace('\\', '/');
				String dir = tmpdir + entryName;
				File dirfile = new File(dir);
				if (!dirfile.exists())
				{
					dirfile.mkdir();
				}
			}
		}

		for (Enumeration e = zip.entries(); e.hasMoreElements();)
		{
			ZipEntry ze = (ZipEntry) e.nextElement();
			String entryName = tmpdir + ze.getName();
			entryName = entryName.replace('\\', '/');
			if (!ze.isDirectory())
			{
				int end = 0;
				int start = 0;
				while (end >= 0)
				{
					String tmp = "";
					end = entryName.indexOf("/", end);
					if (end >= 0)
					{
						tmp = entryName.substring(start, end);
						end = end + 1;
					}
					File tmpf = new File(tmp);
					if (!tmpf.exists())
					{
						tmpf.mkdir();
					}
				}
				FileOutputStream fos = new FileOutputStream(entryName);
				InputStream is = zip.getInputStream(ze);
				byte[] buf = new byte[5 * 1024];
				// small buffer
				int bytesRead;
				while ((bytesRead = is.read(buf)) != -1)
				{
					fos.write(buf, 0, bytesRead);
				}
				fos.close();

				if (entryName != null && entryName.toLowerCase().endsWith(retrieve.toLowerCase()))
				{
					result = entryName;
				}
			}
		}

		return result;
	}

	/**
	 *  Replace all occurence of "pattern" by "replacement" in the string "src"
	 *  This does not use the "replaceAll()" method of the String class, which often leads to issues since it interprets
	 * some charcaters such as "$".
	 * Rather it does a plain search/replace loop.
	 *
	 *@param  src          Description of the Parameter
	 *@param  pattern      Description of the Parameter
	 *@param  replacement  Description of the Parameter
	 *@return              Description of the Return Value
	 */
	public static String replaceAll(String src, String pattern, String replacement)
	{
		int i = src.indexOf(pattern);
		if (i >= 0)
		{
			src = src.substring(0, i) + replacement + src.substring(i + pattern.length(), src.length());
			return replaceAll(src, pattern, replacement);
		}
		return src;
	}

	/**
	 *  Description of the Method
	 *
	 *@param  prefix  Description of the Parameter
	 *@return         Description of the Return Value
	 */
	public static File createTempFile(String prefix, String path)
	{
		if (prefix == null)
		{
			prefix = "temp";
		}

		//Preferences prefs = CheckerManager.getInstance().getPreferences();
		//String path = prefs.getString("server.path.tmp");

		path = "/tmp/" + path;
		String folder = prefix + new java.util.Date().getTime() + "_" + new Random().nextInt(9999);

		return new File(path, folder);
	}

	/**
	 * Formats a date into
	 * - a user friendly format: 01/19/1977 04:08
	 * - an SQL format: 77-01-19 04:08
	 * @param d
	 * @param sqlFormat
	 * @return
	 */
	public static String formatDate(Date d, boolean sqlFormat)
	{
		GregorianCalendar cal = new GregorianCalendar();
		cal.setTime(d);
		String date = "";
		if (!sqlFormat)
		{
			date = sizeIt(cal.get(Calendar.MONTH) + 1, 2) + "/" + sizeIt(cal.get(Calendar.DAY_OF_MONTH), 2) + "/" + cal.get(Calendar.YEAR) + " " + sizeIt(cal.get(Calendar.HOUR_OF_DAY), 2) + ":" + sizeIt(cal.get(Calendar.MINUTE), 2);
		} else
		{
			date = sizeIt(cal.get(Calendar.YEAR), 2) + "-" + sizeIt(cal.get(Calendar.MONTH) + 1, 2) + "-" + sizeIt(cal.get(Calendar.DAY_OF_MONTH), 2) + " " + sizeIt(cal.get(Calendar.HOUR_OF_DAY), 2) + ":" + sizeIt(cal.get(Calendar.MINUTE), 2);
		}
		return date;
	}

	/**
	 * Pads a number with zeroes to make it requested length
	 * @param i
	 * @param length
	 * @return
	 */
	public static String sizeIt(int i, int length)
	{
		return sizeIt("" + i, length);
	}

	/**
	 * Pads a string(number) with zeroes to make itt requested length
	 * @param s
	 * @param length
	 * @return
	 */
	public static String sizeIt(String s, int length)
	{
		while (s.length() < length)
		{
			s = "0" + s;
		}
		return s;
	}

	/**
	 * Checks wether s string is at least minSize long
	 * @param field
	 * @param minSize
	 * @return
	 */
	public static boolean checkFieldLength(String field, int minSize)
	{
		if (field == null)
		{
			return false;
		}
		return field.length() >= minSize;
	}

	/**
	 * Validates wether an email address seem to be valid (ie: ~ aa@bb.cc)
	 * @param email
	 * @return
	 */
	public static boolean checkEmail(String email)
	{
		if (email == null || email.length() < 4)
		{
			return false;
		}
		int i1 = email.indexOf("@");
		int i2 = email.indexOf(".", i1);
		if (i1 == -1 || i2 == -1 || i1 < 1 || i2 < i1)
		{
			return false;
		}
		return true;
	}

	public static String upperCase(String s)
	{
		if (s == null)
		{
			return s;
		}
		return s.toUpperCase();
	}

	public static String lowerCase(String s)
	{
		if (s == null)
		{
			return s;
		}
		return s.toLowerCase();
	}

	/**
	 * Uppercase the first letter of a string (ie: name)
	 * @param s
	 * @return
	 */
	public static String upperFirst(String s)
	{
		if (s == null || s.length() == 0)
		{
			return s;
		}
		if (s.length() == 1)
		{
			return s.toUpperCase();
		} else
		{
			return s.substring(0, 1).toUpperCase() + s.substring(1, s.length());
		}

	}

	public static boolean isWindowsOS()
	{
		String os = System.getProperty("os.name");
		return os.startsWith("Windows");
	}

	/**
	 * Padds an umber with 0's to make it correct length
	 * @param nb
	 * @param length
	 * @return
	 */
	public static String formatNumber(int nb, int length)
	{
		return sizeIt(nb, length);
	}

	/**
	 * The Standard java response.sendredirect tries to rebuild the full URL using the servlet path
	 * This will not work with java behind a proxy (since it will use the proxy path rather than vanity URL)
	 * So here we just send a simple (possibly relative) URL.
	 * @param res
	 * @param newLocation
	 * @param permanent
	 */
	public static void sendRedirect(HttpServletResponse res, String newLocation, boolean permanent, boolean encodeIt)
	{
		try
		{
			/*
			 * Not that encoding add the jsessionid and thta can can issues: SEO and others.
			 */
			if (encodeIt)
			{
				/**
				 * Note: when using "localhost" on firefox, it doesn;t accept the cookie
				 * and instead use a url jsessionid
				 * strange !
				 */
				newLocation = res.encodeRedirectURL(newLocation);
			}
			res.setStatus(permanent ? HttpServletResponse.SC_MOVED_PERMANENTLY : HttpServletResponse.SC_MOVED_TEMPORARILY);
			res.setHeader("Location", newLocation);
			res.flushBuffer();
		} catch (Exception e)
		{
			JOTLogger.logException(JOTLogger.CAT_FLOW, JOTLogger.ERROR_LEVEL, JOTUtilities.class, "sendRedirect failed for:" + newLocation, e);
		}
	}

	/**
	 * Computes an SHA1 hash as an Hex format string.
	 * @param input
	 * @return
	 * @throws java.lang.Exception
	 */
	public static String getSHA1Hash(String input) throws Exception
	{
		//calculate hash
		MessageDigest digest = MessageDigest.getInstance("SHA-1");
		byte[] hash = digest.digest(input.getBytes());
		// convert to Hexadecimal
		BigInteger bi = new BigInteger(hash);
		return bi.toString(16);
	}

	/**
	 * Checks if "f" is within "folder" hierarchy (recursively)
	 * ie: if folder is an ancestor of f.
	 * @param f
	 * @param folder
	 * @return
	 */
	public static boolean isWithinFolder(File f, File folder)
	{
		// we reached file system root without success
		if (f == null)
		{
			if (folder == null)
			{
				return true;
			} else
			{
				return false;
			}
		}
		// keep browsing from "f" up until we find "folder"
		if (f != null && f.equals(folder))
		{
			return true;
		} else
		{
			return isWithinFolder(f.getParentFile(), folder);
		}
	}

	/**
	 * Returns java standrad tmp dir (java.io.tmpdir)
	 * @return
	 */
	public static File getStandardTmpDir()
	{
		// Usually /tmp on unix    c:\\temp on windows
		return new File(System.getProperty("java.io.tmpdir"));
	}

	/**
	 * Computes the MD5 hash of a file's content
	 * @param f
	 * @return
	 * @throws java.lang.Exception
	 */
	public static String getFileMd5(File f) throws Exception
	{
		MessageDigest digest = MessageDigest.getInstance("MD5");
		InputStream is = new FileInputStream(f);
		byte[] buffer = new byte[50000];
		int read = 0;
		String md5 = null;
		try
		{
			while ((read = is.read(buffer)) != -1)
			{
				digest.update(buffer, 0, read);
			}
			byte[] md5sum = digest.digest();
			BigInteger bigInt = new BigInteger(1, md5sum);
			md5 = bigInt.toString(16);
		} catch (IOException e)
		{
			throw new Exception("Failed to compute MD5: ", e);
		} finally
		{
			try
			{
				is.close();
			} catch (IOException e)
			{
			}
		}
		return md5;
	}

	/**
	 * Sorts the file listing
	 * @return the sorted files
	 * @param sortOrder: use one of the constants here such as SORT_BY_NAME_DESC
	 */
	public static File[] sortFolderListing(File[] files, int sortOrder)
	{
		Comparator comp = JOTFileComparators.NAME_ASC_COMPARATOR;
		switch (sortOrder)
		{
			case SORT_BY_NAME_DESC:
				comp = JOTFileComparators.NAME_DESC_COMPARATOR;
				break;
			case SORT_BY_SIZE_ASC:
				comp = JOTFileComparators.SIZE_ASC_COMPARATOR;
				break;
			case SORT_BY_SIZE_DESC:
				comp = JOTFileComparators.SIZE_DESC_COMPARATOR;
				break;
			case SORT_BY_TSTAMP_ASC:
				comp = JOTFileComparators.TSTAMP_ASC_COMPARATOR;
				break;
			case SORT_BY_TSTAMP_DESC:
				comp = JOTFileComparators.TSTAMP_DESC_COMPARATOR;
				break;
		}
		Arrays.sort(files, comp);
		Collection coll = Arrays.asList(files);
		Vector v = new Vector(coll);
		return (File[]) v.toArray(files);
	}

	public static String getShortClassname(Class clazz)
	{
		if (clazz == null)
		{
			return "null";
		}
		String name = clazz.getName();
		if (name != null && name.indexOf(".") != -1)
		{
			name = name.substring(name.lastIndexOf(".") + 1);
		}
		return name;
	}
}

Generated By: JavaOnTracks Doclet 0.1.5     ©Thibaut Colar