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
package com.esotericsoftware.scar;

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

import org.litesoft.logger.*;

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

/**
 * Generic Data structure that contains information needed to perform tasks.
 */
@SuppressWarnings("UnusedDeclaration")
public class Project extends ProjectParameters
{
    protected static final Logger LOGGER = LoggerFactory.getLogger( Project.class );

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

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

    public String getTargetJavaVersion()
    {
        return "1.6";
    }

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

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

    /**
     * Removes an item from a list or map. If the mData under the specified key is a list, the entry equal to the specified value is
     * removed. If the mData under the specified key is a map, the entry with the key specified by value is removed.
     */
    public void remove( Object key, Object value )
    {
        mManager.remove( updatableKey( key ), value );
    }

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

    /**
     * Executes the buildDependencies, clean, compile, jar, and dist utility methods.
     */
    public synchronized boolean build()
    {
        if ( mBuilt )
        {
            return false;
        }
        mBuilt = true;
        if ( !buildDependencies() && !needToBuild() )
        {
            progress( "Build: " + this + " NOT Needed!" );
            return (null != dist());
        }
        progress( "Build: " + this );
        buildIt();
        return true;
    }

    protected boolean needToBuild()
    {
        File zJarFile = new File( path( getJar() ) );
        if ( !zJarFile.isFile() )
        {
            return true;
        }
        long zJarTimestamp = zJarFile.lastModified();
        return checkNewer( zJarTimestamp, classpath() ) || checkNewer( zJarTimestamp, getSource() ) || checkNewer( zJarTimestamp, getResources() );
    }

    protected boolean checkNewer( long pJarTimestamp, Paths pPaths )
    {
        Long zLastModified = pPaths.getGreatestLastModified();
        return (zLastModified != null) && (zLastModified > pJarTimestamp);
    }

    protected void buildIt()
    {
        clean();
        compile();
        jar();
        dist();
    }

    /**
     * Deletes the "target" directory and all files and directories under it.
     */
    public void clean()
    {
        progress( "Clean: " + this );
        deletePath( getAppDir() );
        deletePath( getJar() );
        deletePath( getTarget() );
    }

    /**
     * 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 = classpath();

        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( "-target" );
        args.add( getTargetJavaVersion() );
        args.addAll( pSource.getFullPaths() );
        if ( !pClasspath.isEmpty() )
        {
            args.add( "-classpath" );
            args.add( pClasspath.toString( ";" ) );
        }
        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." );
        }
        int zError = compiler.run( getCompile_in(), getCompile_out(), getCompile_err(), pCompileArgs.toArray( new String[pCompileArgs.size()] ) );
        if ( zError != 0 )
        {
            throw new RuntimeException( "Error (" + zError + ") during compilation of project: " + this + "\nSource: " + pSource.count() + " files\nClasspath: " + pClasspath );
        }
        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 zJarFile = path( getJar() );

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

        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( zJarFile, manifestFile );
        }

        return jar( zJarFile, 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() )
            {
                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 );
        }
    }

    /**
     * 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 a "dist" directory under the "target" directory. This is also
     * done for depenency projects, recursively. This is everything the application needs to be run from JAR files.
     *
     * @return The path to the "dist" directory or null if no distribution (App Dir) is requested for this project.
     */
    public String dist()
    {
        String zAppDir = getAppDir();
        if ( zAppDir == null )
        {
            return null;
        }
        progress( "Dist: " + this );

        if ( !LOGGER.trace.isEnabled() )
        {
            return null; // todo: ...
        }

        String distDir = mkdir( path( "$target$/dist/" ) );
        classpath().copyTo( distDir );
        Paths distPaths = getDist();
        dependencyDistPaths( distPaths );
        distPaths.copyTo( distDir );
        new Paths( path( "$target$" ), "*.jar" ).copyTo( distDir );
        return distDir;
    }

    private Paths dependencyDistPaths( Paths paths )
    {
        for ( String dependency : getDependencies() )
        {
            Project dependencyProject = null; // todo: project( null, path( dependency ) );
            String dependencyTarget = dependencyProject.path( "$target$/" );
            if ( !Utils.fileExists( dependencyTarget ) )
            {
                throw new RuntimeException( "Dependency has not been built: " + dependency );
            }
            paths.glob( dependencyTarget + "dist", "!*/**.jar" );
            paths.add( dependencyDistPaths( paths ) );
        }
        return paths;
    }

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

        progress( "Creating JAR (" + 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( new BufferedOutputStream( new FileOutputStream( 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;
    }

    /**
     * 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 )
    {
        File zJarFile = new File( path( getJar() ) );
        if ( !zJarFile.isFile() )
        {
            throw new RuntimeException( "Dependency (" + this + ") Jar not found, not built?" );
        }
        pPathsToAddTo.add( new FilePath( zJarFile.getParentFile(), zJarFile.getName() ) );
        pPathsToAddTo.add( classpath() );
    }

    /**
     * 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;
    }

    /**
     * Replaces the Data in this project with the contents of the specified YAML file. If the specified project has Data with the
     * same key as this project, the value is overwritten. Keys in this project that are not in the specified project are not
     * affected.
     */
//    public void replace( Project project )
//    {
//        Util.assertNotNull( "project", project );
//        mData.putAll( project.mData );
//        document = project.document;
//        dir = project.dir;
//    }
    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 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
316 Diff Diff GeorgeS picture GeorgeS Tue 19 Jul, 2011 01:02:37 +0000
315 Diff Diff GeorgeS picture GeorgeS Sun 17 Jul, 2011 15:48:36 +0000
314 Diff Diff GeorgeS picture GeorgeS Fri 15 Jul, 2011 01:01:49 +0000
308 Diff Diff GeorgeS picture GeorgeS Sun 10 Jul, 2011 23:55:06 +0000
302 Diff Diff GeorgeS picture GeorgeS Fri 08 Jul, 2011 14:08:10 +0000
299 Diff Diff GeorgeS picture GeorgeS Tue 05 Jul, 2011 04:45:50 +0000
298 Diff Diff GeorgeS picture GeorgeS Fri 01 Jul, 2011 00:25:50 +0000
294 Diff Diff GeorgeS picture GeorgeS Fri 24 Jun, 2011 23:44:22 +0000
293 Diff Diff GeorgeS picture GeorgeS Fri 24 Jun, 2011 00:52:20 +0000
291 GeorgeS picture GeorgeS Wed 22 Jun, 2011 00:33:37 +0000