Revision 438

View differences:

branches/modelio3.7.x/assembly.xml
1
<assembly
2
	xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.7.1.09"
3
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4
	xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.7.1.09 http://maven.apache.org/xsd/assembly-1.7.1.09.xsd">
5
	<id>bin</id>
6
	<formats>
7
		<format>zip</format>
8
	</formats>
9
	<includeBaseDirectory>false</includeBaseDirectory>
10
	<fileSets>
11
		<!-- Copy XML resources -->
12
		<fileSet>
13
			<directory>${project.basedir}/src/main/conf</directory>
14
			<outputDirectory>/${project.name}</outputDirectory>
15
			<includes>
16
				<include>**/*.xml</include>
17
			</includes>
18
			<filtered>true</filtered>
19
		</fileSet>
20
		<!-- Copy DataSheet HTML files -->
21
		<fileSet>
22
			<directory>${project.basedir}</directory>
23
			<outputDirectory>/${project.name}</outputDirectory>
24
			<includes>
25
				<include>DataSheet*.html</include>
26
			</includes>
27
			<filtered>true</filtered>
28
		</fileSet>
29
		<!-- Copy other ressources -->
30
		<fileSet>
31
			<directory>${project.basedir}/src/main/conf</directory>
32
			<outputDirectory>/${project.name}</outputDirectory>
33
			<excludes>
34
				<exclude>**/*.xml</exclude>
35
			</excludes>
36
			<filtered>false</filtered>
37
		</fileSet>
38
		<!-- Copy module's jar file -->
39
		<fileSet>
40
			<directory>${project.build.directory}</directory>
41
			<outputDirectory>${project.name}/lib</outputDirectory>
42
			<includes>
43
				<include>${project.artifactId}-${project.version}.jar</include>		
44
			</includes>
45
		</fileSet>
46
		<!-- Copy java dependencies needed by the module -->
47
		<fileSet>
48
			<directory>${project.build.directory}/lib</directory>
49
			<outputDirectory>${project.name}/lib</outputDirectory>
50
			<includes>
51
				<include>*.jar</include>				
52
			</includes>			
53
		</fileSet>
54
	</fileSets>
