This repository has been archived by the owner on Mar 14, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 233
/
FileManager.java
1731 lines (1630 loc) · 51.1 KB
/
FileManager.java
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
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2010-2017, sikuli.org, sikulix.com - MIT license
*/
package org.sikuli.basics;
import org.sikuli.script.RunTime;
import java.awt.Desktop;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.security.CodeSource;
import java.util.*;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import org.sikuli.script.Image;
import org.sikuli.script.ImagePath;
import org.sikuli.script.Sikulix;
/**
* INTERNAL USE: Support for accessing files and other ressources
*/
public class FileManager {
private static String me = "FileManager";
private static int lvl = 3;
private static void log(int level, String message, Object... args) {
Debug.logx(level, me + ": " + message, args);
}
static final int DOWNLOAD_BUFFER_SIZE = 153600;
private static SplashFrame _progress = null;
private static final String EXECUTABLE = "#executable";
public static int tryGetFileSize(URL aUrl) {
HttpURLConnection conn = null;
try {
if (getProxy() != null) {
conn = (HttpURLConnection) aUrl.openConnection(getProxy());
} else {
conn = (HttpURLConnection) aUrl.openConnection();
}
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setRequestMethod("HEAD");
conn.getInputStream();
return conn.getContentLength();
} catch (Exception ex) {
return 0;
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
public static int isUrlUseabel(String sURL) {
try {
return isUrlUseabel(new URL(sURL));
} catch (Exception ex) {
return -1;
}
}
public static int isUrlUseabel(URL aURL) {
HttpURLConnection conn = null;
try {
// HttpURLConnection.setFollowRedirects(false);
if (getProxy() != null) {
conn = (HttpURLConnection) aURL.openConnection(getProxy());
} else {
conn = (HttpURLConnection) aURL.openConnection();
}
// con.setInstanceFollowRedirects(false);
conn.setRequestMethod("HEAD");
int retval = conn.getResponseCode();
// HttpURLConnection.HTTP_BAD_METHOD 405
// HttpURLConnection.HTTP_NOT_FOUND 404
if (retval == HttpURLConnection.HTTP_OK) {
return 1;
} else if (retval == HttpURLConnection.HTTP_NOT_FOUND) {
return 0;
} else if (retval == HttpURLConnection.HTTP_FORBIDDEN) {
return 0;
} else {
return -1;
}
} catch (Exception ex) {
return -1;
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
public static Proxy getProxy() {
Proxy proxy = Settings.proxy;
if (!Settings.proxyChecked) {
String phost = Settings.proxyName;
String padr = Settings.proxyIP;
String pport = Settings.proxyPort;
InetAddress a = null;
int p = -1;
if (phost != null) {
a = getProxyAddress(phost);
}
if (a == null && padr != null) {
a = getProxyAddress(padr);
}
if (a != null && pport != null) {
p = getProxyPort(pport);
}
if (a != null && p > 1024) {
proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(a, p));
log(lvl, "Proxy defined: %s : %d", a.getHostAddress(), p);
}
Settings.proxyChecked = true;
Settings.proxy = proxy;
}
return proxy;
}
public static boolean setProxy(String pName, String pPort) {
InetAddress a = null;
String host = null;
String adr = null;
int p = -1;
if (pName != null) {
a = getProxyAddress(pName);
if (a == null) {
a = getProxyAddress(pName);
if (a != null) {
adr = pName;
}
} else {
host = pName;
}
}
if (a != null && pPort != null) {
p = getProxyPort(pPort);
}
if (a != null && p > 1024) {
log(lvl, "Proxy stored: %s : %d", a.getHostAddress(), p);
Settings.proxyChecked = true;
Settings.proxyName = host;
Settings.proxyIP = adr;
Settings.proxyPort = pPort;
Settings.proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(a, p));
PreferencesUser prefs = PreferencesUser.getInstance();
prefs.put("ProxyName", (host == null ? "" : host));
prefs.put("ProxyIP", (adr == null ? "" : adr));
prefs.put("ProxyPort", ""+p);
return true;
}
return false;
}
/**
* download a file at the given url to a local folder
*
* @param url a valid url
* @param localPath the folder where the file should go (will be created if necessary)
* @return the absolute path to the downloaded file or null on any error
*/
public static String downloadURL(URL url, String localPath) {
String[] path = url.getPath().split("/");
String filename = path[path.length - 1];
String targetPath = null;
int srcLength = 1;
int srcLengthKB = 0;
int done;
int totalBytesRead = 0;
File fullpath = new File(localPath);
if (fullpath.exists()) {
if (fullpath.isFile()) {
log(-1, "download: target path must be a folder:\n%s", localPath);
fullpath = null;
}
} else {
if (!fullpath.mkdirs()) {
log(-1, "download: could not create target folder:\n%s", localPath);
fullpath = null;
}
}
if (fullpath != null) {
srcLength = tryGetFileSize(url);
srcLengthKB = (int) (srcLength / 1024);
if (srcLength > 0) {
log(lvl, "Downloading %s having %d KB", filename, srcLengthKB);
} else {
log(lvl, "Downloading %s with unknown size", filename);
}
fullpath = new File(localPath, filename);
targetPath = fullpath.getAbsolutePath();
done = 0;
if (_progress != null) {
_progress.setProFile(filename);
_progress.setProSize(srcLengthKB);
_progress.setProDone(0);
_progress.setVisible(true);
}
InputStream reader = null;
FileOutputStream writer = null;
try {
writer = new FileOutputStream(fullpath);
if (getProxy() != null) {
reader = url.openConnection(getProxy()).getInputStream();
} else {
reader = url.openConnection().getInputStream();
}
byte[] buffer = new byte[DOWNLOAD_BUFFER_SIZE];
int bytesRead = 0;
long begin_t = (new Date()).getTime();
long chunk = (new Date()).getTime();
while ((bytesRead = reader.read(buffer)) > 0) {
writer.write(buffer, 0, bytesRead);
totalBytesRead += bytesRead;
if (srcLength > 0) {
done = (int) ((totalBytesRead / (double) srcLength) * 100);
} else {
done = (int) (totalBytesRead / 1024);
}
if (((new Date()).getTime() - chunk) > 1000) {
if (_progress != null) {
_progress.setProDone(done);
}
chunk = (new Date()).getTime();
}
}
writer.close();
log(lvl, "downloaded %d KB to:\n%s", (int) (totalBytesRead / 1024), targetPath);
log(lvl, "download time: %d", (int) (((new Date()).getTime() - begin_t) / 1000));
} catch (Exception ex) {
log(-1, "problems while downloading\n%s", ex);
targetPath = null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ex) {
}
}
if (writer != null) {
try {
writer.close();
} catch (IOException ex) {
}
}
}
if (_progress != null) {
if (targetPath == null) {
_progress.setProDone(-1);
} else {
if (srcLength <= 0) {
_progress.setProSize((int) (totalBytesRead / 1024));
}
_progress.setProDone(100);
}
_progress.closeAfter(3);
_progress = null;
}
}
if (targetPath == null) {
fullpath.delete();
}
return targetPath;
}
/**
* download a file at the given url to a local folder
*
* @param url a string representing a valid url
* @param localPath the folder where the file should go (will be created if necessary)
* @return the absolute path to the downloaded file or null on any error
*/
public static String downloadURL(String url, String localPath) {
URL urlSrc = null;
try {
urlSrc = new URL(url);
} catch (MalformedURLException ex) {
log(-1, "download: bad URL: " + url);
return null;
}
return downloadURL(urlSrc, localPath);
}
public static String downloadURL(String url, String localPath, JFrame progress) {
_progress = (SplashFrame) progress;
return downloadURL(url, localPath);
}
public static String downloadURLtoString(String src) {
URL url = null;
try {
url = new URL(src);
} catch (MalformedURLException ex) {
log(-1, "download to string: bad URL:\n%s", src);
return null;
}
return downloadURLtoString(url);
}
public static String downloadURLtoString(URL uSrc) {
String content = "";
InputStream reader = null;
log(lvl, "download to string from:\n%s,", uSrc);
try {
if (getProxy() != null) {
reader = uSrc.openConnection(getProxy()).getInputStream();
} else {
reader = uSrc.openConnection().getInputStream();
}
byte[] buffer = new byte[DOWNLOAD_BUFFER_SIZE];
int bytesRead = 0;
while ((bytesRead = reader.read(buffer)) > 0) {
content += (new String(Arrays.copyOfRange(buffer, 0, bytesRead), Charset.forName("utf-8")));
}
} catch (Exception ex) {
log(-1, "problems while downloading\n" + ex.getMessage());
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ex) {
}
}
}
return content;
}
/**
* open the given url in the standard browser
*
* @param url string representing a valid url
* @return false on error, true otherwise
*/
public static boolean openURL(String url) {
try {
URL u = new URL(url);
Desktop.getDesktop().browse(u.toURI());
} catch (Exception ex) {
log(-1, "show in browser: bad URL: " + url);
return false;
}
return true;
}
public static File createTempDir(String path) {
File fTempDir = new File(RunTime.get().fpBaseTempPath, path);
log(lvl, "createTempDir:\n%s", fTempDir);
if (!fTempDir.exists()) {
fTempDir.mkdirs();
} else {
FileManager.resetFolder(fTempDir);
}
if (!fTempDir.exists()) {
log(-1, "createTempDir: not possible: %s", fTempDir);
return null;
}
return fTempDir;
}
public static File createTempDir() {
File fTempDir = createTempDir("tmp-" + getRandomInt() + ".sikuli");
if (null != fTempDir) {
fTempDir.deleteOnExit();
}
return fTempDir;
}
public static int getRandomInt() {
int rand = 1 + new Random().nextInt();
return (rand < 0 ? rand * -1 : rand);
}
public static void deleteTempDir(String path) {
if (!deleteFileOrFolder(path)) {
log(-1, "deleteTempDir: not possible");
}
}
public static boolean deleteFileOrFolder(File fPath, FileFilter filter) {
return doDeleteFileOrFolder(fPath, filter);
}
public static boolean deleteFileOrFolder(File fPath) {
return doDeleteFileOrFolder(fPath, null);
}
public static boolean deleteFileOrFolder(String fpPath, FileFilter filter) {
if (fpPath.startsWith("#")) {
fpPath = fpPath.substring(1);
} else {
log(lvl, "deleteFileOrFolder: %s\n%s", (filter == null ? "" : "filtered: "), fpPath);
}
return doDeleteFileOrFolder(new File(fpPath), filter);
}
public static boolean deleteFileOrFolder(String fpPath) {
if (fpPath.startsWith("#")) {
fpPath = fpPath.substring(1);
} else {
log(lvl, "deleteFileOrFolder:\n%s", fpPath);
}
return doDeleteFileOrFolder(new File(fpPath), null);
}
public static void resetFolder(File fPath) {
log(lvl, "resetFolder:\n%s", fPath);
doDeleteFileOrFolder(fPath, null);
fPath.mkdirs();
}
private static boolean doDeleteFileOrFolder(File fPath, FileFilter filter) {
if (fPath == null) {
return false;
}
File aFile;
String[] entries;
boolean somethingLeft = false;
if (fPath.exists() && fPath.isDirectory()) {
entries = fPath.list();
for (int i = 0; i < entries.length; i++) {
aFile = new File(fPath, entries[i]);
if (filter != null && !filter.accept(aFile)) {
somethingLeft = true;
continue;
}
if (aFile.isDirectory()) {
if (!doDeleteFileOrFolder(aFile, filter)) {
return false;
}
} else {
try {
aFile.delete();
} catch (Exception ex) {
log(-1, "deleteFile: not deleted:\n%s\n%s", aFile, ex);
return false;
}
}
}
}
// deletes intermediate empty directories and finally the top now empty dir
if (!somethingLeft && fPath.exists()) {
try {
fPath.delete();
} catch (Exception ex) {
log(-1, "deleteFolder: not deleted:\n" + fPath.getAbsolutePath() + "\n" + ex.getMessage());
return false;
}
}
return true;
}
public static void traverseFolder(File fPath, FileFilter filter) {
if (fPath == null) {
return;
}
File aFile;
String[] entries;
if (fPath.isDirectory()) {
entries = fPath.list();
for (int i = 0; i < entries.length; i++) {
aFile = new File(fPath, entries[i]);
if (filter != null) {
filter.accept(aFile);
}
if (aFile.isDirectory()) {
traverseFolder(aFile, filter);
}
}
}
}
public static File createTempFile(String suffix) {
return createTempFile(suffix, null);
}
public static File createTempFile(String suffix, String path) {
String temp1 = "sikuli-";
String temp2 = "." + suffix;
File fpath = new File(RunTime.get().fpBaseTempPath);
if (path != null) {
fpath = new File(path);
}
try {
fpath.mkdirs();
File temp = File.createTempFile(temp1, temp2, fpath);
temp.deleteOnExit();
String fpTemp = temp.getAbsolutePath();
if (!fpTemp.endsWith(".script")) {
log(lvl, "tempfile create:\n%s", temp.getAbsolutePath());
}
return temp;
} catch (IOException ex) {
log(-1, "createTempFile: IOException: %s\n%s", ex.getMessage(),
fpath + File.separator + temp1 + "12....56" + temp2);
return null;
}
}
public static String saveTmpImage(BufferedImage img) {
return saveTmpImage(img, null);
}
public static String saveTmpImage(BufferedImage img, String path) {
File tempFile;
try {
tempFile = createTempFile("png", path);
if (tempFile != null) {
ImageIO.write(img, "png", tempFile);
return tempFile.getAbsolutePath();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String saveTimedImage(BufferedImage img) {
return saveTimedImage(img, ImagePath.getBundlePath(), null);
}
public static String saveTimedImage(BufferedImage img, String path) {
return saveTimedImage(img, path, null);
}
public static String saveTimedImage(BufferedImage img, String path, String name) {
RunTime.pause(0.01f);
File fImage = new File(path, String.format("%s-%d.png", name, new Date().getTime()));
try {
ImageIO.write(img, "png", fImage);
} catch (Exception ex) {
return "";
}
return fImage.getAbsolutePath();
}
public static boolean unzip(String inpZip, String target) {
return unzip(new File(inpZip), new File(target));
}
public static boolean unzip(File fZip, File fTarget) {
String fpZip = null;
String fpTarget = null;
log(lvl, "unzip: from: %s\nto: %s", fZip, fTarget);
try {
fpZip = fZip.getCanonicalPath();
if (!new File(fpZip).exists()) {
throw new IOException();
}
} catch (IOException ex) {
log(-1, "unzip: source not found:\n%s\n%s", fpZip, ex);
return false;
}
try {
fpTarget = fTarget.getCanonicalPath();
deleteFileOrFolder(fpTarget);
new File(fpTarget).mkdirs();
if (!new File(fpTarget).exists()) {
throw new IOException();
}
} catch (IOException ex) {
log(-1, "unzip: target cannot be created:\n%s\n%s", fpTarget, ex);
return false;
}
ZipInputStream inpZip = null;
ZipEntry entry = null;
try {
final int BUF_SIZE = 2048;
inpZip = new ZipInputStream(new BufferedInputStream(new FileInputStream(fZip)));
while ((entry = inpZip.getNextEntry()) != null) {
if (entry.getName().endsWith("/") || entry.getName().endsWith("\\")) {
new File(fpTarget, entry.getName()).mkdir();
continue;
}
int count;
byte data[] = new byte[BUF_SIZE];
File outFile = new File(fpTarget, entry.getName());
File outFileParent = outFile.getParentFile();
if (! outFileParent.exists()) {
outFileParent.mkdirs();
}
FileOutputStream fos = new FileOutputStream(outFile);
BufferedOutputStream dest = new BufferedOutputStream(fos, BUF_SIZE);
while ((count = inpZip.read(data, 0, BUF_SIZE)) != -1) {
dest.write(data, 0, count);
}
dest.close();
}
} catch (Exception ex) {
log(-1, "unzip: not possible: source:\n%s\ntarget:\n%s\n(%s)%s",
fpZip, fpTarget, entry.getName(), ex);
return false;
} finally {
try {
inpZip.close();
} catch (IOException ex) {
log(-1, "unzip: closing source:\n%s\n%s", fpZip, ex);
}
}
return true;
}
public static boolean xcopy(File fSrc, File fDest) {
if (fSrc == null || fDest == null) {
return false;
}
try {
doXcopy(fSrc, fDest, null);
} catch (Exception ex) {
log(lvl, "xcopy from: %s\nto: %s\n%s", fSrc, fDest, ex);
return false;
}
return true;
}
public static boolean xcopy(File fSrc, File fDest, FileFilter filter) {
if (fSrc == null || fDest == null) {
return false;
}
try {
doXcopy(fSrc, fDest, filter);
} catch (Exception ex) {
log(lvl, "xcopy from: %s\nto: %s\n%s", fSrc, fDest, ex);
return false;
}
return true;
}
public static void xcopy(String src, String dest) throws IOException {
doXcopy(new File(src), new File(dest), null);
}
public static void xcopy(String src, String dest, FileFilter filter) throws IOException {
doXcopy(new File(src), new File(dest), filter);
}
private static void doXcopy(File fSrc, File fDest, FileFilter filter) throws IOException {
if (fSrc.getAbsolutePath().equals(fDest.getAbsolutePath())) {
return;
}
if (fSrc.isDirectory()) {
if (filter == null || filter.accept(fSrc)) {
if (!fDest.exists()) {
fDest.mkdirs();
}
String[] children = fSrc.list();
for (String child : children) {
if (child.equals(fDest.getName())) {
continue;
}
doXcopy(new File(fSrc, child), new File(fDest, child), filter);
}
}
} else {
if (filter == null || filter.accept(fSrc)) {
if (fDest.isDirectory()) {
fDest = new File(fDest, fSrc.getName());
}
InputStream in = new FileInputStream(fSrc);
OutputStream out = new FileOutputStream(fDest);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
}
private static String makeFileListString;
private static String makeFileListPrefix;
public static String makeFileList(File path, String prefix) {
makeFileListPrefix = prefix;
return makeFileListDo(path, true);
}
private static String makeFileListDo(File path, boolean starting) {
String x;
if (starting) {
makeFileListString = "";
}
if (!path.exists()) {
return makeFileListString;
}
if (path.isDirectory()) {
String[] fcl = path.list();
for (String fc : fcl) {
makeFileListDo(new File(path, fc), false);
}
} else {
x = path.getAbsolutePath();
if (!makeFileListPrefix.isEmpty()) {
x = x.replace(makeFileListPrefix, "").replace("\\", "/");
if (x.startsWith("/")) {
x = x.substring(1);
}
}
makeFileListString += x + "\n";
}
return makeFileListString;
}
/**
* Copy a file *src* to the path *dest* and check if the file name conflicts. If a file with the
* same name exists in that path, rename *src* to an alternative name.
* @param src source file
* @param dest destination path
* @return the destination file if ok, null otherwise
* @throws java.io.IOException on failure
*/
public static File smartCopy(String src, String dest) throws IOException {
File fSrc = new File(src);
String newName = fSrc.getName();
File fDest = new File(dest, newName);
if (fSrc.equals(fDest)) {
return fDest;
}
while (fDest.exists()) {
newName = getAltFilename(newName);
fDest = new File(dest, newName);
}
xcopy(src, fDest.getAbsolutePath());
if (fDest.exists()) {
return fDest;
}
return null;
}
public static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public static String getAltFilename(String filename) {
int pDot = filename.lastIndexOf('.');
int pDash = filename.lastIndexOf('-');
int ver = 1;
String postfix = filename.substring(pDot);
String name;
if (pDash >= 0) {
name = filename.substring(0, pDash);
ver = Integer.parseInt(filename.substring(pDash + 1, pDot));
ver++;
} else {
name = filename.substring(0, pDot);
}
return name + "-" + ver + postfix;
}
public static boolean exists(String path) {
File f = new File(path);
return f.exists();
}
public static void mkdir(String path) {
File f = new File(path);
if (!f.exists()) {
f.mkdirs();
}
}
public static String getName(String filename) {
File f = new File(filename);
return f.getName();
}
public static String slashify(String path, Boolean isDirectory) {
if (path != null) {
if (path.contains("%")) {
try {
path = URLDecoder.decode(path, "UTF-8");
} catch (Exception ex) {
log(lvl, "slashify: decoding problem with %s\nwarning: filename might not be useable.", path);
}
}
if (File.separatorChar != '/') {
path = path.replace(File.separatorChar, '/');
}
if (isDirectory != null) {
if (isDirectory) {
if (!path.endsWith("/")) {
path = path + "/";
}
} else if (path.endsWith("/")) {
path = path.substring(0, path.length() - 1);
}
}
if (path.startsWith("./")) {
path = path.substring(2);
}
return path;
} else {
return "";
}
}
public static String normalize(String filename) {
return slashify(filename, false);
}
public static String normalizeAbsolute(String filename, boolean withTrailingSlash) {
filename = slashify(filename, false);
String jarSuffix = "";
int nJarSuffix;
if (-1 < (nJarSuffix = filename.indexOf(".jar!/"))) {
jarSuffix = filename.substring(nJarSuffix + 4);
filename = filename.substring(0, nJarSuffix + 4);
}
File aFile = new File(filename);
try {
filename = aFile.getCanonicalPath();
aFile = new File(filename);
} catch (Exception ex) {
}
String fpFile = aFile.getAbsolutePath();
if (!fpFile.startsWith("/")) {
fpFile = "/" + fpFile;
}
return slashify(fpFile + jarSuffix, withTrailingSlash);
}
public static boolean isFilenameDotted(String name) {
String nameParent = new File(name).getParent();
if (nameParent != null && nameParent.contains(".")) {
return true;
}
return false;
}
/**
* Returns the directory that contains the images used by the ScriptRunner.
*
* @param scriptFile The file containing the script.
* @return The directory containing the images.
*/
public static File resolveImagePath(File scriptFile) {
if (!scriptFile.isDirectory()) {
return scriptFile.getParentFile();
}
return scriptFile;
}
public static URL makeURL(String fName) {
return makeURL(fName, "file");
}
public static URL makeJarURL(File fJar) {
return makeURL(fJar.getAbsolutePath(), "jar");
}
public static URL makeURL(String fName, String type) {
try {
if ("file".equals(type)) {
fName = normalizeAbsolute(fName, false);
if (!fName.startsWith("/")) {
fName = "/" + fName;
}
}
if ("jar".equals(type)) {
if (!fName.contains("!/")) {
fName += "!/";
}
URL url = new URL("jar:file:" + fName);
return url;
} else if ("file".equals(type)) {
File aFile = new File(fName);
if (aFile.exists() && aFile.isDirectory()) {
if (!fName.endsWith("/")) {
fName += "/";
}
}
}
return new URL(type, null, fName);
} catch (MalformedURLException ex) {
return null;
}
}
public static URL makeURL(URL path, String fName) {
try {
if ("file".equals(path.getProtocol())) {
return makeURL(new File(path.getFile(), fName).getAbsolutePath());
} else if ("jar".equals(path.getProtocol())) {
String jp = path.getPath();
if (!jp.contains("!/")) {
jp += "!/";
}
String jpu = "jar:" + jp;
if (jp.endsWith("!/")) {
jpu += fName;
} else {
jpu += "/" + fName;
}
return new URL(jpu);
}
return new URL(path, slashify(fName, false));
} catch (MalformedURLException ex) {
return null;
}
}
public static URL getURLForContentFromURL(URL uRes, String fName) {
URL aURL = null;
if ("jar".equals(uRes.getProtocol())) {
return makeURL(uRes, fName);
} else if ("file".equals(uRes.getProtocol())) {
aURL = makeURL(new File(slashify(uRes.getPath(), false), slashify(fName, false)).getPath(), uRes.getProtocol());
} else if (uRes.getProtocol().startsWith("http")) {
String sRes = uRes.toString();
if (!sRes.endsWith("/")) {
sRes += "/";
}
try {
aURL = new URL(sRes + fName);
if (1 == isUrlUseabel(aURL)) {
return aURL;
} else {
return null;
}
} catch (MalformedURLException ex) {
return null;
}
}
try {
if (aURL != null) {
aURL.getContent();
return aURL;
}
} catch (IOException ex) {
return null;
}
return aURL;
}
public static boolean checkJarContent(String jarPath, String jarContent) {
URL jpu = makeURL(jarPath, "jar");
if (jpu != null && jarContent != null) {
jpu = makeURL(jpu, jarContent);
}
if (jpu != null) {
try {
jpu.getContent();
return true;
} catch (IOException ex) {
ex.getMessage();
}
}
return false;
}
public static int getPort(String p) {
int port;