Subversion Repository Public Repository

litesoft

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
package com.esotericsoftware.scar;

import org.litesoft.logger.*;

import com.esotericsoftware.filesystem.*;
import com.esotericsoftware.scar.support.*;
import com.esotericsoftware.utils.*;

import javax.tools.*;
import java.io.*;
import java.util.*;
import java.util.jar.*;
import java.util.zip.*;

/**
 * Generic Data structure that contains information needed to perform tasks.
 */
@SuppressWarnings("UnusedDeclaration")
public class Project extends ProjectParameters {
    private static final String JAVA_SOURCE_TARGET_VERSION = "1.7";

    protected static final Logger LOGGER = LoggerFactory.getLogger( Project.class );

    private static final String META_INF_MANIFEST_MF = "META-INF/MANIFEST.MF";

    private static final String VERSIONED_URL_PATTERN_PREFIX = "<url-pattern>/v";
    private static final String VERSIONED_SCRIPT_PREFIX = "<script src='v";
    private static final String VERSIONED_SCRIPT_SUFFIX = ".nocache.js'></script>";
    private static final String VERSIONED_MODULE_PREFIX = "<module rename-to=\"v";
    private static final String VERSIONED_MODULE_SUFFIX = "\">";
    private static final String JAVA_HOME = "JAVA_HOME";

    public Project( ProjectParameters pParameters ) {
        super( pParameters.validate() );
        applyDefaults();
    }

    public String getSourceJavaVersion() {
        return JAVA_SOURCE_TARGET_VERSION;
    }

    public String getTargetJavaVersion() {
        return JAVA_SOURCE_TARGET_VERSION;
    }

    protected void packageClean() {
        delete( getPhoneGapDirPath() );
        delete( getAppDirPath() );
        delete( getOneJarPath() );
        delete( getWarPath() );
    }

    protected boolean packageIt() {
        return phoneGapDir() | appDir() | oneJAR() | war(); // Note: SINGLE '|' ORs to force full execution!
    }

    /**
     * Unzips all JARs in the classpath and creates a single JAR containing those files and this Project's JAR (which MUST exist).
     * The manifest from the project's JAR is used. Putting everything into a single JAR makes it harder to see what libraries are
     * being used, but makes it easier for end users to distribute the application.
     * <p/>
     * Note: Files with the same path in different JARs will be overwritten. Files in the project's JAR will never be overwritten,
     * but may overwrite other files.
     *
     * @param pExcludeJARs The names of any JARs to exclude.
     *
     * @return True if the "OneJAR" was created / updated or false if no OneJar is NOT requested for this project or it was not needed.
     */
    public boolean oneJAR( String... pExcludeJARs ) {
        File zOneJarPath = getOneJarPathFile();

        if ( zOneJarPath == null ) {
            return false;
        }

        File zJarPath = getJarPathFile();
        if ( !zJarPath.isFile() ) {
            throw new IllegalStateException( "One JAR: " + this + " requested, BUT NO jar File produced at: " + zJarPath.getPath() );
        }

        if ( zOneJarPath.isFile() && (zOneJarPath.lastModified() >= zJarPath.lastModified()) ) {
            progress( "One JAR: " + this + " NOT Needed!" );
            return false;
        }

        Paths zClasspath = classpath();
        if ( zClasspath.isEmpty() ) {
            progress( "One JAR: " + this + " No supporting Jars!  Simply Copying to: " + zOneJarPath.getPath() );
            copyFile( zJarPath, zOneJarPath );
            return true;
        }
        progress( "One JAR: " + this );

        File zOnejarDir = mkdir( new File( path( "$target$/onejar/" ) ) );

        List<String> zExcludeJARs = Arrays.asList( pExcludeJARs );
        for ( File jarFile : zClasspath.getFiles() ) // All our Class Path (dependant) JARS
        {
            if ( !zExcludeJARs.contains( jarFile.getName() ) ) {
                unzip( jarFile, zOnejarDir );
            }
        }

        unzip( zJarPath, zOnejarDir ); // Our Jar! - Our Manifest will be "the" Manifest !!!!!! Need to remove class PATH!
        innerJar( "'ONE' JAR", zOneJarPath.getPath(), new Paths( zOnejarDir.getPath() ) );
        return true;
    }

    /**
     * Collects the distribution files using the "dist" property, the project's JAR file, and everything on the project's classpath
     * (including dependency project classpaths) and places them into the specified directory. This is also done for depenency projects,
     * recursively. This is everything the application needs to be run from JAR files.
     *
     * @return True if the PhoneGapDir was populated or false if no distribution (App Dir) is requested for this project.
     */
    public boolean phoneGapDir() {
        String zPhoneGapDir = getPhoneGapDirPath();
        if ( zPhoneGapDir == null ) {
            return false;
        }
        Paths zPaths = new Paths( getGWTwarPath(), "**.js", "**.gif" );
        zPaths.add( getDist() );

        File zPhoneGapDirFile = new File( zPhoneGapDir );
        if ( zPhoneGapDirFile.exists() ) {
            if ( zPhoneGapDirFile.lastModified() >= zPaths.getGreatestLastModified() ) {
                progress( "PhoneGapDir: " + this + " NOT Needed!" );
                return false;
            }
            delete( zPhoneGapDirFile );
        }

        progress( "PhoneGapDir: " + this + " -> " + zPhoneGapDir );
        String distDir = mkdir( zPhoneGapDir ); // Give it a new Timestamp
        zPaths.copyTo( distDir );
        return true;
    }