55
</assembly>
0 56

  
branches/modelio3.7.x/src/main/java/org/modelio/module/javadesigner/ant/AntGenerator.java
1
package org.modelio.module.javadesigner.ant;
2

  
3
import java.io.File;
4
import java.io.FileWriter;
5
import java.io.IOException;
6
import java.util.ArrayList;
7
import java.util.List;
8
import org.modelio.api.module.IModule;
9
import org.modelio.metamodel.uml.infrastructure.Dependency;
10
import org.modelio.metamodel.uml.infrastructure.ModelElement;
11
import org.modelio.metamodel.uml.infrastructure.ModelTree;
12
import org.modelio.metamodel.uml.statik.Artifact;
13
import org.modelio.metamodel.uml.statik.GeneralClass;
14
import org.modelio.metamodel.uml.statik.Generalization;
15
import org.modelio.metamodel.uml.statik.Manifestation;
16
import org.modelio.metamodel.uml.statik.NameSpace;
17
import org.modelio.metamodel.uml.statik.Operation;
18
import org.modelio.metamodel.uml.statik.Package;
19
import org.modelio.module.javadesigner.api.IJavaDesignerPeerModule;
20
import org.modelio.module.javadesigner.api.JavaDesignerNoteTypes;
21
import org.modelio.module.javadesigner.api.JavaDesignerParameters;
22
import org.modelio.module.javadesigner.api.JavaDesignerStereotypes;
23
import org.modelio.module.javadesigner.api.JavaDesignerTagTypes;
24
import org.modelio.module.javadesigner.dialog.JConsoleWithDialog;
25
import org.modelio.module.javadesigner.impl.JavaDesignerModule;
26
import org.modelio.module.javadesigner.utils.JavaDesignerUtils;
27
import org.modelio.module.javadesigner.utils.ModelUtils;
28

  
29
public class AntGenerator {
30
    private String NL = System.getProperty ("line.separator"); // $NON-NLS-1$
31

  
32
    private IModule module;
33

  
34
    private JConsoleWithDialog console;
35

  
36
    public AntGenerator(final IModule module) {
37
        this(module, new JConsoleWithDialog(null));
38
    }
39

  
40
    public AntGenerator(final IModule module, final JConsoleWithDialog console) {
41
        this.module = module;
42
        this.console = console;
43
    }
44

  
45
    public boolean generateBuildXmlFile(final Artifact jarFile) {
46
        String buildXmlContent;
47
        
48
        buildXmlContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
49
        buildXmlContent += this.NL;
50
        buildXmlContent += createProjectTarget (jarFile);
51
        return saveAntFile (buildXmlContent, JavaDesignerUtils.getAntFileName(jarFile, this.module));
52
    }
53

  
54
    private boolean saveAntFile(final String fileContent, final File targetFile) {
55
        if (!targetFile.getParentFile().exists()) {
56
            targetFile.getParentFile().mkdirs();
57
        }
58
        
59
        try (FileWriter fw = new FileWriter(targetFile)) {
60
            fw.write(fileContent);
61
            this.console.writeInfo("The \"" + targetFile + "\" file was created.\n");
62
            
63
            fw.close();
64
            
65
            return true;
66
        } catch (IOException e) {
67
            // TODO i18n error message
68
            this.console.writeError("An error occured during ant file's saving:\n" + e.getMessage());
69
            JavaDesignerModule.getInstance().getModuleContext().getLogService().error(e);
70
        }
71
        return false;
72
    }
73

  
74
    private String createProjectTarget(final Artifact jarFile) {
75
        String ret = "<project basedir=\".\" name=\"" + jarFile.getName () +
76
        "\" default=\"build\" >" + this.NL;
77
        try {
78
            ret += createConfigs (jarFile);
79
        } catch (Exception e) {
80
            // TODO i18n error message
81
            this.console.writeError("An error occured during configuration's creation:\n" + e.getMessage());
82
            JavaDesignerModule.getInstance().getModuleContext().getLogService().error(e);
83
        }
84
        
85
        try {
86
            ret += createInitTarget (jarFile);
87
        } catch (Exception e) {
88
            // TODO i18n error message
89
            this.console.writeError("An error occured during init target's creation:\n" + e.getMessage());
90
            JavaDesignerModule.getInstance().getModuleContext().getLogService().error(e);
91
        }
92
        
93
        try {
94
            ret += createCleanTarget (jarFile);
95
        } catch (Exception e) {
96
            // TODO i18n error message
97
            this.console.writeError("An error occured during clean target's creation:\n" + e.getMessage());
98
            JavaDesignerModule.getInstance().getModuleContext().getLogService().error(e);
99
        }
100
        
101
        try {
102
            ret += createResourcesTarget (jarFile);
103
        } catch (Exception e) {
104
            // TODO i18n error message
105
            this.console.writeError("An error occured during resource target's creation:\n" + e.getMessage());
106
            JavaDesignerModule.getInstance().getModuleContext().getLogService().error(e);
107
        }
108
        
109
        try {
110
            ret += createBuildTarget (jarFile);
111
        } catch (Exception e) {
112
            // TODO i18n error message
113
            this.console.writeError("An error occured during build target's creation:\n" + e.getMessage());
114
            JavaDesignerModule.getInstance().getModuleContext().getLogService().error(e);
115
        }
116
        
117
        try {
118
            ret += createJarTarget (jarFile);
119
        } catch (Exception e) {
120
            // TODO i18n error message
121
            this.console.writeError("An error occured during archive target's creation:\n" + e.getMessage());
122
            JavaDesignerModule.getInstance().getModuleContext().getLogService().error(e);
123
        }
124
        
125
        try {
126
            ret += createRMITarget (jarFile);
127
        } catch (Exception e) {
128
            // TODO i18n error message
129
            this.console.writeError("An error occured during RMI target's creation:\n" + e.getMessage());
130
            JavaDesignerModule.getInstance().getModuleContext().getLogService().error(e);
131
        }
132
        
133
        if (isUseJavah ()) {
134
            try {
135
                // Do not generate javah target when no native classes are found
136
                List<GeneralClass> natives = getNativeClasses (jarFile);
137
                if (natives.size() > 0) {
138
                    ret += createJavahTarget (jarFile, natives) + this.NL;
139
                }
140
            } catch (Exception e) {
141
                // TODO i18n error message
142
                this.console.writeError("An error occured during javah target's creation:\n" + e.getMessage());
143
                JavaDesignerModule.getInstance().getModuleContext().getLogService().error(e);
144
            }
145
        }
146
        
147
        try {
148
            ret += createPersonnalTarget (jarFile);
149
        } catch (Exception e) {
150
            // TODO i18n error message
151
            this.console.writeError("An error occured during custom target's creation:\n" + e.getMessage());
152
            JavaDesignerModule.getInstance().getModuleContext().getLogService().error(e);
153
        }
154
        
155
        ret += "</project>";
156
        ret += this.NL;
157
        return ret;
158
    }
159

  
160
    private String createPersonnalTarget(final Artifact jarFile) {
161
        String perso = jarFile.getNoteContent (IJavaDesignerPeerModule.MODULE_NAME, JavaDesignerNoteTypes.JARFILE_ANTTARGET);
162
        
163
        String ret = "";
164
        if (perso != null && !perso.isEmpty()) {
165
            ret = "<!-- " + beginZoneId () + "-->" + this.NL;
166
            ret += perso;
167
            ret += this.NL;
168
            ret += "<!-- " + endZoneId () + "-->" + this.NL;
169
        }
170
        return ret;
171
    }
172

  
173
    private String endZoneId() {
174
        return "end of custom ant target";
175
    }
176

  
177
    private String beginZoneId() {
178
        return "begin of custom ant target";
179
    }
180

  
181
    private String createJavahTarget(final Artifact jarFile, final List<GeneralClass> natives) {
182
        String ret = "    <target name=\"javah\" depends=\"build\">" + this.NL;
183
        if (natives.size () > 0) {
184
            ret += "        <mkdir dir=\"${JNIout}\"/>" + this.NL;
185
        }
186
        ret += "        <javah destdir=\"${JNIout}\" classpath=\"${classpath}\">" + this.NL +
187
        "            <classpath>" + this.NL +
188
        "                <pathelement location=\"" + JavaDesignerUtils.getCompilationPath(jarFile, this.module) + "\"/>" + this.NL +
189
        "                <path refid=\"project.classpath\"/>" + this.NL +
190
        "            </classpath>" + this.NL;
191
        
192
        for (GeneralClass nat : natives) {
193
            ret += "            <class name=\"" + JavaDesignerUtils.getFullJavaName (this.module.getModuleContext().getModelingSession(), nat) + "\"/>" + this.NL;
194
        }
195
        ret += "        </javah>" + this.NL +
196
        "    </target>" + this.NL;
197
        return ret;
198
    }
199

  
200
    private List<GeneralClass> getNativeClasses(final Artifact jarFile) {
201
        List<GeneralClass> ret = new ArrayList<> ();
202
        
203
        for (Manifestation manif : jarFile.getUtilized()) {
204
            ModelElement utilized = manif.getUtilizedElement();
205
            if (utilized instanceof NameSpace) {
206
                ret.addAll(getNativeClasses((NameSpace) utilized));
207
            }
208
        }
209
        return ret;
210
    }
211

  
212
    private List<GeneralClass> getNativeClasses(final NameSpace ns) {
213
        List<GeneralClass> ret = new ArrayList<> ();
214
        
215
        for (ModelTree child : ns.getOwnedElement()) {
216
            if (child instanceof GeneralClass) {
217
                if (isNative((GeneralClass) child)) {
218
                    ret.add((GeneralClass) child);
219
                }
220
            } else if (child instanceof Package) {
221
                ret.addAll(getNativeClasses((Package) child));
222
            }
223
        }
224
        return ret;
225
    }
226

  
227
    private boolean isNative(final GeneralClass cls) {
228
        for (Operation op : cls.getOwnedOperation()) {
229
            if (op.isTagged(IJavaDesignerPeerModule.MODULE_NAME, JavaDesignerTagTypes.OPERATION_JAVANATIVE)) {
230
                return true;
231
            }
232
        }
233
        return false;
234
    }
235

  
236
    private String createRMITarget(final Artifact jarFile) {
237
        String ret = "    <target name=\"rmi\" depends=\"build\">"+ this.NL +
238
        "        <rmic base=\"${compilation.path}\">"+ this.NL;
239
        
240
        for (GeneralClass elt : getUnicastRemoteObjectClasses (jarFile)) {
241
            String className = JavaDesignerUtils.getFullJavaName (this.module.getModuleContext().getModelingSession(), elt);
242
            className = className.replace (".", "/");
243
            
244
            ret += "          <include name=\"" + className + ".class\"/>"+ this.NL;
245
        }
246
        
247
        ret += "        </rmic>"+ this.NL +
248
        "    </target>"+ this.NL;
249
        return ret;
250
    }
251

  
252
    private List<GeneralClass> getUnicastRemoteObjectClasses(final Artifact jarFile) {
253
        List<GeneralClass> ret = new ArrayList<> ();
254
        
255
        for (Manifestation manif : jarFile.getUtilized()) {
256
            ModelElement utilized = manif.getUtilizedElement();
257
            if (utilized instanceof NameSpace) {
258
                ret.addAll(getAllUnicastRemoteObject ((NameSpace) utilized));
259
            }
260
        }
261
        return ret;
262
    }
263

  
264
    private List<GeneralClass> getAllUnicastRemoteObject(final ModelTree utilized) {
265
        List<GeneralClass> ret = new ArrayList<> ();
266
        
267
        for (ModelTree ownedElement : utilized.getOwnedElement()) {
268
            if (ownedElement instanceof GeneralClass) {
269
                if (isUnicastRemoteObject ((GeneralClass) ownedElement)) {
270
                    ret.add((GeneralClass) ownedElement);
271
                }
272
            } else {
273
                ret.addAll(getAllUnicastRemoteObject (ownedElement));
274
            }
275
        }
276
        return ret;
277
    }
278

  
279
    private boolean isUnicastRemoteObject(final GeneralClass ownedElement) {
280
        String targetName = "UnicastRemoteObject";
281
        
282
        
283
        if (JavaDesignerUtils.getJavaName(ownedElement).equals(targetName)) {
284
            return true;
285
        } else {
286
            for (Generalization gen : ownedElement.getParent()) {
287
                NameSpace superType = gen.getSuperType();
288
                if (superType instanceof GeneralClass) {
289
                    if (isUnicastRemoteObject((GeneralClass) superType)) {
290
                        return true;
291
                    }
292
                }
293
            }
294
            
295
            List<String> tagValues = ownedElement.getTagValues(IJavaDesignerPeerModule.MODULE_NAME, JavaDesignerTagTypes.CLASS_JAVAEXTENDS);
296
            return tagValues != null && tagValues.contains(targetName);
297
        }
298
    }
299

  
300
    private String createBuildTarget(final Artifact jarFile) {
301
        String ret = "    <target name=\"build\" depends=\"init, resources \">"+ this.NL +
302
        "        <echo message=\"Building *.java\"/>"+ this.NL +
303
        "        <javac includeAntRuntime=\"false\" srcdir=\"${generation.path}\" destdir=\"${compilation.path}\">"+ this.NL;
304
        
305
        // Mantis 5223, for the compilation options
306
        String options = this.module.getModuleContext().getConfiguration().getParameterValue (JavaDesignerParameters.COMPILATIONOPTIONS);
307
        if (!options.isEmpty()) {
308
            ret += "            <compilerarg value=\"" + options + "\"/>"+ this.NL;
309
        }
310
        
311
        ret += "            <classpath refid=\"project.classpath\"/>" + this.NL;
312
        
313
        for (Manifestation manif : jarFile.getUtilized()) {
314
            ModelElement elt = manif.getUtilizedElement();
315
            
316
            if (elt instanceof Package) {
317
                String fileName = JavaDesignerUtils.getFullJavaName(this.module.getModuleContext().getModelingSession(), elt);
318
                fileName = fileName.replace(".", "/");
319
                if( !fileName.isEmpty() ) {
320
                    fileName += "/";
321
                }
322
                
323
                ret += "            <include name=\"" + fileName + "**/*.java\"/>" + this.NL;
324
            }
325
            
326
            if (elt instanceof GeneralClass && ! (elt instanceof Artifact)) {
327
                String fileName = JavaDesignerUtils.getFullJavaName(this.module.getModuleContext().getModelingSession(), elt);
328
                fileName = fileName.replace(".", "/");
329
                
330
                ret += "            <include name=\"" + fileName + ".java\"/>" + this.NL;
331
            }
332
        }
333
        
334
        ret += "        </javac>" + this.NL +
335
        "    </target>"+ this.NL;
336
        return ret;
337
    }
338

  
339
    private String createJarTarget(final Artifact jarFile) throws IOException {
340
        File jarFilename = JavaDesignerUtils.getFilename(jarFile, this.module);
341
        
342
        String ret =  "    <target name=\"archive\" depends=\"build\">"+ this.NL +
343
        "        <echo message=\"Archiving jar file\"/>"+ this.NL +
344
        "        <mkdir dir=\"" + jarFilename.getParent() + "\"/>"+ this.NL +
345
        "        <jar destfile=\"" + jarFilename + "\" index=\"true\" >"+ this.NL +
346
        "            <manifest>"+ this.NL +
347
        "                <attribute name=\"Built-By\" value=\"Modelio\"/>"+ this.NL;
348
        
349
        String mainClass = ModelUtils.getFirstTagParameter(jarFile, IJavaDesignerPeerModule.MODULE_NAME, JavaDesignerTagTypes.JARFILE_JAVAMAINCLASS);
350
        if (mainClass != null && !mainClass.isEmpty()) {
351
            ret += "                <attribute name=\"Main-Class\" value=\"" + mainClass + "\"/>"+ this.NL;
352
        }
353
        
354
        ret += "            </manifest>"+ this.NL + createFileSetElement (jarFile);
355
        
356
        /* a second fileset for resources  */
357
        List <String> resources = getAllResources (jarFile);
358
        if (resources.size () > 0) {
359
            ret += "            <fileset dir=\"${compilation.path}\" >"+ this.NL;
360
            
361
            for (String resource : resources) {
362
                ret += "          <include name=\"" + resource + "\"/>"+ this.NL;
363
            }
364
            
365
            ret += "            </fileset>"+ this.NL;
366
        }
367
        
368
        ret += "        </jar>"+ this.NL +
369
        "    </target>"+ this.NL;
370
        return ret;
371
    }
372

  
373
    private String createFileSetElement(final Artifact jarFile) {
374
        String ret = "";
375
        
376
        for (Manifestation manif : jarFile.getUtilized()) {
377
            ModelElement elt = manif.getUtilizedElement();
378
            
379
            if (elt instanceof Package) {
380
                String fileName = JavaDesignerUtils.getFullJavaName(this.module.getModuleContext().getModelingSession(), elt);
381
                fileName = fileName.replace(".", "/");
382
                if( !fileName.isEmpty() ) {
383
                    fileName += "/";
384
                }
385
                
386
                ret += "                <include name=\"" + fileName + "**/*.class\"/>" + this.NL;
387
            }
388
            
389
            if (elt instanceof GeneralClass && ! (elt instanceof Artifact)) {
390
                String fileName = JavaDesignerUtils.getFullJavaName(this.module.getModuleContext().getModelingSession(), elt);
391
                fileName = fileName.replace(".", "/");
392
                
393
                ret += "                <include name=\"" + fileName + ".class\"/>" + this.NL;
394
            }
395
        }
396
        
397
        
398
        if (!ret.isEmpty()) {
399
            ret  = "            <fileset dir=\"${compilation.path}\">" + this.NL + ret;
400
            
401
            ret += "            </fileset>" + this.NL;
402
        }
403
        return ret;
404
    }
405

  
406
    private List<String> getAllResources(final Artifact jarFile) throws IOException {
407
        List<String> ret = new ArrayList<> ();
408
        
409
        for (Manifestation manif : jarFile.getUtilized()) {
410
            ModelElement utilized = manif.getUtilizedElement();
411
            if (utilized instanceof ModelTree) {
412
                ret.addAll(getAllResources ((ModelTree) utilized));
413
            }
414
        }
415
        return ret;
416
    }
417

  
418
    private List<String> getAllResources(final ModelTree elt) throws IOException {
419
        List<String> resources = new ArrayList <> (); 
420
        
421
        for (ModelTree ownedElement : elt.getOwnedElement()) {
422
            if (ownedElement instanceof Artifact && ownedElement.isStereotyped(IJavaDesignerPeerModule.MODULE_NAME, JavaDesignerStereotypes.JAVARESOURCE)) {
423
                File directory = JavaDesignerUtils.getDirectory(this.module.getModuleContext().getModelingSession(), ownedElement);
424
                resources.add(new File(directory, JavaDesignerUtils.getJavaName (ownedElement)).getPath()); 
425
            } else if (ownedElement instanceof Package) {
426
                resources.addAll(getAllResources(ownedElement));
427
            }
428
        }
429
        return resources;
430
    }
431

  
432
    private String createResourcesTarget(final Artifact jarFile) throws IOException {
433
        String ret = "    <target name=\"resources\" depends=\"init\">"+ this.NL +
434
        "        <echo message=\"Copying resources\"/>"+ this.NL;
435
        
436
        // The resources target copy resources files from source dir to class dir.
437
        List <String> resources = getAllResources (jarFile);
438
        if (resources.size () != 0) {
439
            ret += "        <copy toDir=\"${compilation.path}\" failonerror=\"false\" preservelastmodified=\"true\" >"+ this.NL +
440
            "            <fileset dir=\"${generation.path}\" >"+ this.NL;
441
            
442
            for (String resource : resources) {
443
                ret += "                <include name=\"" + resource + "\"/>"+ this.NL;
444
            }
445
            
446
            ret += "            </fileset>"+ this.NL +
447
            "        </copy>"+ this.NL;
448
        }
449
        
450
        ret += "    </target>"+ this.NL;
451
        return ret;
452
    }
453

  
454
    private String createCleanTarget(final Artifact jarFile) {
455
        String ret = "    <target name=\"clean\" depends=\"init\"> "+ this.NL +
456
        "        <delete>"+ this.NL +
457
        createFileSetElement(jarFile) +
458
        "        </delete>"+ this.NL +
459
        "    </target>"+ this.NL;
460
        return ret;
461
    }
462

  
463
    private String createInitTarget(final Artifact jarFile) throws IOException {
464
        File JNIOut          = JavaDesignerUtils.getJavahGenerationPath (this.module);
465
        File compilationpath = JavaDesignerUtils.getCompilationPath (jarFile, this.module);
466
        File generationpath  = JavaDesignerUtils.getGenerationPath (jarFile, this.module);
467
        
468
        String ret;
469
        ret =  "    <target name=\"init\" >"+ this.NL;
470
        ret += "        <echo message=\"Initializing Ant properties\"/>"+ this.NL;
471
        ret += "        <property name=\"generation.path\" location=\"" + generationpath.getCanonicalPath() + "\"/>"+ this.NL;
472
        ret += "        <property name=\"compilation.path\" location=\"" + compilationpath.getCanonicalPath() + "\"/>"+ this.NL;
473
        ret += "        <property name=\"JNIout\" location=\"" + JNIOut.getCanonicalPath() + "\"/>"+ this.NL;
474
        ret += "    </target>"+ this.NL;
475
        return ret;
476
    }
477

  
478
    private String createConfigs(final Artifact jarFile) throws IOException {
479
        List <File> classpath = JavaDesignerUtils.getClassPath(this.module);
480
        
481
        File binDir = JavaDesignerUtils.getCompilationPath(jarFile, this.module);
482
        
483
        String javadesignerjar = this.module.getModuleContext().getConfiguration().getModuleResourcesPath() + "/bin/javadesigner.jar";
484
        
485
        String ret = "  <path id=\"project.classpath\">"+ this.NL;
486
        
487
        ret += "    <pathelement location=\"" + javadesignerjar + "\"/>"+ this.NL;
488
        
489
        ret += "    <pathelement location=\"" + binDir + "\"/>"+ this.NL;
490
        
491
        for (File entry : classpath) {
492
            ret += "    <pathelement location=\"" + entry.getCanonicalPath() + "\"/>"+ this.NL;
493
        }
494
        
495
        for (File entry : getUsedJar(jarFile)) {
496
            ret += "    <pathelement location=\"" + entry.getCanonicalPath() + "\"/>"+ this.NL;
497
        }
498
        
499
        ret += "  </path>"+ this.NL;
500
        return ret;
501
    }
502

  
503
    private List<File> getUsedJar(final Artifact jarFile) {
504
        List<File> ret = new ArrayList<>();
505
        
506
        for (Dependency dep : jarFile.getDependsOnDependency()) {
507
            ModelElement dependsOnElt = dep.getDependsOn();
508
            
509
            if (dependsOnElt.isStereotyped(IJavaDesignerPeerModule.MODULE_NAME, JavaDesignerStereotypes.JARFILE)) {
510
                ret.add(JavaDesignerUtils.getFilename((Artifact)dependsOnElt, this.module));
511
            }
512
        }
513
        return ret;
514
    }
515

  
516
    private boolean isUseJavah() {
517
        return this.module.getModuleContext().getConfiguration().getParameterValue(JavaDesignerParameters.USEJAVAH).equalsIgnoreCase("TRUE");
518
    }
519

  
520
}
0 521

  
branches/modelio3.7.x/src/main/java/org/modelio/module/javadesigner/ant/AntTargetExplorer.java
1
package org.modelio.module.javadesigner.ant;
2

  
3
import java.util.List;
4
import org.eclipse.jface.viewers.ISelectionChangedListener;
5
import org.eclipse.jface.viewers.LabelProvider;
6
import org.eclipse.jface.viewers.SelectionChangedEvent;
7
import org.eclipse.jface.viewers.StructuredSelection;
8
import org.eclipse.jface.viewers.TreeViewer;
9
import org.eclipse.swt.SWT;
10
import org.eclipse.swt.graphics.Point;
11
import org.eclipse.swt.layout.GridData;
12
import org.eclipse.swt.widgets.Composite;
13
import org.eclipse.swt.widgets.Control;
14
import org.eclipse.swt.widgets.Shell;
15
import org.modelio.api.ui.ModelioDialog;
16
import org.modelio.module.javadesigner.i18n.Messages;
17
import org.modelio.module.javadesigner.reverse.newwizard.ListContentProvider;
18

  
19
class AntTargetExplorer extends ModelioDialog {
20
     String result;
21

  
22
    private TreeViewer treeViewer;
23

  
24
    protected AntTargetExplorer(final Shell parentShell) {
25
        super (parentShell);
26
    }
27

  
28
    @Override
29
    public void addButtonsInButtonBar(final Composite parent) {
30
        super.addDefaultButtons (parent);
31
    }
32

  
33
    @Override
34
    public Control createContentArea(final Composite parent) {
35
        this.treeViewer = new TreeViewer (parent, SWT.SINGLE | SWT.BORDER);
36
        this.treeViewer.getTree ().setLayoutData (new GridData (SWT.FILL, SWT.FILL, true, true));
37
        
38
        this.treeViewer.setContentProvider (new ListContentProvider ());
39
        this.treeViewer.setLabelProvider (new LabelProvider ());
40
        
41
        this.treeViewer.addSelectionChangedListener (new ISelectionChangedListener () {
42
            
43
            @Override
44
            public void selectionChanged (
45
                    SelectionChangedEvent evt)
46
            {
47
                StructuredSelection sel = ((StructuredSelection) evt.getSelection ());
48
                if (!sel.isEmpty ()) {
49
                    Object selectedElement = sel.getFirstElement ();
50
                    if (selectedElement instanceof String) {
51
                        AntTargetExplorer.this.result = (String) selectedElement;
52
                    } else {
53
                        AntTargetExplorer.this.result = null;
54
                    }
55
                }
56
            }
57
            
58
        });
59
        return parent;
60
    }
61

  
62
    @Override
63
    public void init() {
64
        Shell shell = this.getShell ();
65
        shell.setText (Messages.getString ("Gui.antSelector.shellTitle")); //$NON-NLS-1$
66
        setTitle (Messages.getString ("Gui.antSelector.title")); //$NON-NLS-1$
67
        setMessage (Messages.getString ("Gui.antSelector.message")); //$NON-NLS-1$
68
    }
69

  
70
    public static String getTarget(final Shell parent, final List<String> targets) throws InterruptedException {
71
        AntTargetExplorer l_Explorer = new AntTargetExplorer (parent);
72
        l_Explorer.create ();
73
        l_Explorer.treeViewer.setInput (targets);
74
        
75
        int ret = l_Explorer.open ();
76
        if (ret == 0) {
77
            return l_Explorer.result;
78
        } else {
79
            throw new InterruptedException();
80
        }
81
    }
82

  
83
    @Override
84
    protected Point getInitialSize() {
85
        Point initial = new Point(300, 350);
86
        return initial;
87
    }
88

  
89
}
0 90

  
branches/modelio3.7.x/src/main/java/org/modelio/module/javadesigner/ant/AntTargetLoader.java
1
package org.modelio.module.javadesigner.ant;
2

  
3
import java.util.ArrayList;
4
import java.util.List;
5
import org.xml.sax.Attributes;
6
import org.xml.sax.SAXException;
7
import org.xml.sax.SAXParseException;
8
import org.xml.sax.helpers.DefaultHandler;
9

  
10
class AntTargetLoader extends DefaultHandler {
11
    private List<String> targets;
12

  
13
    public AntTargetLoader() {
14
        super ();
15
    }
16

  
17
    @Override
18
    public void startDocument() throws SAXException {
19
        this.targets = new ArrayList<> ();
20
    }
21

  
22
    @Override
23
    public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException {
24
        if (qName.equals ("target")) {
25
            this.targets.add (attributes.getValue("name"));
26
        }
27
    }
28

  
29
    /**
30
     * Treat validation errors as fatal
31
     */
32
    @Override
33
    public void error(final SAXParseException e) throws SAXParseException {
34
        throw e;
35
    }
36

  
37
    public List<String> getTargets() {
38
        return this.targets;
39
    }
40

  
41
}
0 42

  
branches/modelio3.7.x/src/main/java/org/modelio/module/javadesigner/ant/AntExecutor.java
1
package org.modelio.module.javadesigner.ant;
2

  
3
import java.io.File;
4
import java.io.FileNotFoundException;
5
import java.io.IOException;
6
import java.util.List;
7
import javax.xml.parsers.ParserConfigurationException;
8
import javax.xml.parsers.SAXParser;
9
import javax.xml.parsers.SAXParserFactory;
10
import org.eclipse.swt.widgets.Display;
11
import org.modelio.api.module.IModule;
12
import org.modelio.api.module.context.configuration.IModuleUserConfiguration;
13
import org.modelio.metamodel.uml.statik.Artifact;
14
import org.modelio.module.javadesigner.api.JavaDesignerParameters;
15
import org.modelio.module.javadesigner.custom.CustomFileException;
16
import org.modelio.module.javadesigner.dialog.JConsoleWithDialog;
17
import org.modelio.module.javadesigner.utils.JavaDesignerUtils;
18
import org.modelio.module.javadesigner.utils.ProcessManager;
19
import org.xml.sax.SAXException;
20

  
21
public class AntExecutor {
22
    private IModule module;
23

  
24
     JConsoleWithDialog console;
25

  
26
    public AntExecutor(final IModule module) {
27
        this(module, new JConsoleWithDialog(null));
28
    }
29

  
30
    public AntExecutor(final IModule module, final JConsoleWithDialog console) {
31
        this.module = module;
32
        this.console = console;
33
    }
34

  
35
    public boolean executeTarget(final Artifact antArtifact) {
36
        File antFile = JavaDesignerUtils.getAntFileName(antArtifact, this.module);
37
        
38
        try {
39
            List<String> targets = loadTargets(antFile);
40
            
41
            if (!targets.isEmpty()) {
42
                String target = AntTargetExplorer.getTarget(Display.getDefault().getActiveShell(), targets);
43
                
44
                return executeTarget(antArtifact, target);
45
            } else {
46
                this.console.writeError("No target found\n");
47
            }
48
        } catch (CustomFileException e) {
49
            this.console.writeError(e.getMessage());
50
            this.console.writeError("\n");
51
            return false;
52
        } catch (InterruptedException e) {
53
            // Box canceled
54
        }
55
        return false;
56
    }
57

  
58
    public boolean executeTarget(final Artifact antArtifact, final String target) {
59
        File antFile = JavaDesignerUtils.getAntFileName(antArtifact, this.module);
60
        
61
        IModuleUserConfiguration config = this.module.getModuleContext().getConfiguration();
62
        
63
        File jdkPath = JavaDesignerUtils.getJDKPath(this.module);
64
        
65
        File projectDir = JavaDesignerUtils.getCompilationPath (antArtifact, this.module);
66
        projectDir.mkdirs();
67
        
68
        // Complete classpath with Antlr jars
69
        String toolsJar = jdkPath + "/lib/tools.jar";
70
        String sep = System.getProperty ("os.name").startsWith ("Windows") ? ";" : ":";
71
        
72
        String classpath = config.getParameterValue(JavaDesignerParameters.ACCESSIBLECLASSES);
73
        
74
        // Get ANTLR directory
75
        String antDir = config.getModuleResourcesPath() + "/bin/ant/";
76
        for (File antJarFile : new File(antDir).listFiles()) {
77
            classpath += sep + antJarFile;
78
        }
79
        
80
        classpath += sep + toolsJar;
81
        
82
        // Build command
83
        String javaCmd = "\"" + jdkPath + "/bin/java\"";
84
        String command = javaCmd + " -cp \"" + classpath + "\" -Dant.home=\""+ antDir + "\" -Dbasedir=\"" + projectDir + "\" org.apache.tools.ant.Main -f \"" + antFile +"\" " + target;
85
        
86
        // Write command before execution
87
        this.console.writeInfo(command + "\n\n");
88
        
89
        // Execute command
90
        ProcessManager manager = new ProcessManager(this.console);
91
        manager.execute (command, false);
92
        
93
        this.console.writeInfo("\n");
94
        return true;
95
    }
96

  
97
    /**
98
     * Start the XML parsing of the file in argument.
99
     * @param antFile The file to parse.
100
     * @throws org.modelio.module.javadesigner.custom.CustomFileException If an error has occurred during the loading.
101
     */
102
    public List<String> loadTargets(final File antFile) throws CustomFileException {
103
        // Use a SAX event handler
104
        AntTargetLoader handler = new AntTargetLoader ();
105
        
106
        // Use the validating parser
107
        SAXParserFactory factory = SAXParserFactory.newInstance ();
108
        factory.setNamespaceAware (true);
109
        
110
        try {
111
            // Parse the input
112
            SAXParser saxParser = factory.newSAXParser ();
113
            saxParser.parse (antFile, handler);
114
            
115
            // Save data from the handler
116
            return handler.getTargets();
117
        } catch (SAXException e) {
118
            throw new CustomFileException ("Error when parsing file \"" + antFile.getAbsolutePath () + "\": " + e.getMessage ());
119
        } catch (FileNotFoundException e) {
120
            throw new CustomFileException ("Ant file not found: \"" + antFile.getAbsolutePath () + "\" does not exist");
121
        } catch (IOException e) {
122
            throw new CustomFileException ("Error when loading file: \"" + antFile.getAbsolutePath () + "\"");
123
        } catch (ParserConfigurationException e) {
124
            throw new CustomFileException ("Error when loading file: \"" + antFile.getAbsolutePath () + "\"");
125
        }
126
    }
127

  
128
}
0 129

  
branches/modelio3.7.x/src/main/java/org/modelio/module/javadesigner/editor/EditorManager.java
1
package org.modelio.module.javadesigner.editor;
2

  
3
import java.io.File;
4
import java.util.ArrayList;
5
import java.util.Collection;
6
import java.util.Iterator;
7
import java.util.Vector;
8
import org.eclipse.swt.widgets.Display;
9
import org.modelio.api.modelio.editor.EditorType;
10
import org.modelio.api.modelio.editor.IEditionService;
11
import org.modelio.api.modelio.editor.IMDATextEditor;
12
import org.modelio.api.module.IModule;
13
import org.modelio.metamodel.uml.infrastructure.ModelElement;
14
import org.modelio.metamodel.uml.statik.NameSpace;
15
import org.modelio.module.javadesigner.api.IRefreshService;
16
import org.modelio.module.javadesigner.api.JavaDesignerParameters;
17
import org.modelio.module.javadesigner.utils.JavaDesignerUtils;
18
import org.modelio.vcore.smkernel.mapi.MObject;
19
import org.modelio.vcore.smkernel.mapi.MStatus;
20

  
21
public class EditorManager implements IRefreshService {
22
    private static EditorManager instance;
23

  
24
    protected EditorListener listener = null;
25

  
26
    protected IModule module = null;
27

  
28
    protected Vector<IMDATextEditor> editors;
29

  
30
    public Vector<IMDATextEditor> getEditors() {
31
        return this.editors;
32
    }
33

  
34
    public EditorManager() {
35
        this.editors = new Vector<>();
36
        this.listener = new EditorListener();
37
    }
38

  
39
    protected IMDATextEditor getEditor(final NameSpace element) {
40
        IMDATextEditor editor = null;
41
        for(Iterator<IMDATextEditor> iterator = this.editors.iterator() ; iterator.hasNext() &&
42
               (editor == null) ;) {
43
            IMDATextEditor localeditor = iterator.next();
44
            if(element.equals(localeditor.getElement())) {
45
                editor = localeditor;
46
            }
47
        }
48
        return editor;
49
    }
50

  
51
    public static EditorManager getInstance() {
52
        if(instance == null) {
53
            instance = new EditorManager();
54
        }
55
        return instance;
56
    }
57

  
58
    public void open(final NameSpace element, final IModule currentModule) {
59
        this.module = currentModule;
60
        final MStatus status = element.getStatus();
61
        
62
        final String encoding = this.module.getModuleContext().getConfiguration().getParameterValue(JavaDesignerParameters.ENCODING);
63
        
64
        final File file = JavaDesignerUtils.getFilename(element, this.module);
65
        
66
        Display.getDefault().asyncExec(new Runnable() {
67
            @Override
68
            public void run() {
69
                boolean isReadOnly = !status.isModifiable();
70
        
71
                // Retrieve the editor if already opened
72
                IMDATextEditor editor = getEditor(element);
73
                IEditionService editionService = EditorManager.this.module.getModuleContext().getModelioServices().getEditionService();
74
                if(editor == null) {
75
                    // Open a new editor
76
                    EditorType editorId;
77
                    if(JavaDesignerUtils.isRoundtripMode(currentModule)) {
78
                        editorId = EditorType.RTEditor;
79
                    } else if(JavaDesignerUtils.isModelDrivenMode(currentModule)) {
80
                        editorId = EditorType.MDDEditor;
81
                    } else {
82
                        // Release mode, use RT editor for coloration, but always in read only.
83
                        editorId = EditorType.RTEditor;
84
                        isReadOnly = true;
85
                    }
86
        
87
                    editor = editionService.openEditor(element, file, editorId, isReadOnly, encoding);
88
                    editor.setListener(EditorManager.this.listener);
89
                    EditorManager.this.listener.setModule(currentModule);
90
                    EditorManager.this.editors.add(editor);
91
                } else {
92
                    editionService.activateEditor(editor);
93
                }
94
            }
95
        });
96
    }
97

  
98
    public void removeEditor(final IMDATextEditor editor) {
99
        this.editors.remove(editor);
100
    }
101

  
102
    public void updateStatusForElement(final MObject element, final boolean isReadOnly, final String encoding) {
103
        if((element instanceof NameSpace)) {
104
            NameSpace modelelement =(NameSpace) element;
105
            final IMDATextEditor editor = getEditor(modelelement);
106
            if(editor != null) {
107
                editor.setReadonlyMode(isReadOnly);
108
                editor.setCharsetName(encoding);
109
            }
110
        }
111
    }
112

  
113
    public void updateEditorsFromElements() {
114
        if(EditorManager.this.editors.size() == 0) {
115
            return;
116
        }
117
        
118
        final ArrayList<IMDATextEditor> toDelete = new ArrayList<>();
119
        final ArrayList<IMDATextEditor> needModeUpdate = new ArrayList<>();
120
        
121
        // Get the current generation mode from the module
122
        final boolean isReleaseMode;
123
        final EditorType editorId;
124
        if(EditorManager.this.module != null && JavaDesignerUtils.isRoundtripMode(this.module)) {
125
            editorId = EditorType.RTEditor;
126
            isReleaseMode = false;
127
        } else if(EditorManager.this.module != null && JavaDesignerUtils.isModelDrivenMode(this.module)) {
128
            editorId = EditorType.MDDEditor;
129
            isReleaseMode = false;
130
        } else {
131
            // Release mode, use RT editor for coloration, but always in read only.
132
            editorId = EditorType.RTEditor;
133
            isReleaseMode = true;
134
        }
135
        
136
        // Get the current encoding
137
        final String encoding = this.module.getModuleContext().getConfiguration().getParameterValue(JavaDesignerParameters.ENCODING);
138
        
139
        Display.getDefault().asyncExec(new Runnable() {
140
            @Override
141
            public void run() {
142
                // For all editors, check the mode for update, and verifies the element
143
                for(IMDATextEditor editor : EditorManager.this.editors) {
144
                    ModelElement modelElement = editor.getElement();
145
        
146
                    if(modelElement == null || modelElement.isDeleted()) {
147
                        toDelete.add(editor);
148
                    } else {
149
                        File openedFile = editor.getFile();
150
                        String newPath = JavaDesignerUtils.getDirectory(EditorManager.this.module.getModuleContext().getModelingSession(),(NameSpace) editor.getElement()) + File.separator + JavaDesignerUtils.getJavaName(editor.getElement()) + ".java";
151
        
152
                        // Check if the file has changed for this element
153
                        if(!openedFile.getAbsolutePath().endsWith(newPath) || !openedFile.exists()) {
154
                            toDelete.add(editor);
155
                        } else if(editor.getType() != null && !editor.getType().equals(editorId)) {
156
                            needModeUpdate.add(editor);
157
                        } else {
158
                            boolean isReadOnly = isReleaseMode || !modelElement.getStatus().isModifiable();
159
                            updateStatusForElement(modelElement, isReadOnly, encoding);
160
                        }
161
                    }
162
                }
163
        
164
                // For all editors with an invalid element, close it
165
                IEditionService editionService = EditorManager.this.module.getModuleContext().getModelioServices().getEditionService();
166
                for(IMDATextEditor editor : toDelete) {
167
                    editionService.closeEditor(editor);
168
                    EditorManager.this.editors.remove(editor);
169
                }
170
        
171
                // For all editors having a bad mode, close the current editor and open it again
172
                for(IMDATextEditor textEditor : needModeUpdate) {
173
                    NameSpace theElement =(NameSpace) textEditor.getElement();
174
                    editionService.closeEditor(textEditor);
175
                    open(theElement, EditorManager.this.module);
176
                }
177
            }
178
        });
179
    }
180

  
181
    public void closeEditors() {
182
        if(!this.editors.isEmpty()) {
183
            Display.getDefault().asyncExec(new Runnable() {
184
                @Override
185
                public void run() {
186
                    // Create a temp list to store editors to delete.
187
                    ArrayList<IMDATextEditor> toDelete = new ArrayList<>(EditorManager.this.editors);
188
        
189
                    IEditionService editionService = EditorManager.this.module.getModuleContext().getModelioServices().getEditionService();
190
                    for(IMDATextEditor editor : toDelete) {
191
                        editionService.closeEditor(editor);
192
                        EditorManager.this.editors.remove(editor);
193
                    }
194
                }
195
            });
196
        }
197
    }
198

  
199
    @Override
200
    public void refresh(final Collection<NameSpace> elements) {
201
        Display.getDefault().asyncExec(new Runnable() {
202
            @Override
203
            public void run() {
204
                // First, validate all editors
205
                updateEditorsFromElements();
206
        
207
                // Check the dirty flag
208
                for(IMDATextEditor editor : getEditors()) {
209
                    if(!editor.isDirty() && elements.contains(editor.getElement())) {
210
                        editor.reload();
211
                    }
212
                }
213
            }
214
        });
215
    }
216

  
217
}
0 218

  
branches/modelio3.7.x/src/main/java/org/modelio/module/javadesigner/editor/EditorListener.java
1
package org.modelio.module.javadesigner.editor;
2

  
3
import java.io.File;
4
import java.util.HashSet;
5
import org.modelio.api.modelio.editor.IMDAEditorListener;
6
import org.modelio.api.modelio.editor.IMDATextEditor;
7
import org.modelio.api.module.IModule;
8
import org.modelio.metamodel.uml.infrastructure.ModelElement;
9
import org.modelio.metamodel.uml.statik.NameSpace;
10
import org.modelio.module.javadesigner.report.ReportManager;
11
import org.modelio.module.javadesigner.report.ReportModel;
12
import org.modelio.module.javadesigner.reverse.Reversor;
13
import org.modelio.module.javadesigner.utils.JavaDesignerUtils;
14

  
15
public class EditorListener implements IMDAEditorListener {
16
    private IModule module;
17

  
18
    public EditorListener() {
19
        // Nothing to initialize
20
    }
21

  
22
    public void setModule(final IModule module) {
23
        this.module = module;
24
    }
25

  
26
    @Override
27
    public void documentSaved(final IMDATextEditor editor, final ModelElement element, final File file) {
28
        if (element instanceof NameSpace) {
29
            HashSet<NameSpace> elementsToReverse = new HashSet<> ();
30
            elementsToReverse.add ((NameSpace) element);
31
        
32
            try {
33
                JavaDesignerUtils.initCurrentGenRoot (elementsToReverse);
34
            } catch (InterruptedException e) {
35
                return;
36
            }
37
            
38
            ReportModel report = ReportManager.getNewReport ();
39
        
40
            Reversor reversor = new Reversor (this.module, report);
41
            reversor.update (elementsToReverse, EditorManager.getInstance ());
42
        
43
            ReportManager.showGenerationReport (report);
44
            
45
            JavaDesignerUtils.setProjectGenRoot (null);
46
        }
47
    }
48

  
49
    @Override
50
    public void editorClosed(final IMDATextEditor editor) {
51
        EditorManager.getInstance ().removeEditor (editor);
52
    }
53

  
54
}
0 55

  
branches/modelio3.7.x/src/main/java/org/modelio/module/javadesigner/generator/GenerateProgressBar.java
1
package org.modelio.module.javadesigner.generator;
2

  
3
import java.io.BufferedOutputStream;
4
import java.io.File;
5
import java.io.FileOutputStream;
6
import java.io.IOException;
7
import java.io.PrintStream;
8
import java.lang.reflect.InvocationTargetException;
9
import java.util.ArrayList;
10
import java.util.Collection;
11
import java.util.HashSet;
12
import java.util.List;
13
import java.util.Set;
14
import com.modelio.module.xmlreverse.IReportWriter;
15
import org.eclipse.core.runtime.IProgressMonitor;
16
import org.eclipse.jface.operation.IRunnableWithProgress;
17
import org.eclipse.swt.widgets.Display;
18
import org.modelio.api.modelio.model.IModelingSession;
19
import org.modelio.api.module.IModule;
20
import org.modelio.gproject.gproject.GProject;
21
import org.modelio.metamodel.uml.infrastructure.ModelTree;
22
import org.modelio.metamodel.uml.statik.Component;
23
import org.modelio.metamodel.uml.statik.NameSpace;
24
import org.modelio.metamodel.uml.statik.Package;
25
import org.modelio.module.javadesigner.api.CustomException;
26
import org.modelio.module.javadesigner.api.IJavaDesignerPeerModule;
27
import org.modelio.module.javadesigner.i18n.Messages;
28
import org.modelio.module.javadesigner.progress.ProgressBar;
29
import org.modelio.module.javadesigner.utils.JavaDesignerUtils;
30
import org.modelio.vcore.session.api.ICoreSession;
31
import org.modelio.vcore.session.api.transactions.ITransaction;
32

  
33
public class GenerateProgressBar extends ProgressBar implements IRunnableWithProgress {
34
	private Collection<NameSpace> elementsToGenerate;
35

  
36
	private IReportWriter report;
37

  
38
	public GenerateProgressBar(final IModule module, final Collection<NameSpace> elementsToGenerate, final IReportWriter report) {
39
		super (module, elementsToGenerate.size ());
40
		this.elementsToGenerate = elementsToGenerate;
41
		this.report = report;
42
	}
43

  
44
	@Override
45
	public void run(final IProgressMonitor localMonitor) throws InterruptedException, InvocationTargetException {
46
		init (true);
47
		monitor = localMonitor;
48
		monitor.beginTask ("Generating", this.elementsToGenerate.size ());
49

  
50
		List<JavaMoveFileStruct> filesToMove = new ArrayList<> ();
51
		File tempDir;
52
		// Create a temporary directory
53
		try {
54
			tempDir = File.createTempFile (IJavaDesignerPeerModule.MODULE_NAME, ""); //$NON-NLS-1$ //$NON-NLS-2$
55
			tempDir.delete ();
56
			tempDir.mkdir ();
57
			tempDir.deleteOnExit ();
58
		} catch (IOException e) {
59
			this.module.getModuleContext().getLogService().error(e);
60
			// Should nether happen
61
			throw new InterruptedException (e.getMessage());
62
		}
63

  
64
		IModelingSession session = this.module.getModuleContext().getModelingSession ();
65

  
66
		ClassTemplate classTemplate = new ClassTemplate (this.report, session);
67

  
68
		// Create module parameter cache
69
		JavaConfiguration javaConfig = new JavaConfiguration (this.module.getModuleContext().getConfiguration ());
70

  
71
		// Generation
72
		for (NameSpace element : this.elementsToGenerate) {
73
			if ((element instanceof Package && !JavaDesignerUtils.isPackageAnnotated ((Package) element)) ||
74
					(element instanceof Component && JavaDesignerUtils.isAJavaComponent(element))) {
75
				// Nothing to do, the directory will be created later
76
			} else {
77
				// Compute the real file to generate
78
				File realFile = JavaDesignerUtils.getFilename (element, this.module);
79

  
80
				monitor.setTaskName (Messages.getString ("Info.ProgressBar.Generating", realFile)); //$NON-NLS-1$
81

  
82
				this.module.getModuleContext().getLogService().info (Messages.getString ("Info.ProgressBar.Generating", realFile));
83

  
84
				// Use a temporary file
85
				File tempFile = new File (tempDir, "tempFile" + filesToMove.size());
86
				filesToMove.add (new JavaMoveFileStruct(tempFile, realFile, element));
87

  
88
				// Generate the code
89
				generate(classTemplate, javaConfig, element, tempFile);
90

  
91
				updateProgressBar (null);
92
				if (monitor.isCanceled ()) {
93
					break;
94
				}
95
			}
96
		}
97

  
98
		// Move all temporary files towards their real destinations
99
		if (!this.report.hasErrors ()) {
100
			if (!filesToMove.isEmpty()) {
101
				Display.getDefault().asyncExec(new Runnable() {
102
					@Override
103
					public void run() {
104
						ICoreSession coreSession = GProject.getProject(filesToMove.get(0).element).getSession();
105
						try (ITransaction t = coreSession.getTransactionSupport().createTransaction("Update generation dates")) {
106
							t.disableUndo();
107

  
108
							Set<Package> generatedPackages = new HashSet<>();
109

  
110
							for (JavaMoveFileStruct tempStruct : filesToMove) {
111
								// Save the file time on the element
112
								JavaDesignerUtils.updateDate (session, tempStruct.element, tempStruct.executeMove());
113

  
114
								if (tempStruct.element instanceof Package) {
115
									generatedPackages.add((Package) tempStruct.element);
116
								}
117

  
118
								ModelTree parent = tempStruct.element.getOwner();
119
								while (parent instanceof Package) {
120
									generatedPackages.add((Package) parent);
121
									parent = parent.getOwner();
122
								}
123
							}
124
							t.commit();
125
						}
126
					}
127
				});
128
			}
129
		} else {
130
			this.report.addError (Messages.getString ("Error.GenerationCanceled"), null, Messages.getString ("Error.GenerationCanceled.GenerationFailed")); //$NON-NLS-1$  //$NON-NLS-2$
131
		}
132

  
133
		this.module.getModuleContext().getLogService().info (this.elementsToGenerate.size () + " elements generated in " + formatTime (getElapsedTime ()));
134

  
135
		ProgressBar.monitor.done ();
136
	}
137

  
138
	private void generate(ClassTemplate classTemplate, JavaConfiguration javaConfig, NameSpace element, File targetFile) {
139
		try (FileOutputStream fos = new FileOutputStream (targetFile); PrintStream out = new PrintStream (new BufferedOutputStream (fos), false, javaConfig.ENCODING)) {
140
			// Call the template
141
			try {
142
				classTemplate.generate (element, out, javaConfig);
143

  
144
				// Flush the output in case the buffer is not empty
145
				out.flush ();
146

  
147
				out.close();
148
			} catch (TemplateException|CustomException e) {
149
				this.report.addError (e.getMessage (), element, "");
150
			} catch (Exception e) {
151
				this.module.getModuleContext().getLogService().error(e);
152
				this.report.addError (e.getMessage (), element, "");
153
			}
154
		} catch (IOException e) {
155
			this.report.addError (e.getMessage (), element, "");
156
		}
157
	}
158

  
159
	/**
160
	 * Simple file structure used to delay a file move related to a {@link NameSpace}.
161
	 */
162
	private static class JavaMoveFileStruct {
163
		private File sourceFile;
164

  
165
		private File targetFile;
166

  
167
		private NameSpace element;
168

  
169
		JavaMoveFileStruct(File sourceFile, File targetFile, NameSpace element) {
170
			this.sourceFile = sourceFile;
171
			this.targetFile = targetFile;
172
			this.element = element;
173
		}
174

  
175
		/**
176
		 * Move the source file to the target file.
177
		 * @return the modification date of the target file.
178
		 */
179
		long executeMove() {
180
			if (this.sourceFile.exists ()) {
181
				if (this.targetFile.exists ()) {
182
					this.targetFile.delete ();
183
				}
184

  
185
				if (!this.sourceFile.renameTo (this.targetFile)) {
186
					// If the rename fails, copy the file manually then delete the original...
187
					JavaDesignerUtils.copyFile (this.sourceFile, this.targetFile);
188
					this.sourceFile.delete ();
189
				}
190
			}
191
			return this.targetFile.lastModified ();
192
		}
193

  
194
	}
195

  
196
}
0 197

  
branches/modelio3.7.x/src/main/java/org/modelio/module/javadesigner/generator/Generator.java
1
package org.modelio.module.javadesigner.generator;
2

  
3
import java.lang.reflect.InvocationTargetException;
4
import java.util.Collection;
5
import java.util.HashSet;
6
import java.util.Set;
7
import org.eclipse.jface.dialogs.IDialogConstants;
8
import org.eclipse.jface.dialogs.MessageDialog;
9
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
10
import org.eclipse.jface.window.Window;
11
import org.eclipse.swt.widgets.Display;
12
import org.modelio.api.modelio.editor.IMDATextEditor;
13
import org.modelio.api.modelio.model.IModelingSession;
14
import org.modelio.api.modelio.model.ITransaction;
15
import org.modelio.api.modelio.model.event.IModelChangeHandler;
16
import org.modelio.api.module.IModule;
17
import org.modelio.api.module.lifecycle.IModuleLifeCycleHandler;
18
import org.modelio.metamodel.uml.statik.NameSpace;
19
import org.modelio.metamodel.uml.statik.Package;
20
import org.modelio.module.javadesigner.api.ISessionWithHandler;
21
import org.modelio.module.javadesigner.editor.EditorManager;
22
import org.modelio.module.javadesigner.file.FileModificationAnalyzer;
23
import org.modelio.module.javadesigner.i18n.Messages;
24
import org.modelio.module.javadesigner.report.ReportModel;
25
import org.modelio.module.javadesigner.reverse.Reversor;
26
import org.modelio.module.javadesigner.reverse.ui.ReverseException;
27
import org.modelio.module.javadesigner.utils.JavaDesignerUtils;
28

  
29
public class Generator {
30
    private IModule module = null;
31

  
32
    private Collection<NameSpace> elementsToGenerate;
33

  
34
    public Generator(final Collection<NameSpace> elements, final IModule module) {
35
        this.module = module;
36
        this.elementsToGenerate = elements;
37
    }
38

  
39
    public void generate(final ReportModel report) {
40
        boolean cancel = false;
41
        
42
        // Handle dirty editors on elements to be generated
43
        for (IMDATextEditor editor : EditorManager.getInstance ().getEditors ()) {
44
            if (editor.isDirty () && this.elementsToGenerate.contains (editor.getElement ())) {
45
                // Ask the user what to do
46
                MessageDialog dialog = new MessageDialog (Display.getCurrent ().getActiveShell (), Messages.getString ("Info.SaveFileBeforeGeneration.Title"), null, Messages.getString ("Info.SaveFileBeforeGeneration.Label", editor.getFile ().getName ()), MessageDialog.QUESTION, new String[] { //$NON-NLS-1$ //$NON-NLS-2$
47
                        IDialogConstants.YES_LABEL,
48
                        IDialogConstants.NO_LABEL,
49
                        Messages.getString ("Gui.CancelButton") }, 0); //$NON-NLS-1$
50
                int res = dialog.open ();
51
                if (res == Window.OK) {
52
                    // Yes button => save the editor
53
                    editor.save ();
54
                } else if (res == 1) {
55
                    // No button => discard changes and reload the editor
56
                    editor.reload();
57
                } else if (res == 2) {
58
                    // Cancel button => cancel generation without modifying the editor
59
                    cancel = true;
60
                }
61
            }
62
        }
63
        
64
        if (!cancel) {
65
            // Open transaction
66
            IModelingSession session = this.module.getModuleContext().getModelingSession ();
67
        
68
            try (ITransaction transaction = session.createTransaction (Messages.getString ("Info.Session.Generate"))) {
69
                // Updating model
70
                Reversor reversor = new Reversor (this.module, report);
71
                FileModificationAnalyzer fileAnalyzer = new FileModificationAnalyzer(this.module);
72
        
73
                // Remove all packages and java components from the element list to avoid reversing classes after choosing "keep" in the
74
                // retrieve behavior box
75
                Set<NameSpace> classesToGenerate = new HashSet<> ();
76
                for (NameSpace element : this.elementsToGenerate) {
77
                    if ((!(element instanceof Package) || JavaDesignerUtils.isPackageAnnotated ((Package) element))
78
                            && !JavaDesignerUtils.isAJavaComponent(element)) {
79
                        classesToGenerate.add (element);
80
                    }
81
                }
82
                this.elementsToGenerate = classesToGenerate;
83
        
84
                try {
85
                    // Analyze generated files
86
                    fileAnalyzer.analyzeFiles(this.elementsToGenerate);
87
        
88
                    // Update some files if necessary
89
                    if (!fileAnalyzer.getOutdatedElements().isEmpty()) {
90
                        reversor.update (fileAnalyzer.getOutdatedElements(), EditorManager.getInstance ());
91
                    }
92
                    
93
                    if (report.getErrors ().isEmpty ()) {
94
                        ProgressMonitorDialog dialog = new ProgressMonitorDialog(Display.getDefault().getActiveShell());
95
                        dialog.open();
96
                        dialog.run(true, true, new GenerateProgressBar (this.module, this.elementsToGenerate, report));
97
                    } else {
98
                        cancel = true;
99
                        report.addError (Messages.getString ("Error.GenerationCanceled"), null, Messages.getString ("Error.GenerationCanceled.InitialReverse")); //$NON-NLS-1$  //$NON-NLS-2$
100
                    }
101
                } catch (InvocationTargetException e) {
102
                    cancel = true;
103
                } catch (InterruptedException e) {
104
                    cancel = true;
105
                } catch (ReverseException e) {
106
                    cancel = true;
107
                    // TODO add message
108
                }
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff