-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJar.java
More file actions
728 lines (615 loc) · 25.8 KB
/
Jar.java
File metadata and controls
728 lines (615 loc) · 25.8 KB
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
package javaxt.io;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.FileInputStream;
//Imports for dealing with ZIP files
import java.net.URI;
import java.util.zip.*;
//******************************************************************************
//** Jar Class
//******************************************************************************
/**
* Used to find entries in a jar file associated with a given class or
* package.
*
* The original motivation behind this class was to support a requirement to
* extract and update config files stored in Java packages. For console apps,
* the config file is stored in the jar (zip) file. For web apps, chances are
* that the package has been un-zipped and the config file is laying around
* on disk. This class was designed to support both use cases.
*
******************************************************************************/
public class Jar {
private java.io.File file;
private java.lang.Package Package;
//**************************************************************************
//** Constructor
//**************************************************************************
/** Creates a new instance of this class using an instance of another class.
*/
public Jar(java.lang.Object object){
this(object.getClass());
}
//**************************************************************************
//** Constructor
//**************************************************************************
/** Creates a new instance of this class using a Class.
*/
public Jar(java.lang.Class Class) {
this.Package = Class.getPackage();
String path = Class.getName();
if (path!=null) path = path.replace((CharSequence)".",(CharSequence)"/") + ".class";
java.util.ArrayList<java.net.URL> urls = getResource(path, Class.getClassLoader());
if (urls.size()==1){
file = getFile(urls.get(0));
}
/*
else if (urls.size()>1){ //Should never happen!
for (java.net.URL url : urls){
java.net.JarURLConnection urlcon = (java.net.JarURLConnection) (url.openConnection());
java.util.jar.JarFile jar = urlcon.getJarFile();
java.util.Enumeration<java.util.jar.JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
String entry = entries.nextElement().getName();
//System.out.println(entry);
}
}
}
*/
}
//**************************************************************************
//** Constructor
//**************************************************************************
/** Creates a new instance of this class using a Package. This method is
* somewhat unreliable if there are multiple jar files that contain the
* same package name. Suggest using the getJars() method instead.
*/
public Jar(java.lang.Package Package) {
this.Package = Package;
String path = Package.getName().replace((CharSequence)".",(CharSequence)"/");
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
for (java.net.URL url : getResource(path, classLoader)){
file = getFile(url);
if (file!=null) break;
}
}
//**************************************************************************
//** Constructor
//**************************************************************************
/** Creates a new instance of this class using a path to a jar file or
* directory.
*/
public Jar(java.io.File file){
this.file = file;
}
//**************************************************************************
//** getJars
//**************************************************************************
/** Returns an array of files or directories associated with a given Package.
* This method should be used instead of new Jar(java.lang.Package).
*/
public static Jar[] getJars(java.lang.Package Package){
return getJars(Package.getName());
}
public static Jar[] getJars(String packageName){
java.util.ArrayList<Jar> jars = new java.util.ArrayList<Jar>();
String path = packageName.replace((CharSequence)".",(CharSequence)"/");
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
for (java.net.URL url : getResource(path, classLoader)){
java.io.File file = getFile(url);
if (file!=null) jars.add(new Jar(file));
}
return jars.toArray(new Jar[jars.size()]);
}
//**************************************************************************
//** getFile
//**************************************************************************
/** Returns a java.io.File representation of the jar file or directory where
* the jar file has been extracted.
*/
public java.io.File getFile(){
return file;
}
//**************************************************************************
//** getManifest
//**************************************************************************
/** Returns the Manifest file found in the "META-INF" directory. The
* Manifest file contains metadata for the jar file including version
* numbers, vendor name, etc. You can loop through properties in the
* Manifest like this:
<pre>
java.io.File file = new java.io.File("/Drivers/h2/h2-1.3.162.jar");
java.util.jar.JarFile jar = new javaxt.io.Jar(file);
java.util.jar.Manifest manifest = jar.getManifest();
System.out.println("\r\nMain Attributes:\r\n--------------------------");
printAttributes(manifest.getMainAttributes());
System.out.println("\r\nOther Attributes:\r\n--------------------------");
java.util.Map<String, java.util.jar.Attributes> entries = manifest.getEntries();
java.util.Iterator<String> it = entries.keySet().iterator();
while (it.hasNext()){
String key = it.next();
printAttributes(entries.get(key));
System.out.println();
}
jar.close();
private static void printAttributes(java.util.jar.Attributes attributes){
java.util.Iterator it = attributes.keySet().iterator();
while (it.hasNext()){
java.util.jar.Attributes.Name key = (java.util.jar.Attributes.Name) it.next();
Object value = attributes.get(key);
System.out.println(key + ": " + value);
}
}
</pre>
*/
public java.util.jar.Manifest getManifest(){
try{
Entry entry = this.getEntry("META-INF", "MANIFEST.MF");
if (entry!=null) {
ByteArrayInputStream is = new ByteArrayInputStream(entry.getBytes());
java.util.jar.Manifest manifest = new java.util.jar.Manifest(is);
is.close();
return manifest;
}
}
catch(Exception e){
}
return null;
}
//**************************************************************************
//** getVersion
//**************************************************************************
/** Returns the version number of the jar file, if available. Two different
* strategies are used to find the version number. First strategy is to
* parse the jar file manifest and return the value of the
* "Implementation-Version" or "Bundle-Version", whichever is found first.
* If no version information is found in the manifest, an attempt is made
* to parse the file name. Returns a null is no version information is
* available.
*/
public String getVersion(){
java.util.jar.Attributes attributes = getManifest().getMainAttributes();
if (attributes!=null){
java.util.Iterator it = attributes.keySet().iterator();
while (it.hasNext()){
java.util.jar.Attributes.Name key = (java.util.jar.Attributes.Name) it.next();
String keyword = key.toString();
if (keyword.equals("Implementation-Version") || keyword.equals("Bundle-Version")){
return (String) attributes.get(key);
}
}
}
String fileName = file.getName().substring(0, file.getName().lastIndexOf("."));
if (fileName.contains(".")){
String majorVersion = fileName.substring(0, fileName.indexOf("."));
int delimiter = majorVersion.lastIndexOf("-");
if (majorVersion.indexOf("_")>delimiter) delimiter = majorVersion.indexOf("_");
majorVersion = majorVersion.substring(delimiter+1, fileName.indexOf("."));
String minorVersion = fileName.substring(fileName.indexOf("."));
return majorVersion + minorVersion;
}
return null;
}
//**************************************************************************
//** getEntries
//**************************************************************************
/** Used to return a list of all the entries found in the jar file.
*/
public Entry[] getEntries(){
java.util.ArrayList<Entry> entries = new java.util.ArrayList<Entry>();
try{
if (file.isDirectory()){
Directory dir = new Directory(file);
java.util.List items = dir.getChildren(true);
for (int i=0; i<items.size(); i++){
Object item = items.get(i);
if (item instanceof File){
entries.add(new Entry(((File) item).toFile()));
}
}
}
else{
ZipInputStream in = new ZipInputStream(new FileInputStream(file));
ZipEntry zipEntry = null;
while((zipEntry = in.getNextEntry())!=null){
entries.add(new Entry(zipEntry));
}
in.close();
}
}
catch(Exception e){
}
return entries.toArray(new Entry[entries.size()]);
}
//**************************************************************************
//** getEntry
//**************************************************************************
/** Used to retrieve a single entry from the jar file. */
public Entry getEntry(String Entry){
return getEntry(Package.getName(),Entry);
}
//**************************************************************************
//** getEntry
//**************************************************************************
/** Used to retrieve a single entry from the jar file.
* @param Package Name of the package or directory in the jar file
* (e.g. "javaxt.io"). Null values and zero length strings default to the
* the root directory.
* @param Entry Name of the class/file found in the given package
* (e.g. "Jar.class").
*/
public Entry getEntry(String Package, String Entry){
ZipInputStream in = null;
try{
if (file.isDirectory()){
return new Entry(new java.io.File(file, Entry));
}
else{
//Update package name and entry
if (Package!=null){
Package = Package.trim();
if (Package.length()==0) Package = null;
}
if (Package!=null){
if (Package.contains(".")) Package = Package.replace(".","/");
Entry = Package + "/" + Entry;
}
//Find entry in the jar file
in = new ZipInputStream(new FileInputStream(file));
ZipEntry zipEntry = null;
while((zipEntry = in.getNextEntry())!=null){
if (zipEntry.getName().equalsIgnoreCase(Entry)){
//System.out.println(zipEntry.getName() + " <--");
Entry entry = new Entry(zipEntry);
in.close();
return entry;
}
}
in.close();
}
}
catch(Exception e){
if (in!=null){
try{ in.close(); }
catch(Exception ex){}
}
//e.printStackTrace();
}
return null;
}
//**************************************************************************
//** getEntries
//**************************************************************************
/** Used to retrieve a single entry from the jar file. */
public Entry getEntry(java.lang.Class Class) {
String ClassName = Class.getName();
String PackageName = Class.getPackage().getName();
ClassName = ClassName.substring(PackageName.length()+1);
return getEntry(PackageName,ClassName+".class");
}
//**************************************************************************
//** getClasses
//**************************************************************************
/** Returns all the classes in the jar file. Returns an empty array if the
* jar file has not been loaded or if there are no classes in the file.
*/
public Class[] getClasses(){
java.util.ArrayList<Class> classes = new java.util.ArrayList<Class>();
java.net.URLClassLoader child = null;
for (Jar.Entry entry : getEntries()){
String name = entry.getName();
if (name.endsWith(".class")){
name = name.substring(0, name.length()-6).replace("/", ".");
try{
classes.add(Class.forName(name));
}
catch(Exception e){
try{
if (child==null){
child = new java.net.URLClassLoader(
new java.net.URL[] {file.toURI().toURL()},
this.getClass().getClassLoader()
);
}
classes.add(Class.forName(name, true, child));
}
catch(Exception e2){
//e2.printStackTrace();
}
}
}
}
return classes.toArray(new Class[classes.size()]);
}
//**************************************************************************
//** toString
//**************************************************************************
/** Returns the path to the jar file. */
public String toString(){
return file.toString();
}
//**************************************************************************
//** getResource
//**************************************************************************
/** Returns the URL associated with a given path in the jar file.
* @param cl ClassLoader used to find the given path/resource. If the
* ClassLoader is null or fails to find the requested path, an alternate
* ClassLoader is used (e.g. ClassLoader's Parent, ContextClassLoader,
* SystemClassLoader).
*/
private static java.util.ArrayList<java.net.URL> getResource(String path, ClassLoader cl){
java.util.ArrayList<java.net.URL> arr = new java.util.ArrayList<java.net.URL>();
try{
int x = 0;
while (true){
if (cl==null){
cl = Thread.currentThread().getContextClassLoader();
if (cl==null){
cl = java.lang.ClassLoader.getSystemClassLoader();
if (cl==null){
break; //Throw Exception?
}
}
}
java.util.Enumeration<java.net.URL> en = cl.getResources(path);
if (en.hasMoreElements()){
while (en.hasMoreElements()){
java.net.URL url = en.nextElement();
arr.add(url);
}
break;
}
else{
if (cl.getParent()!=null && cl.getParent().equals(cl)){
break;
}
cl = cl.getParent();
}
x++;
if (x==50) break;
}
/*
String debug = "";
debug += "Path: " + path + "\r\n";
debug += "ClassLoader: " + cl + "\r\n";
for (java.net.URL url : arr){
debug += "Resource: " + url + "\r\n";
}
System.out.println(debug);
*/
}
catch(Exception e){
//e.printStackTrace();
}
return arr;
}
private static java.io.File getFile(java.net.URL url){
if (url!=null)
try{
java.net.URI uri = new java.net.URI(url.toString().replace((CharSequence)" ",(CharSequence)"%20"));
if (uri.getPath()==null){
String path = uri.toString();
//Special case for nexted jar files (e.g. spring boot)
if (path.startsWith("jar:nested:")){
path = "jar:file:" + path.substring("jar:nested:".length());
}
if (path.startsWith("jar:file:")){
//Update Path and Define Zipped File
path = path.substring(path.indexOf("file:/"));
path = path.substring(0,path.toLowerCase().indexOf(".jar")+4);
if (path.startsWith("file://")){ //UNC Path
path = "C:/" + path.substring(path.indexOf("file:/")+7);
path = "/" + new URI(path).getPath();
}
else{
path = new URI(path).getPath();
}
return new java.io.File(path);
}
else if (path.startsWith("jar:http")){
path = path.substring(path.indexOf("http"));
path = path.substring(0,path.toLowerCase().indexOf(".jar")+4);
}
}
else{
return new java.io.File(uri);
}
}
catch(Exception e){
//e.printStackTrace();
}
return null;
}
//**************************************************************************
//** JAR Entry Class
//**************************************************************************
/** Used to represent an entry in a jar/war file. The jar file might be
* zipped or unpacked by a web server.
*/
public class Entry{
private ZipEntry zipEntry = null;
private java.io.File fileEntry = null;
/** Constructor for zipped jar files. */
private Entry(ZipEntry zipEntry){
this.zipEntry = zipEntry;
}
/** Constructor for unzipped jar files. */
private Entry(java.io.File fileEntry){
this.fileEntry = fileEntry;
}
public String getName(){
if (fileEntry==null) return zipEntry.getName();
else return fileEntry.getName();
}
public java.util.Date getDate(){
if (fileEntry==null) return new java.util.Date(zipEntry.getTime());
else return new java.util.Date(fileEntry.lastModified());
}
/** Returns a long value representing a cyclic redundancy check
* (CRC-32 checksum) of the uncompressed entry data, or -1 if not known.
*/
public long checksum(){
if (fileEntry==null) return zipEntry.getCrc();
else return new javaxt.io.File(fileEntry).checksum();
}
public java.io.File getFile(){
return fileEntry;
}
public long getSize(){
if (fileEntry==null){
return zipEntry.getSize();
}
else{
return fileEntry.length();
}
}
public byte[] getBytes(){
ZipFile zip = null;
try{
if (fileEntry==null){
zip = new ZipFile(file);
java.io.DataInputStream is = new java.io.DataInputStream(zip.getInputStream(zipEntry));
int bufferSize = 1024;
ByteArrayOutputStream bas = new ByteArrayOutputStream();
byte[] b = new byte[bufferSize];
int x=0;
while((x=is.read(b,0,bufferSize))>-1) {
bas.write(b,0,x);
}
bas.close();
zip.close();
return bas.toByteArray();
}
else{
return new javaxt.io.File(fileEntry).getBytes().toByteArray();
}
}
catch(Exception e){
if (zip!=null){
try{ zip.close(); }
catch(Exception ex){}
}
return null;
}
}
/** Used to extract the zip entry to a file. */
public void extractFile(java.io.File destination){
try{
if (fileEntry==null){
destination.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(destination);
ZipInputStream in = new ZipInputStream(new FileInputStream(file));
ZipEntry zipEntry = null;
while((zipEntry = in.getNextEntry())!=null){
if (zipEntry.getName().equals(this.zipEntry.getName())){
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
break;
}
}
in.close();
out.close();
}
else{
//Simply copy the file to the destination
if (destination.isFile()){
new File(fileEntry).copyTo(new File(destination),false);
}
else{
new File(fileEntry).copyTo(new Directory(destination),false);
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
public void setText(String text){
try{
if (fileEntry==null){
ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
ByteArrayInputStream byteInput = new ByteArrayInputStream(text.getBytes());
ZipOutputStream zipOutput = new ZipOutputStream(byteOutput);
ZipInputStream zipInput = new ZipInputStream(new FileInputStream(file));
ZipEntry zipEntry = null;
while((zipEntry = zipInput.getNextEntry())!=null){
if (zipEntry.getName().equals(this.zipEntry.getName())){
//Write Updated Config File
zipOutput.putNextEntry(new ZipEntry(this.zipEntry.getName()));
byte[] buf = new byte[1024];
int len;
while ((len = byteInput.read(buf)) > 0) {
zipOutput.write(buf, 0, len);
}
byteInput.close();
}
else{
zipOutput.putNextEntry(zipEntry);
byte[] buf = new byte[1024];
int len;
while ((len = zipInput.read(buf)) > 0) {
zipOutput.write(buf, 0, len);
}
}
zipInput.closeEntry();
zipOutput.closeEntry();
}
zipInput.close();
zipOutput.close();
FileOutputStream fos = new FileOutputStream(file);
fos.write(byteOutput.toByteArray());
fos.close();
byteOutput.close();
}
else{
new File(fileEntry).write(text);
}
}
catch(Exception e){
}
}
/** Used to extract the contents to a string. */
public String getText(){
return getText("UTF-8");
}
/** Used to extract the contents to a string. Returns null if the
* extraction failed.
* @param charsetName Name of the character encoding used to read the
* file. Examples include UTF-8 and ISO-8859-1
*/
public String getText(String charsetName){
try{
if (fileEntry==null){
ByteArrayOutputStream out = new ByteArrayOutputStream();
ZipInputStream in = new ZipInputStream(new FileInputStream(file));
ZipEntry zipEntry = null;
while((zipEntry = in.getNextEntry())!=null){
if (zipEntry.getName().equals(this.zipEntry.getName())){
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
break;
}
}
in.close();
return out.toString(charsetName);
}
else{
return new File(fileEntry).getText(charsetName);
}
}
catch(Exception e){
return null;
}
}
public String toString(){
return getName();
}
}
}