    /**
     * Collects the distribution files using the "dist" property, the project's JAR file, and everything on the project's classpath
     * (including dependency project classpaths) and places them into the specified directory. This is also done for depenency projects,
     * recursively. This is everything the application needs to be run from JAR files.
     *
     * @return True if the AppDir was populated or false if no distribution (App Dir) is requested for this project.
     */
    public boolean appDir() {
        String zAppDir = getAppDirPath();
        if ( zAppDir == null ) {
            return false;
        }
        File zJarPath = getJarPathFile();
        if ( !zJarPath.isFile() ) {
            progress( "AppDir: " + this + " BUT NO jar File produced at: " + zJarPath.getPath() );
            return false;
        }
        Paths zPaths = new Paths();
        addDependantProjectsDistPaths( zPaths );
        zPaths.add( classpath() );
        zPaths.add( FilePath.canonicalize( getJarPathFile() ) );

        File zAppDirFile = new File( zAppDir );
        if ( zAppDirFile.exists() ) {
            if ( zAppDirFile.lastModified() >= zPaths.getGreatestLastModified() ) {
                progress( "AppDir: " + this + " NOT Needed!" );
                return false;
            }
            delete( zAppDirFile );
        }

        progress( "AppDir: " + this + " -> " + zAppDir );
        String distDir = mkdir( zAppDir ); // Give it a new Timestamp
        zPaths.copyTo( distDir );
        return true;
    }

    /**
     * Produce either a 'war' directory or a '.war' file, in theory ready to deploy to a servlet/web container.
     *
     * @return true if the 'war' was created.
     */
    public boolean war() {
        String zWar = getWar();
        if ( zWar == null ) {
            return false;
        }
        File zJarPath = getJarPathFile();
        if ( !zJarPath.isFile() ) {
            progress( "WAR: " + this + " BUT NO jar File produced at: " + zJarPath.getPath() );
            return false;
        }

        Paths zDistPaths = new Paths();
        addDependantProjectsDistPaths( zDistPaths );
        if ( null != getGWT() ) {
            zDistPaths.add( new Paths( getGWTwarPath() ) );
        }

        Paths zClassPath = new Paths();
        zClassPath.add( FilePath.canonical( getGWTatDir(), GWT_SERVLET ) );
        zClassPath.add( classpath() );
        zClassPath.add( FilePath.canonicalize( getJarPathFile() ) );

        File zWarPathFile = getWarPathFile();
        if ( zWarPathFile.exists() ) {
            long zWarLastModified = zWarPathFile.lastModified();
            if ( (zWarLastModified >= zClassPath.getGreatestLastModified()) && (zWarLastModified >= zDistPaths.getGreatestLastModified()) ) {
                progress( "WAR: " + this + " NOT Needed!" );
                return false;
            }
            delete( zWarPathFile );
        }

        boolean zWarIt = zWar.endsWith( ".war" );

        File zWarDir = zWarPathFile;
        if ( zWarIt ) {
            zWarDir = new File( path( "$target$/war/" ) );
            delete( zWarDir );
        }

        progress( "WAR: " + this + " -> " + zWarDir.getPath() );

        File zWarDirLibPath = new File( zWarDir, "WEB-INF/lib" );
        mkdir( zWarDirLibPath );

        zDistPaths.copyTo( zWarDir.getPath() );
        zClassPath.copyTo( zWarDirLibPath.getPath() );

        if ( zWarIt ) {
            innerJar( "WAR", zWarPathFile.getPath(), new Paths( zWarDir.getPath() ) );
        }
        return true;
    }

    /**
     * Computes the classpath for all the dependencies of the specified project, recursively.
     */
    protected void addDependantProjectsDistPaths( Paths pPathsToAddTo ) {
        for ( Project zProject : mDependantProjects ) {
            zProject.addDependantProjectsDistPaths( pPathsToAddTo );
        }
        pPathsToAddTo.add( getDist() );
    }

    protected boolean GWTcompileIt() {
        Utils.shell( new ShellArgs()
                             .add( getPathJavaJRE() )
                             .add( "-Xmx" + getGWTmx() )
                             .add( "-cp", buildGWTcompileClassPath() )
                             .add( "com.google.gwt.dev.Compiler" )
                             .add( getGWTcompileReport() )
                             .add( "-logLevel", getGWTlogging() )
                             .add( "-war", getGWTwarPath() )
                             .add( "-style", getGWTstyle() )
                             .add( getGWT() )
                             .toArray() );
        return true;
    }

    private String buildGWTcompileClassPath() {
        Paths zGWTclassPath = new Paths();
        File zGWTatDir = getGWTatDir();
        zGWTclassPath.add( FilePath.canonical( zGWTatDir, GWT_DEV ) );
        zGWTclassPath.add( FilePath.canonical( zGWTatDir, GWT_USER ) );
        zGWTclassPath.add( FilePath.canonical( zGWTatDir, GWT_VALIDATION ) );
        zGWTclassPath.add( FilePath.canonical( zGWTatDir, GWT_VALIDATION_SOURCE ) );
        if ( mSources ) {
            zGWTclassPath.add( FilePath.canonicalize( getJarPathFile() ) );
        }
        zGWTclassPath.add( classpath() );
        return zGWTclassPath.toString( File.pathSeparator );
    }

    protected String getPathJavaJRE() {
        File zJavaHomeDir = assertIsDirectory( JAVA_HOME, new File( assertNotEmpty( JAVA_HOME, System.getenv( JAVA_HOME ) ) ) );
        File zJavaDir = new File( zJavaHomeDir, "jre/bin" );
        if ( !zJavaDir.isDirectory() ) {
            if ( !(zJavaDir = new File( zJavaHomeDir, "bin" )).isDirectory() ) {
                throw new IllegalStateException( "Unable to find JAVA_HOME bin directory under: " + zJavaHomeDir );
            }
        }
        File zJavaExecutable = new File( zJavaDir, isWindows ? "java.exe" : "java" );
        if ( zJavaExecutable.isFile() ) {
            return getCanonicalFile( zJavaExecutable ).getPath();
        }
        throw new IllegalStateException( "Unable to find JAVA_HOME based executable at: " + zJavaExecutable );
    }

    protected File getGeneratedGWT_nocache_jsFile() {
        String zGWTxmlRelativeFilePath = getGWT().replace( '.', '/' ) + ".gwt.xml"; // e.g. org.litesoft.sandbox.csapp.CSapp
        File zFound = getGeneratedGWT_nocache_jsFile( zGWTxmlRelativeFilePath, getSource() );
        if ( zFound == null ) {
            if ( null == (zFound = getGeneratedGWT_nocache_jsFile( zGWTxmlRelativeFilePath, getResources() )) ) {
                throw new IllegalArgumentException( "Unable to locate GWT module file: " + getGWT() );
            }
        }
        return zFound;
    }

    private File getGeneratedGWT_nocache_jsFile( String pGWTxmlRelativeFilePath, Paths pPaths ) {
        RootedPaths[] zRootedPaths = pPaths.getRootedPaths();
        for ( RootedPaths zPath : zRootedPaths ) {
            File zFile = new File( zPath.getCanonicalRootDirectory(), pGWTxmlRelativeFilePath );
            if ( zFile.isFile() ) {
                String moduleName = extractModuleNameFrom( getGWT(), fileContents( zFile ) );
                return new File( getGWTwarPath(), moduleName + "/" + moduleName + ".nocache.js" );
            }
        }
        return null;
    }

    private String extractModuleNameFrom( String pGWTmoduleReference, String pGWTmoduleFileContents ) {
        int at = pGWTmoduleFileContents.indexOf( " rename-to" );
        if ( at != -1 ) // . . . . . . . . . . . .01234567890
        {
            int upTo = pGWTmoduleFileContents.indexOf( '>', at += 10 );
            if ( upTo != -1 ) {
                String stuff = pGWTmoduleFileContents.substring( at, upTo ).trim();
                if ( stuff.startsWith( "=" ) ) {
                    if ( (stuff = stuff.substring( 1 ).trim()).length() > 2 ) {
                        char c = stuff.charAt( 0 );
                        if ( (c == '"') || (c == '\'') ) {
                            if ( -1 != (at = stuff.indexOf( c, 1 )) ) {
                                return stuff.substring( 1, at );
                            }
                        }
                    }
                }
            }
        }
        String s = "." + pGWTmoduleReference;
        return s.substring( s.lastIndexOf( '.' ) + 1 );
    }

    protected boolean needToCompileGWT() {
        File zGeneratedGWT_nocache_jsFile = getGeneratedGWT_nocache_jsFile();
        return needToBuild( ((zGeneratedGWT_nocache_jsFile != null) && zGeneratedGWT_nocache_jsFile.isFile()) ?
                            zGeneratedGWT_nocache_jsFile.lastModified() : forceBuildLastModified() );
    }

    public boolean GWTcompile() {
        String zGWT = getGWT();
        if ( zGWT == null ) {
            return false;
        }
        if ( !needToCompileGWT() ) {
            progress( "GWT Compile: " + this + " NOT Needed!" );
            return false;
        }
        progress( "GWT Compile: " + this );
        return GWTcompileIt();
    }

    /**
     * Assert that this project is currently a 'Versioned' GWT project, and then rev the version number by 1
     */
    public void versionGWT() {
        File zWarWebXmlFile = new File( mCanonicalProjectDir, "war/WEB-INF/web.xml" );
        String zWarWebXml = fileContents( assertIsFile( "web.xml", zWarWebXmlFile ) );

        int zCurVersion = extractVersionFromUrlPattern( zWarWebXml );

        String zWarResourceRelativePathCurrent = "warResources/v" + zCurVersion;

        File zIndexHtmlFile = new File( mCanonicalProjectDir, zWarResourceRelativePathCurrent + "/index.html" );
        String zIndexHtml = assertVersionedIndexHtml( zIndexHtmlFile, zCurVersion );

        List<File> zVersionedGwtXmlFiles = findVersionedGwtXmlFiles( zCurVersion );

        int zNewVersion = zCurVersion + 1;

        String zWarResourceRelativePathNew = "warResources/v" + zNewVersion;
        if ( new File( mCanonicalProjectDir, zWarResourceRelativePathNew ).exists() ) {
            throw new IllegalStateException( "Project already contains a 'warResources/v" + zNewVersion + "' directory?" );
        }

        progress( "versionGWT: " + this + " | " + zCurVersion + " -> " + (zCurVersion + 1) );
        progress( "    " + zWarWebXmlFile.getPath() );
        progress( "    " + zIndexHtmlFile.getPath() );
        for ( File zFile : zVersionedGwtXmlFiles ) {
            progress( "    " + zFile.getPath() );
        }
        progress( "    " + zWarResourceRelativePathCurrent + " -> " + zWarResourceRelativePathNew );

        new Paths( zWarResourceRelativePathCurrent ).copyTo( zWarResourceRelativePathNew );

        updateFileContents( new File( mCanonicalProjectDir, zWarResourceRelativePathNew + "/index.html" ),
                            updateVersionedIndexHtml( zIndexHtml, zCurVersion, zNewVersion ) );

        updateFileContents( zWarWebXmlFile, updateVersionedWebXml( zWarWebXml, zCurVersion, zNewVersion ) );

        for ( File zFile : zVersionedGwtXmlFiles ) {
            updateFileContents( zFile, updateVersionedGwtXmlFile( fileContents( zFile ), zCurVersion, zNewVersion ) );
        }
        // Update/Create the Current Version's redirect JavaScript file
        String zCurPathVersion = "/v" + zCurVersion;
        String redirectScript = "var loc = window.location.href;\n" + //
                                "var at = loc.indexOf( '" + zCurPathVersion + "' );\n" + //
                                "window.location.href = loc.substring(0, at) + '/v" + zNewVersion + "' + loc.substring(at + " + zCurPathVersion.length() + ");\n";
        updateFileContents( new File( mCanonicalProjectDir, zWarResourceRelativePathCurrent + "/v" + zCurVersion + ".nocache.js" ), redirectScript );

        // Update the "root" html (if it exists)
        File zRootHtmlFile = new File( mCanonicalProjectDir, "warResources/index.html" );
        if ( zRootHtmlFile.isFile() ) {
            updateFileContents( zRootHtmlFile, updateRootHTML( fileContents( zRootHtmlFile ), zCurVersion, zNewVersion ) );
        }
    }

    protected String updateRootHTML( String pFileContents, int pCurVersion, int pNewVersion ) {
        // <!DOCTYPE html>
        // <html>
        //     <head>
        //         <meta http-equiv="Refresh" content="1; url=v1/">
        //     </head>
        //     <body>
        //         <script>window.location.href = 'v1/';</script>
        //     </body>
        // </html>
        String zCurPathVersion = "v" + pCurVersion + "/";
        String zNewPathVersion = "v" + pNewVersion + "/";
        for ( int at; -1 != (at = pFileContents.indexOf( zCurPathVersion )); ) {
            pFileContents = pFileContents.substring( 0, at ) + zNewPathVersion + pFileContents.substring( at + zCurPathVersion.length() );
        }
        return pFileContents;
    }

    protected String updateVersionedGwtXmlFile( String pFileContents, int pCurVersion, int pNewVersion ) {
        String zCurVersionedModule = VERSIONED_MODULE_PREFIX + pCurVersion + VERSIONED_MODULE_SUFFIX;
        String zNewVersionedModule = VERSIONED_MODULE_PREFIX + pNewVersion + VERSIONED_MODULE_SUFFIX;
        int at = pFileContents.indexOf( zCurVersionedModule );
        return pFileContents.substring( 0, at ) + zNewVersionedModule + pFileContents.substring( at + zCurVersionedModule.length() );
    }

    protected List<File> findVersionedGwtXmlFiles( int pVersion ) {
        String zVersionedModule = VERSIONED_MODULE_PREFIX + pVersion + VERSIONED_MODULE_SUFFIX;

        ArrayList<File> zVersionedFiles = new ArrayList<File>();

        String zSourceString = get( SOURCE.getName() ) + "|";
        Paths zGwtXml = new Paths( zSourceString.substring( 0, zSourceString.indexOf( '|' ) ), "**.gwt.xml" );
        for ( File zFile : zGwtXml.getFiles() ) {
            if ( fileContents( zFile ).contains( zVersionedModule ) ) {
                zVersionedFiles.add( zFile );
            }
        }
        if ( zVersionedFiles.isEmpty() ) {
            throw new IllegalStateException(
                    "Project does not appear to contain a 'gwt.xml' file with the current version module definition of: " + zVersionedModule );
        }
        return zVersionedFiles;
    }

    protected String updateVersionedIndexHtml( String pFileContents, int pCurVersion, int pNewVersion ) {
        String zCurVersionedScript = VERSIONED_SCRIPT_PREFIX + pCurVersion + VERSIONED_SCRIPT_SUFFIX;
        String zNewVersionedScript = VERSIONED_SCRIPT_PREFIX + pNewVersion + VERSIONED_SCRIPT_SUFFIX;
        int at = pFileContents.indexOf( zCurVersionedScript );
        return pFileContents.substring( 0, at ) + zNewVersionedScript + pFileContents.substring( at + zCurVersionedScript.length() );
    }

    protected String assertVersionedIndexHtml( File pIndexHtmlFile, int pVersion ) {
        String zVersionedScript = VERSIONED_SCRIPT_PREFIX + pVersion + VERSIONED_SCRIPT_SUFFIX;

        String zContents = fileContents( assertIsFile( "Versioned index.html", pIndexHtmlFile ) );
        if ( !zContents.contains( zVersionedScript ) ) {
            throw new IllegalStateException(
                    "Project's current versioned index.html file (" + pIndexHtmlFile.getPath() + ") does not contain a 'versioned' script element of: " +
                    zVersionedScript );
        }
        return zContents;
    }

    protected String updateVersionedWebXml( String pFileContents, int pCurVersion, int pNewVersion ) {
        String zCurVersionedUrlPattern = VERSIONED_URL_PATTERN_PREFIX + pCurVersion + "/";
        String zNewVersionedUrlPattern = VERSIONED_URL_PATTERN_PREFIX + pNewVersion + "/";
        for ( int at; -1 != (at = pFileContents.indexOf( zCurVersionedUrlPattern )); ) {
            pFileContents = pFileContents.substring( 0, at ) + zNewVersionedUrlPattern + pFileContents.substring( at + zCurVersionedUrlPattern.length() );
        }
        return pFileContents;
    }

    protected int extractVersionFromUrlPattern( String pWarWebXml ) {
        for ( int at, from = 0; -1 != (at = pWarWebXml.indexOf( VERSIONED_URL_PATTERN_PREFIX, from )); from = at + 1 ) {
            int slashAt = pWarWebXml.indexOf( '/', at += VERSIONED_URL_PATTERN_PREFIX.length() );
            if ( slashAt > 0 ) {
                try {
                    return Integer.parseInt( pWarWebXml.substring( at, slashAt ) );
                }
                catch ( NumberFormatException acceptable ) {
                    // path starts w/ a 'v' but is not of pattern "v####"
                }
            }
        }
        throw new IllegalStateException( "Project's war/WEB-INF/web.xml does not appear to contain a 'versioned' <url-pattern>." );
    }

    /**
     * Executes the buildDependencies, clean, compile, jar, [GWTcompile], and then "packageIt" utility methods.
     */
    public synchronized boolean build() {
        if ( mBuilt ) {
            return false;
        }
        mBuilt = true;
        mSources = !getSource().isEmpty();
        boolean zAnythingBuilt = false;
        boolean zBuildIt;
        try {
            zBuildIt = buildDependencies() || needToBuild();
        }
        catch ( RuntimeException e ) {
            progress( "Build: " + this );
            throw e;
        }
        if ( !zBuildIt ) {
            progress( "Build: " + this + " NOT Needed!" );
        } else {
            progress( "Build: " + this );
            clean();
            if ( mSources ) {
                compile();
                jar();
                zAnythingBuilt = true;
            }
        }
        zAnythingBuilt |= GWTcompile();
        zAnythingBuilt |= packageIt();
        return zAnythingBuilt;
    }

    protected boolean needToBuild() {
        return needToBuild( determineOutputLastModified() );
    }

    protected boolean needToBuild( long pOutputLastModified ) {
        return (mProjectFileLastModified > pOutputLastModified) || //
               checkNewer( pOutputLastModified, "ClassPath", compileClasspath() ) || //
               checkNewer( pOutputLastModified, "Source", getSource() ) || //
               checkNewer( pOutputLastModified, "Resources", getResources() ) || //
               checkNewer( pOutputLastModified, "Dist", getDist() );
    }

    protected boolean checkNewer( long pOutputLastModified, String pWhat, Paths pPaths ) {
        Long zLastModified = pPaths.getGreatestLastModified();
        if ( (zLastModified != null) && (zLastModified > pOutputLastModified) ) {
            System.out.println( this + ": " + pWhat + " - " + new NewerBy( pOutputLastModified, zLastModified ) );
            return true;
        }
        return false;
    }

    protected long forceBuildLastModified() {
        return (mProjectFileLastModified - 1);
    }

    protected long determineOutputLastModified() {
        if ( mSources ) {
            File zJarFile = getJarPathFile();
            if ( zJarFile.isFile() ) {
                return zJarFile.lastModified();
            }
        } else {
            String zPhoneGapDir = getPhoneGapDirPath();
            if ( zPhoneGapDir != null ) {
                File zPhoneGapDirFile = new File( zPhoneGapDir );
                if ( zPhoneGapDirFile.isDirectory() ) {
                    return zPhoneGapDirFile.lastModified();
                }
            }
        }
        return forceBuildLastModified();
    }

    /**
     * Deletes the "target" directory and all files and directories under it.
     */
    public void clean() {
        progress( "Clean: " + this );
        packageClean();
        delete( getGWTwarPath() );
        delete( getJarPath() );
        delete( getTargetPath() );
    }

    /**
     * Collects the source files using the "source" property and compiles them into a "classes" directory under the target
     * directory. It uses "classpath" and "dependencies" to find the libraries required to compile the source.
     * <p/>
     * Note: Each dependency project is not built automatically. Each needs to be built before the dependent project.
     *
     * @return The path to the "classes" directory or null if there was no sources to compile
     */
    public String compile() {
        Paths source = getSource();
        if ( source.isEmpty() ) {
            return null;
        }
        Paths classpath = compileClasspath();

        String classesDir = mkdir( path( "$target$/classes/" ) );

        String zMessage = "Compile: " + this;
        if ( LOGGER.debug.isEnabled() ) {
            zMessage += " | " + source.count() + " source files";
            if ( !classpath.isEmpty() ) {
                zMessage += "\n         Classpath: " + classpath;
            }
        }
        progress( zMessage );

        List<String> zCompileArgs = createCompileJavaArgs( classpath, source, classesDir );

        compileJava( classpath, source, zCompileArgs );

        return classesDir;
    }

    protected List<String> createCompileJavaArgs( Paths pClasspath, Paths pSource, String pClassesDir ) {
        List<String> args = new ArrayList<String>();
        if ( LOGGER.trace.isEnabled() ) {
            args.add( "-verbose" );
        }
        args.add( "-d" );
        args.add( pClassesDir );
        args.add( "-g:source,lines" );
        args.add( "-source" );
        args.add( getSourceJavaVersion() );
        args.addAll( pSource.getFullPaths() );
        if ( !pClasspath.isEmpty() ) {
            args.add( "-classpath" );
            args.add( pClasspath.toString( File.pathSeparator ) );
        }
        return args;
    }

    protected void compileJava( Paths pClasspath, Paths pSource, List<String> pCompileArgs ) {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

        if ( compiler == null ) {
            throw new RuntimeException( "No compiler available. Ensure you are running from a " + getTargetJavaVersion() +
                                        "+ JDK, and not a JRE *and* that your class path includes tools.jar." );
        }
        int zError = compiler.run( getCompile_in(), getCompile_out(), getCompile_err(), pCompileArgs.toArray( new String[pCompileArgs.size()] ) );
        if ( zError != 0 ) {
            String zMessage = "Error (" + zError + ") during compilation of project: " + this +
                              "\nSource: " + pSource.count() + " files\nCompilerArgs: " + pCompileArgs;
            if ( LOGGER.debug.isEnabled() ) {
                zMessage += "\nClasspath: " + pClasspath + "\nSource: " + pSource.toString( " " );
            }
            throw new RuntimeException( zMessage );
        }
        try {
            Thread.sleep( 100 );
        }
        catch ( InterruptedException ex ) {
            // Whatever
        }
    }

    protected InputStream getCompile_in() {
        return null;
    }

    protected OutputStream getCompile_out() {
        return null;
    }

    protected OutputStream getCompile_err() {
        return new OutputStream() {
            private StringBuilder mBuffer = new StringBuilder();
            private boolean mLastWasCRtreatedAsLF = false;

            private void dumpLine( int pByte ) {
                if ( pByte == 13 ) {
                    mLastWasCRtreatedAsLF = true;
                    pByte = 10;
                } else {
                    boolean zLastWasCRtreatedAsLF = mLastWasCRtreatedAsLF;
                    mLastWasCRtreatedAsLF = false;
                    if ( (pByte == 10) && zLastWasCRtreatedAsLF ) {
                        return;
                    }
                }
                mBuffer.append( (char) pByte ); // Assuming Ascii!
                String line = mBuffer.toString();
                mBuffer = new StringBuilder();
                if ( !line.startsWith( "Note: " ) ) {
                    System.err.print( line );
                }
            }

            @Override
            public void write( int pByte ) // Not a Unicode character, just a BYTE!  --- Asumming Ascii ---
                    throws IOException {
                if ( (10 <= pByte) && (pByte <= 13) ) // New Line Indicator
                {                                        // LF: Line Feed, U+000A
                    dumpLine( pByte );                   // VT: Vertical Tab, U+000B
                    return;                              // FF: Form Feed, U+000C
                }                                        // CR: Carriage Return, U+000D
                mBuffer.append( (char) pByte ); // Assuming Ascii!
            }
        };
    }

    /**
     * Collects the class files from the "classes" directory and all the resource files using the "resources" property and encodes
     * them into a JAR file.
     * <p/>
     * If the resources don't contain a META-INF/MANIFEST.MF file, one is generated. If the project has a main property, the
     * generated manifest will include "Main-Class" and "Class-Path" entries to allow the main class to be run with "java -jar".
     *
     * @return The path to the created JAR file or null if No JAR created.
     */
    public String jar() {
        String zJarPath = getJarPath();

        Paths zClasses = new Paths( path( "$target$/classes/" ), "**.class" );
        Paths zResources = getResources();
        if ( zClasses.isEmpty() && zResources.isEmpty() ) {
            delete( zJarPath );
            return null;
        }
        progress( "JAR: " + this + " -> " + zJarPath );

        String jarDir = mkdir( path( "$target$/jar/" ) );

        zClasses.copyTo( jarDir );
        zResources.copyTo( jarDir );

        File manifestFile = new File( jarDir, "META-INF/MANIFEST.MF" );
        if ( !manifestFile.exists() ) {
            createDefaultManifestFile( zJarPath, manifestFile );
        }

        return jar( zJarPath, new Paths( jarDir ) );
    }

    protected void createDefaultManifestFile( String pJarFile, File pManifestFile ) {
        LOGGER.debug.log( "Generating JAR manifest: ", pManifestFile );
        mkdir( pManifestFile.getParent() );
        Manifest manifest = new Manifest();
        manifest.getMainAttributes().putValue( Attributes.Name.MANIFEST_VERSION.toString(), "1.0" );
        if ( hasMain() ) {
            LOGGER.debug.log( "Main class: ", getMain() );
            manifest.getMainAttributes().putValue( Attributes.Name.MAIN_CLASS.toString(), getMain() );
            StringBuilder buffer = new StringBuilder( 512 );
            buffer.append( Utils.fileName( pJarFile ) );
            buffer.append( " ." );
            Paths classpath = classpath();
            for ( String name : classpath.getRelativePaths( pJarFile ) ) {
                buffer.append( ' ' );
                buffer.append( name );
            }
            manifest.getMainAttributes().putValue( Attributes.Name.CLASS_PATH.toString(), buffer.toString() );
        }
        OutputStream output = createFileOutputStream( pManifestFile );
        try {
            manifest.write( output );
            Closeable zCloseable = output;
            output = null;
            close( zCloseable );
        }
        catch ( IOException e ) {
            throw new WrappedIOException( e );
        }
        finally {
            dispose( output );
        }
    }

    /**
     * Encodes the specified paths into a JAR file.
     *
     * @return The path to the JAR file.
     */
    public String jar( String jarFile, Paths paths ) {
        return innerJar( "JAR", jarFile, paths );
    }

    /**
     * Encodes the specified paths into a JAR/WAR file.
     *
     * @return The path to the JAR/WAR file.
     */
    protected String innerJar( String pType, String jarFile, Paths paths ) {
        Util.assertNotNull( "jarFile", jarFile );
        Util.assertNotNull( "paths", paths );

        progress( "Creating " + pType + " (" + paths.count() + " entries): " + jarFile );

        int zZipped = paths.zip( jarFile, new ZipFactory() {
            @Override
            public ZipOutputStream createZOS( String pFilePath, List<FilePath> pPaths ) {
                putManifestFirst( pPaths );
                try {
                    return new JarOutputStream( FileUtil.createBufferedFileOutputStream( pFilePath ) );
                }
                catch ( IOException e ) {
                    throw new WrappedIOException( e );
                }
            }

            @Override
            public ZipEntry createZE( String pRelativePath ) {
                return new JarEntry( pRelativePath );
            }

            private void putManifestFirst( List<FilePath> pPaths ) {
                int at = findManifest( pPaths );
                if ( at > 0 ) {
                    FilePath zManifest = pPaths.remove( at );
                    pPaths.add( 0, zManifest );
                }
            }

            private int findManifest( List<FilePath> pPaths ) {
                for ( int i = 0; i < pPaths.size(); i++ ) {
                    if ( META_INF_MANIFEST_MF.equals( pPaths.get( i ).getFileSubPath() ) ) {
                        return i;
                    }
                }
                return -1;
            }
        } );
        return zZipped == 0 ? null : jarFile;
    }

    /**
     * Decodes the specified ZIP file.
     *
     * @return The path to the output directory.
     */
    protected void quiteUnzip( File zipFile, File outputDir ) {
        ZipInputStream input = new ZipInputStream( createFileInputStream( zipFile ) );
        try {
            for ( ZipEntry entry; null != (entry = input.getNextEntry()); ) {
                File file = new File( outputDir, entry.getName() );
                if ( entry.isDirectory() ) {
                    mkdir( file.getPath() );
                    continue;
                }
                writeStream( input, createFileOutputStream( file ) );
            }
        }
        catch ( IOException e ) {
            throw new WrappedIOException( e );
        }
        finally {
            dispose( input );
        }
    }

    /**
     * Decodes the specified ZIP file.
     */
    public void unzip( File zipFile, File outputDir ) {
        Util.assertNotNull( "zipFile", zipFile );
        Util.assertNotNull( "outputDir", outputDir );
        progress( "ZIP decoding: " + zipFile.getPath() + " -> " + outputDir.getPath() );
        quiteUnzip( zipFile, outputDir );
    }

    /**
     * Decodes the specified ZIP file.
     *
     * @return The path to the output directory.
     */
    public String unzip( String zipFile, String outputDir ) {
        zipFile = assertNotEmpty( "zipFile", zipFile );
        outputDir = assertNotEmpty( "outputDir", outputDir );
        progress( "ZIP decoding: " + zipFile + " -> " + outputDir );
        quiteUnzip( new File( zipFile ), new File( outputDir ) );
        return outputDir;
    }

    /**
     * Computes the classpath for the specified project and all its dependency projects, recursively.
     */
    protected Paths compileClasspath() {
        Paths classpath = getCompileClasspath();
        classpath.add( getClasspath() );
        for ( Project zProject : mDependantProjects ) {
            zProject.addDependantProjectsCompileClassPaths( classpath );
        }
        return classpath;
    }

    /**
     * Computes the classpath for all the dependencies of the specified project, recursively.
     */
    protected void addDependantProjectsCompileClassPaths( Paths pPathsToAddTo ) {
        addDependentProjectJar( pPathsToAddTo );
        pPathsToAddTo.add( compileClasspath() );
    }

    /**
     * Computes the classpath for the specified project and all its dependency projects, recursively.
     */
    protected Paths classpath() {
        Paths classpath = getClasspath();
        for ( Project zProject : mDependantProjects ) {
            zProject.addDependantProjectsClassPaths( classpath );
        }
        return classpath;
    }

    /**
     * Computes the classpath for all the dependencies of the specified project, recursively.
     */
    protected void addDependantProjectsClassPaths( Paths pPathsToAddTo ) {
        addDependentProjectJar( pPathsToAddTo );
        pPathsToAddTo.add( classpath() );
    }

    protected void addDependentProjectJar( Paths pPathsToAddTo ) {
        if ( mSources ) {
            File zJarFile = getJarPathFile();
            if ( !zJarFile.isFile() ) {
                throw new RuntimeException( "Dependency (" + this + ") Jar not found, not built?" );
            }
            pPathsToAddTo.add( new FilePath( zJarFile.getParentFile(), zJarFile.getName() ) );
        }
    }

    /**
     * Calls {@link #build(Project)} for each dependency project in the specified project.
     */
    public boolean buildDependencies() {
        boolean anyBuilt = false;
        for ( Project zProject : mDependantProjects ) {
            anyBuilt |= zProject.build();
        }
        return anyBuilt;
    }

    public void set( Object key, Object object ) {
        mManager.put( validateSetableKey( key ), object );
    }

    public void remove( Object key ) {
        set( key, null );
    }

    private Object validateSetableKey( Object pKey ) {
        if ( pKey instanceof String ) {
            String zStrKey = noEmpty( pKey.toString().toLowerCase() );
            if ( Parameter.reservedNames().contains( zStrKey ) ) {
                throw new IllegalArgumentException( zStrKey + " not updatable!" );
            }
            pKey = zStrKey;
        }
        Util.assertNotNull( "key", pKey );
        return pKey;
    }

    public synchronized void initialize( ProjectFactory pProjectFactory ) {
        List<String> zDependencies = getDependencies();
        if ( zDependencies != null ) {
            for ( String zDependency : zDependencies ) {
                mDependantProjects.add( pProjectFactory.project( mCanonicalProjectDir, zDependency ) );
            }
        }

//        Project defaults = new Project();
//
//        File file = new File( canonical( pPath ) );
//        if ( file.isDirectory() )
//        {
//            String name = file.getName();
//            defaults.set( "name", name );
//            defaults.set( "target", file.getParent() + "/target/" + name + "/" );
//        }
//        else
//        {
//            String name = file.getParentFile().getName();
//            defaults.set( "name", name );
//            defaults.set( "target", file.getParentFile().getParent() + "/target/" + name + "/" );
//        }
//        defaults.set( "classpath", "lib|**/*.jar" );
//        defaults.set( "dist", "dist" );
//
//        List<String> source = new ArrayList<String>();
//        source.add( "src|**/*.java" );
//        source.add( "src/main/java|**/*.java" );
//        defaults.set( "source", source );
//
//        List<String> resources = new ArrayList<String>();
//        resources.add( "resources" );
//        resources.add( "src/main/resources" );
//        defaults.set( "resources", resources );
//
//        Project project = project( pPath, defaults );
//
//        // Remove dependency if a JAR of the same name is on the classpath.
//        Paths classpath = project.getPaths( "classpath" );
//        classpath.add( dependencyClasspaths( project, classpath, false, false ) );
//        for ( String dependency : project.getDependencies() )
//        {
//            String dependencyName = project( project.path( dependency ) ).getName();
//            for ( String classpathFile : classpath )
//            {
//                String name = fileWithoutExtension( classpathFile );
//                int dashIndex = name.lastIndexOf( '-' );
//                if ( dashIndex != -1 )
//                {
//                    name = name.substring( 0, dashIndex );
//                }
//                if ( name.equals( dependencyName ) )
//                {
//                    if ( DEBUG )
//                    {
//                        debug( "Ignoring " + project + " dependency: " + dependencyName + " (already on classpath: " + classpathFile + ")" );
//                    }
//                    project.remove( "dependencies", dependency );
//                    break;
//                }
//            }
//        }
//
//        if ( TRACE )
//        {
//            trace( "scar", "Project: " + project + "\n" + project );
//        }
//
//        return project;
    }

    protected boolean mBuilt = false;
    protected boolean mSources = false;
    protected List<Project> mDependantProjects = new ArrayList<Project>();
}

Commits for litesoft/trunk/Java/ScarPlus/src/com/esotericsoftware/scar/Project.java

Diff revisions: vs.
Revision Author Commited Message
959 Diff Diff GeorgeS picture GeorgeS Sat 19 Jul, 2014 15:27:50 +0000

Scar update

950 Diff Diff GeorgeS picture GeorgeS Thu 19 Jun, 2014 17:57:04 +0000

New Lines

943 Diff Diff GeorgeS picture GeorgeS Tue 03 Jun, 2014 04:25:50 +0000

Extracting commonfoundation

939 Diff Diff GeorgeS picture GeorgeS Mon 02 Jun, 2014 21:30:31 +0000

Extracting commonfoundation

918 Diff Diff GeorgeS picture GeorgeS Sun 29 Dec, 2013 01:20:18 +0000

Switch from raw warResources to v1 as subdir & update Scar.

905 Diff Diff GeorgeS picture GeorgeS Wed 05 Jun, 2013 23:17:06 +0000

Introduce NewerBy...

904 Diff Diff GeorgeS picture GeorgeS Mon 15 Apr, 2013 23:04:40 +0000

Updated Scar for 1.7 changing “-target 1.6” to "-source 1.6"

889 Diff Diff GeorgeS picture GeorgeS Tue 18 Dec, 2012 00:21:56 +0000

Correct Relative Path for JARing

873 Diff Diff GeorgeS picture GeorgeS Tue 27 Nov, 2012 17:41:11 +0000

!

826 GeorgeS picture GeorgeS Mon 20 Aug, 2012 02:46:37 +0000