KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > emf > codegen > ecore > Generator


1 /**
2  * <copyright>
3  *
4  * Copyright (c) 2002-2005 IBM Corporation and others.
5  * All rights reserved. This program and the accompanying materials
6  * are made available under the terms of the Eclipse Public License v1.0
7  * which accompanies this distribution, and is available at
8  * http://www.eclipse.org/legal/epl-v10.html
9  *
10  * Contributors:
11  * IBM - Initial API and implementation
12  *
13  * </copyright>
14  *
15  * $Id: Generator.java,v 1.21 2005/06/16 15:45:54 marcelop Exp $
16  */

17 package org.eclipse.emf.codegen.ecore;
18
19
20 import java.io.File JavaDoc;
21 import java.util.Arrays JavaDoc;
22 import java.util.Collections JavaDoc;
23 import java.util.HashMap JavaDoc;
24 import java.util.Iterator JavaDoc;
25 import java.util.List JavaDoc;
26 import java.util.Map JavaDoc;
27
28 import org.xml.sax.Attributes JavaDoc;
29 import org.xml.sax.XMLReader JavaDoc;
30 import org.xml.sax.helpers.DefaultHandler JavaDoc;
31 import org.xml.sax.helpers.XMLReaderFactory JavaDoc;
32
33 import org.eclipse.core.resources.ICommand;
34 import org.eclipse.core.resources.IContainer;
35 import org.eclipse.core.resources.IFolder;
36 import org.eclipse.core.resources.IProject;
37 import org.eclipse.core.resources.IProjectDescription;
38 import org.eclipse.core.resources.IWorkspace;
39 import org.eclipse.core.resources.IWorkspaceRunnable;
40 import org.eclipse.core.resources.ResourcesPlugin;
41 import org.eclipse.core.runtime.CoreException;
42 import org.eclipse.core.runtime.IPath;
43 import org.eclipse.core.runtime.IProgressMonitor;
44 import org.eclipse.core.runtime.IStatus;
45 import org.eclipse.core.runtime.Path;
46 import org.eclipse.core.runtime.Status;
47 import org.eclipse.core.runtime.SubProgressMonitor;
48 import org.eclipse.jdt.core.IClasspathEntry;
49 import org.eclipse.jdt.core.IJavaProject;
50 import org.eclipse.jdt.core.JavaCore;
51 import org.eclipse.jdt.launching.JavaRuntime;
52
53 import org.eclipse.emf.codegen.CodeGen;
54 import org.eclipse.emf.codegen.ecore.genmodel.GenModel;
55 import org.eclipse.emf.codegen.ecore.genmodel.GenModelFactory;
56 import org.eclipse.emf.codegen.ecore.genmodel.GenPackage;
57 import org.eclipse.emf.codegen.util.CodeGenUtil;
58 import org.eclipse.emf.common.util.URI;
59 import org.eclipse.emf.common.util.UniqueEList;
60 import org.eclipse.emf.ecore.EPackage;
61 import org.eclipse.emf.ecore.plugin.EcorePlugin;
62 import org.eclipse.emf.ecore.resource.Resource;
63 import org.eclipse.emf.ecore.resource.ResourceSet;
64 import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
65
66
67 /**
68  * This implements the method {@link #run},
69  * which is called just like main during headless workbench invocation.
70  */

71 public class Generator extends CodeGen
72 {
73   /**
74    * This supports a non-headless invocation.
75    * The variable VABASE or ECLIPSE.
76    * @deprecated It is not possible to generate code withtout using Eclipse. If
77    * you are invoking this method, you should instantiate a Generator and call
78    * {@link #run(Object)}. This method will be removed in a future release.
79    */

80   public static void main(String JavaDoc args[])
81   {
82     new Generator().run(args);
83   }
84
85   protected String JavaDoc basePackage;
86
87   public void printGenerateUsage()
88   {
89     System.out.println("Usage arguments:");
90     System.out.println(" [-platform | -data] <workspace-directory> ");
91     System.out.println(" [-projects ] <project-root-directory> ");
92     System.out.println(" [-dynamicTemplates] [-forceOverwrite | -diff]");
93     System.out.println(" [-generateSchema] [-nonNLSMarkers]");
94     System.out.println(" [-codeFormatting { default | <profile-file> } ]");
95     System.out.println(" [-model] [-edit] [-editor]");
96     System.out.println(" <genmodel-file>");
97     System.out.println(" [ <target-root-directory> ]");
98     System.out.println("");
99     System.out.println("For example:");
100     System.out.println("");
101     System.out.println(" generate result/model/Extended.genmodel");
102   }
103
104   /**
105    * This is called with the command line arguments of a headless workbench invocation.
106    */

107   public Object JavaDoc run(Object JavaDoc object)
108   {
109     try
110     {
111       final String JavaDoc[] arguments = (String JavaDoc[])object;
112       final IWorkspace workspace = ResourcesPlugin.getWorkspace();
113       IWorkspaceRunnable runnable =
114         new IWorkspaceRunnable()
115         {
116           public void run(IProgressMonitor progressMonitor) throws CoreException
117           {
118             try
119             {
120               if (arguments.length == 0)
121               {
122                 printGenerateUsage();
123               }
124               else if ("-ecore2GenModel".equalsIgnoreCase(arguments[0]))
125               {
126                 IPath ecorePath = new Path(arguments[1]);
127                 basePackage = arguments[2];
128                 String JavaDoc prefix = arguments[3];
129
130                 ResourceSet resourceSet = new ResourceSetImpl();
131                 resourceSet.getURIConverter().getURIMap().putAll(EcorePlugin.computePlatformURIMap());
132                 URI ecoreURI = URI.createFileURI(ecorePath.toString());
133                 Resource resource = resourceSet.getResource(ecoreURI, true);
134                 EPackage ePackage = (EPackage)resource.getContents().get(0);
135
136                 IPath genModelPath = ecorePath.removeFileExtension().addFileExtension("genmodel");
137                 progressMonitor.beginTask("", 2);
138                 progressMonitor.subTask("Creating " + genModelPath);
139
140                 URI genModelURI = URI.createFileURI(genModelPath.toString());
141                 Resource genModelResource =
142                   Resource.Factory.Registry.INSTANCE.getFactory(genModelURI).createResource(genModelURI);
143                 GenModel genModel = GenModelFactory.eINSTANCE.createGenModel();
144                 genModelResource.getContents().add(genModel);
145                 resourceSet.getResources().add(genModelResource);
146                 genModel.setModelDirectory("/TargetProject/src");
147                 genModel.getForeignModel().add(ecorePath.toString());
148                 genModel.initialize(Collections.singleton(ePackage));
149                 GenPackage genPackage = (GenPackage)genModel.getGenPackages().get(0);
150                 genModel.setModelName(genModelURI.trimFileExtension().lastSegment());
151
152                 genPackage.setPrefix(prefix);
153                 genPackage.setBasePackage(basePackage);
154
155                 progressMonitor.worked(1);
156
157                 if (arguments.length > 4 && "-sdo".equals(arguments[4]))
158                 {
159                   setSDODefaults(genModel);
160                 }
161
162                 genModelResource.save(Collections.EMPTY_MAP);
163               }
164               else
165               {
166                 String JavaDoc rootLocation = null;
167                 boolean dynamicTemplates = false;
168                 boolean diff = false;
169                 boolean forceOverwrite = false;
170                 boolean generateSchema = false;
171                 boolean nonNLSMarkers = false;
172                 boolean codeFormatting = false;
173                 String JavaDoc profileFile = null;
174                 boolean model = false;
175                 boolean edit = false;
176                 boolean editor = false;
177                 boolean tests = false;
178                 
179                 int index = 0;
180                 for (; index < arguments.length && arguments[index].startsWith("-"); ++index)
181                 {
182                   if (arguments[index].equalsIgnoreCase("-projects"))
183                   {
184                     rootLocation = new File JavaDoc(arguments[++index]).getAbsoluteFile().getCanonicalPath();
185                   }
186                   else if (arguments[index].equalsIgnoreCase("-dynamicTemplates"))
187                   {
188                     dynamicTemplates = true;
189                   }
190                   else if (arguments[index].equalsIgnoreCase("-diff"))
191                   {
192                     diff = true;
193                   }
194                   else if (arguments[index].equalsIgnoreCase("-forceOverwrite"))
195                   {
196                     forceOverwrite = true;
197                   }
198                   else if (arguments[index].equalsIgnoreCase("-generateSchema"))
199                   {
200                     generateSchema = true;
201                   }
202                   else if (arguments[index].equalsIgnoreCase("-nonNLSMarkers"))
203                   {
204                     nonNLSMarkers = true;
205                   }
206                   else if (arguments[index].equalsIgnoreCase("-codeFormatting"))
207                   {
208                     codeFormatting = true;
209                     profileFile = arguments[++index];
210                     if ("default".equals(profileFile))
211                     {
212                       profileFile = null;
213                     }
214                   }
215                   else if (arguments[index].equalsIgnoreCase("-model"))
216                   {
217                     model = true;
218                   }
219                   else if (arguments[index].equalsIgnoreCase("-edit"))
220                   {
221                     edit = true;
222                   }
223                   else if (arguments[index].equalsIgnoreCase("-editor"))
224                   {
225                     editor = true;
226                   }
227                   else if (arguments[index].equalsIgnoreCase("-tests"))
228                   {
229                     tests = true;
230                   }
231                   else
232                   {
233                     throw new CoreException(
234                       new Status(
235                         IStatus.ERROR,
236                         CodeGenEcorePlugin.getPlugin().getBundle().getSymbolicName(),
237                         0,
238                         "Unrecognized argument: '" + arguments[index] + "'",
239                         null));
240                   }
241                 }
242
243                 if (!model && !edit && !editor && !tests)
244                 {
245                   model = true;
246                 }
247
248                 // This is the name of the model.
249
//
250
String JavaDoc genModelName = arguments[index++];
251
252                 progressMonitor.beginTask("Generating " + genModelName, 2);
253           
254                 // Create a resource set and load the model file into it.
255
//
256
ResourceSet resourceSet = new ResourceSetImpl();
257                 resourceSet.getURIConverter().getURIMap().putAll(EcorePlugin.computePlatformURIMap());
258                 URI genModelURI = URI.createFileURI(new File JavaDoc(genModelName).getAbsoluteFile().getCanonicalPath());
259                 Resource genModelResource = resourceSet.getResource(genModelURI, true);
260                 GenModel genModel = (GenModel)genModelResource.getContents().get(0);
261
262                 IStatus status = genModel.validate();
263                 if (!status.isOK())
264                 {
265                   printStatus("", status);
266                 }
267                 else
268                 {
269                   if (dynamicTemplates)
270                   {
271                     genModel.setDynamicTemplates(dynamicTemplates);
272                   }
273                   genModel.setForceOverwrite(forceOverwrite);
274                   genModel.setRedirection(diff ? ".{0}.new" : "");
275   
276                   if (index < arguments.length)
277                   {
278                     IPath path = new Path(genModel.getModelDirectory());
279                     // This is the path of the target directory.
280
//
281
IPath targetRootDirectory = new Path(arguments[index]);
282                     targetRootDirectory = new Path(targetRootDirectory.toFile().getAbsoluteFile().getCanonicalPath());
283                     CodeGenUtil.findOrCreateContainer
284                       (new Path(path.segment(0)), true, targetRootDirectory, new SubProgressMonitor(progressMonitor, 1));
285                   }
286                   // This is to handle a genmodel produced by rose2genmodel.
287
//
288
else
289                   {
290                     String JavaDoc modelDirectory = genModel.getModelDirectory();
291                     genModel.setModelDirectory(findOrCreateContainerHelper(rootLocation, modelDirectory, progressMonitor));
292   
293                     String JavaDoc editDirectory = genModel.getEditDirectory();
294                     if (edit && editDirectory != null)
295                     {
296                       genModel.setEditDirectory(findOrCreateContainerHelper(rootLocation, editDirectory, progressMonitor));
297                     }
298   
299                     String JavaDoc editorDirectory = genModel.getEditorDirectory();
300                     if (editor && editorDirectory != null)
301                     {
302                       genModel.setEditorDirectory(findOrCreateContainerHelper(rootLocation, editorDirectory, progressMonitor));
303                     }
304
305                     String JavaDoc testsDirectory = genModel.getTestsDirectory();
306                     if (tests && testsDirectory != null)
307                     {
308                       genModel.setTestsDirectory(findOrCreateContainerHelper(rootLocation, testsDirectory, progressMonitor));
309                     }
310                   }
311   
312                   genModel.setCanGenerate(true);
313                   genModel.setUpdateClasspath(false);
314   
315                   genModel.setGenerateSchema(generateSchema);
316                   genModel.setNonNLSMarkers(nonNLSMarkers);
317                   genModel.setCodeFormatting(codeFormatting);
318
319                   if (profileFile != null)
320                   {
321                     Map JavaDoc options = CodeFormatterProfileParser.parse(profileFile);
322                     if (options == null)
323                     {
324                       throw new CoreException
325                         (new Status
326                           (IStatus.ERROR,
327                            CodeGenEcorePlugin.getPlugin().getBundle().getSymbolicName(),
328                            0,
329                            "Unable to read profile file: '" + profileFile + "'",
330                            null));
331                     }
332                     genModel.setCodeFormatterOptions(options);
333                   }
334
335                   if (model)
336                   {
337                     genModel.generate(new SubProgressMonitor(progressMonitor, 1));
338                   }
339                   if (edit)
340                   {
341                     genModel.generateEdit(new SubProgressMonitor(progressMonitor, 1));
342                   }
343                   if (editor)
344                   {
345                     genModel.generateEditor(new SubProgressMonitor(progressMonitor, 1));
346                   }
347                   if (tests)
348                   {
349                     genModel.generateTests(new SubProgressMonitor(progressMonitor, 1));
350                   }
351                 }
352               }
353             }
354             catch (CoreException exception)
355             {
356               throw exception;
357             }
358             catch (Exception JavaDoc exception)
359             {
360               throw
361                 new CoreException
362                   (new Status
363                     (IStatus.ERROR, CodeGenEcorePlugin.getPlugin().getBundle().getSymbolicName(), 0, "EMF Error", exception));
364             }
365             finally
366             {
367               progressMonitor.done();
368             }
369           }
370         };
371       workspace.run(runnable, new CodeGenUtil.StreamProgressMonitor(System.out));
372
373       return new Integer JavaDoc(0);
374     }
375     catch (Exception JavaDoc exception)
376     {
377       printGenerateUsage();
378       exception.printStackTrace();
379       CodeGenEcorePlugin.INSTANCE.log(exception);
380       return new Integer JavaDoc(1);
381     }
382   }
383
384   protected String JavaDoc findOrCreateContainerHelper
385     (String JavaDoc rootLocation, String JavaDoc encodedPath, IProgressMonitor progressMonitor) throws CoreException
386   {
387     int index = encodedPath.indexOf("/./");
388     if (encodedPath.endsWith("/.") && index != -1)
389     {
390       IPath modelProjectLocation = new Path(encodedPath.substring(0, index));
391       IPath fragmentPath = new Path(encodedPath.substring(index + 3, encodedPath.length() - 2));
392
393       IPath projectRelativePath = new Path(modelProjectLocation.lastSegment()).append(fragmentPath);
394
395       CodeGenUtil.findOrCreateContainer
396         (projectRelativePath,
397          true,
398          modelProjectLocation,
399          new SubProgressMonitor(progressMonitor, 1));
400
401       return projectRelativePath.makeAbsolute().toString();
402     }
403     else if (rootLocation != null)
404     {
405       // Look for a likely plugin name.
406
//
407
index = encodedPath.indexOf("/org.");
408       if (index == -1)
409       {
410         index = encodedPath.indexOf("/com.");
411       }
412       if (index == -1)
413       {
414         index = encodedPath.indexOf("/javax.");
415       }
416       if (index != -1)
417       {
418         IPath projectRelativePath = new Path(encodedPath.substring(index, encodedPath.length()));
419         index = encodedPath.indexOf("/", index + 5);
420         if (index != -1)
421         {
422           IPath modelProjectLocation = new Path(rootLocation + "/" + encodedPath.substring(0, index));
423   
424           CodeGenUtil.findOrCreateContainer
425             (projectRelativePath,
426              true,
427              modelProjectLocation,
428              new SubProgressMonitor(progressMonitor, 1));
429   
430           return projectRelativePath.makeAbsolute().toString();
431         }
432       }
433     }
434
435     return encodedPath;
436   }
437
438   public static int EMF_MODEL_PROJECT_STYLE = 0x0001;
439   public static int EMF_EDIT_PROJECT_STYLE = 0x0002;
440   public static int EMF_EDITOR_PROJECT_STYLE = 0x0004;
441   public static int EMF_XML_PROJECT_STYLE = 0x0008;
442   public static int EMF_PLUGIN_PROJECT_STYLE = 0x0010;
443   public static int EMF_EMPTY_PROJECT_STYLE = 0x0020;
444   public static int EMF_TESTS_PROJECT_STYLE = 0x0040;
445
446   public static IProject createEMFProject
447     (IPath javaSource,
448      IPath projectLocationPath,
449      List JavaDoc referencedProjects,
450      IProgressMonitor progressMonitor,
451      int style)
452   {
453     return createEMFProject(javaSource, projectLocationPath, referencedProjects, progressMonitor, style, Collections.EMPTY_LIST);
454   }
455
456   public static IProject createEMFProject
457     (IPath javaSource,
458      IPath projectLocationPath,
459      List JavaDoc referencedProjects,
460      IProgressMonitor progressMonitor,
461      int style,
462      List JavaDoc pluginVariables)
463   {
464     String JavaDoc projectName = javaSource.segment(0);
465     IProject project = null;
466     try
467     {
468       List JavaDoc classpathEntries = new UniqueEList();
469
470       progressMonitor.beginTask("", 10);
471       progressMonitor.subTask(CodeGenEcorePlugin.INSTANCE.getString("_UI_CreatingEMFProject_message", new Object JavaDoc [] { projectName }));
472       IWorkspace workspace = ResourcesPlugin.getWorkspace();
473       project = workspace.getRoot().getProject(projectName);
474
475       // Clean up any old project information.
476
//
477
if (!project.exists())
478       {
479         IPath location = projectLocationPath;
480         if (location == null)
481         {
482           location = workspace.getRoot().getLocation().append(projectName);
483         }
484         location = location.append(".project");
485         File JavaDoc projectFile = new File JavaDoc(location.toString());
486         if (projectFile.exists())
487         {
488           projectFile.renameTo(new File JavaDoc(location.toString() + ".old"));
489         }
490       }
491
492       IJavaProject javaProject = JavaCore.create(project);
493       IProjectDescription projectDescription = null;
494       if (!project.exists())
495       {
496         projectDescription = ResourcesPlugin.getWorkspace().newProjectDescription(projectName);
497         projectDescription.setLocation(projectLocationPath);
498         project.create(projectDescription, new SubProgressMonitor(progressMonitor, 1));
499       }
500       else
501       {
502         projectDescription = project.getDescription();
503         classpathEntries.addAll(Arrays.asList(javaProject.getRawClasspath()));
504       }
505
506       boolean isInitiallyEmpty = classpathEntries.isEmpty();
507
508       {
509         if (referencedProjects.size() != 0 && (style & (EMF_PLUGIN_PROJECT_STYLE | EMF_EMPTY_PROJECT_STYLE)) == 0)
510         {
511           projectDescription.setReferencedProjects
512             ((IProject [])referencedProjects.toArray(new IProject [referencedProjects.size()]));
513           for (Iterator JavaDoc i = referencedProjects.iterator(); i.hasNext(); )
514           {
515             IProject referencedProject = (IProject)i.next();
516             IClasspathEntry referencedProjectClasspathEntry = JavaCore.newProjectEntry(referencedProject.getFullPath());
517             classpathEntries.add(referencedProjectClasspathEntry);
518           }
519         }
520
521         String JavaDoc [] natureIds = projectDescription.getNatureIds();
522         if (natureIds == null)
523         {
524           natureIds = new String JavaDoc [] { JavaCore.NATURE_ID };
525         }
526         else
527         {
528           boolean hasJavaNature = false;
529           boolean hasPDENature = false;
530           for (int i = 0; i < natureIds.length; ++i)
531           {
532             if (JavaCore.NATURE_ID.equals(natureIds[i]))
533             {
534               hasJavaNature = true;
535             }
536             if ("org.eclipse.pde.PluginNature".equals(natureIds[i]))
537             {
538               hasPDENature = true;
539             }
540           }
541           if (!hasJavaNature)
542           {
543             String JavaDoc [] oldNatureIds = natureIds;
544             natureIds = new String JavaDoc [oldNatureIds.length + 1];
545             System.arraycopy(oldNatureIds, 0, natureIds, 0, oldNatureIds.length);
546             natureIds[oldNatureIds.length] = JavaCore.NATURE_ID;
547           }
548           if (!hasPDENature)
549           {
550             String JavaDoc [] oldNatureIds = natureIds;
551             natureIds = new String JavaDoc [oldNatureIds.length + 1];
552             System.arraycopy(oldNatureIds, 0, natureIds, 0, oldNatureIds.length);
553             natureIds[oldNatureIds.length] = "org.eclipse.pde.PluginNature";
554           }
555         }
556         projectDescription.setNatureIds(natureIds);
557
558         ICommand [] builders = projectDescription.getBuildSpec();
559         if (builders == null)
560         {
561           builders = new ICommand [0];
562         }
563         boolean hasManifestBuilder = false;
564         boolean hasSchemaBuilder = false;
565         for (int i = 0; i < builders.length; ++i)
566         {
567           if ("org.eclipse.pde.ManifestBuilder".equals(builders[i].getBuilderName()))
568           {
569             hasManifestBuilder = true;
570           }
571           if ("org.eclipse.pde.SchemaBuilder".equals(builders[i].getBuilderName()))
572           {
573             hasSchemaBuilder = true;
574           }
575         }
576         if (!hasManifestBuilder)
577         {
578           ICommand [] oldBuilders = builders;
579           builders = new ICommand [oldBuilders.length + 1];
580           System.arraycopy(oldBuilders, 0, builders, 0, oldBuilders.length);
581           builders[oldBuilders.length] = projectDescription.newCommand();
582           builders[oldBuilders.length].setBuilderName("org.eclipse.pde.ManifestBuilder");
583         }
584         if (!hasSchemaBuilder)
585         {
586           ICommand [] oldBuilders = builders;
587           builders = new ICommand [oldBuilders.length + 1];
588           System.arraycopy(oldBuilders, 0, builders, 0, oldBuilders.length);
589           builders[oldBuilders.length] = projectDescription.newCommand();
590           builders[oldBuilders.length].setBuilderName("org.eclipse.pde.SchemaBuilder");
591         }
592         projectDescription.setBuildSpec(builders);
593
594         project.open(new SubProgressMonitor(progressMonitor, 1));
595         project.setDescription(projectDescription, new SubProgressMonitor(progressMonitor, 1));
596
597         IContainer sourceContainer = project;
598         if (javaSource.segmentCount() > 1)
599         {
600           sourceContainer = project.getFolder(javaSource.removeFirstSegments(1).makeAbsolute());
601           if (!sourceContainer.exists())
602           {
603             ((IFolder)sourceContainer).create(false, true, new SubProgressMonitor(progressMonitor, 1));
604           }
605         }
606
607         if (isInitiallyEmpty)
608         {
609           IClasspathEntry sourceClasspathEntry =
610             JavaCore.newSourceEntry(javaSource);
611           for (Iterator JavaDoc i = classpathEntries.iterator(); i.hasNext(); )
612           {
613             IClasspathEntry classpathEntry = (IClasspathEntry)i.next();
614             if (classpathEntry.getPath().isPrefixOf(javaSource))
615             {
616               i.remove();
617             }
618           }
619           classpathEntries.add(0, sourceClasspathEntry);
620
621           IClasspathEntry jreClasspathEntry =
622             JavaCore.newVariableEntry
623               (new Path(JavaRuntime.JRELIB_VARIABLE), new Path(JavaRuntime.JRESRC_VARIABLE), new Path(JavaRuntime.JRESRCROOT_VARIABLE));
624           for (Iterator JavaDoc i = classpathEntries.iterator(); i.hasNext(); )
625           {
626             IClasspathEntry classpathEntry = (IClasspathEntry)i.next();
627             if (classpathEntry.getPath().isPrefixOf(jreClasspathEntry.getPath()))
628             {
629               i.remove();
630             }
631           }
632
633           classpathEntries.add(JavaCore.newContainerEntry(new Path("org.eclipse.jdt.launching.JRE_CONTAINER")));
634         }
635
636         if ((style & EMF_EMPTY_PROJECT_STYLE) == 0)
637         {
638           if ((style & EMF_PLUGIN_PROJECT_STYLE) != 0)
639           {
640             classpathEntries.add(JavaCore.newContainerEntry(new Path("org.eclipse.pde.core.requiredPlugins")));
641
642             // Remove variables since the plugin.xml should provide the complete path information.
643
//
644
for (Iterator JavaDoc i = classpathEntries.iterator(); i.hasNext(); )
645             {
646               IClasspathEntry classpathEntry = (IClasspathEntry)i.next();
647               if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_VARIABLE &&
648                     !JavaRuntime.JRELIB_VARIABLE.equals(classpathEntry.getPath().toString()) ||
649                     classpathEntry.getEntryKind() == IClasspathEntry.CPE_PROJECT)
650               {
651                 i.remove();
652               }
653             }
654           }
655           else
656           {
657             CodeGenUtil.addClasspathEntries(classpathEntries, "ECLIPSE_CORE_RUNTIME", "org.eclipse.core.runtime");
658             CodeGenUtil.addClasspathEntries(classpathEntries, "ECLIPSE_CORE_RESOURCES", "org.eclipse.core.resources");
659             CodeGenUtil.addClasspathEntries(classpathEntries, "EMF_COMMON", "org.eclipse.emf.common");
660             CodeGenUtil.addClasspathEntries(classpathEntries, "EMF_ECORE", "org.eclipse.emf.ecore");
661
662             if ((style & EMF_XML_PROJECT_STYLE) != 0)
663             {
664               CodeGenUtil.addClasspathEntries(classpathEntries, "EMF_ECORE_XMI", "org.eclipse.emf.ecore.xmi");
665             }
666
667             if ((style & EMF_MODEL_PROJECT_STYLE) == 0)
668             {
669               CodeGenUtil.addClasspathEntries(classpathEntries, "EMF_EDIT", "org.eclipse.emf.edit");
670
671               if ((style & EMF_EDIT_PROJECT_STYLE) == 0)
672               {
673                 CodeGenUtil.addClasspathEntries(classpathEntries, "ECLIPSE_SWT", "org.eclipse.swt");
674                 CodeGenUtil.addClasspathEntries(classpathEntries, "ECLIPSE_JFACE", "org.eclipse.jface");
675                 CodeGenUtil.addClasspathEntries(classpathEntries, "ECLIPSE_UI_VIEWS", "org.eclipse.ui.views");
676                 CodeGenUtil.addClasspathEntries(classpathEntries, "ECLIPSE_UI_EDITORS", "org.eclipse.ui.editors");
677                 CodeGenUtil.addClasspathEntries(classpathEntries, "ECLIPSE_UI_IDE", "org.eclipse.ui.ide");
678                 CodeGenUtil.addClasspathEntries(classpathEntries, "ECLIPSE_UI_WORKBENCH", "org.eclipse.ui.workbench");
679                 CodeGenUtil.addClasspathEntries(classpathEntries, "EMF_COMMON_UI", "org.eclipse.emf.common.ui");
680                 CodeGenUtil.addClasspathEntries(classpathEntries, "EMF_EDIT_UI", "org.eclipse.emf.edit.ui");
681                 if ((style & EMF_XML_PROJECT_STYLE) == 0)
682                 {
683                   CodeGenUtil.addClasspathEntries(classpathEntries, "EMF_ECORE_XMI", "org.eclipse.emf.ecore.xmi");
684                 }
685               }
686             }
687
688             if ((style & EMF_TESTS_PROJECT_STYLE) != 0)
689             {
690               CodeGenUtil.addClasspathEntries(classpathEntries, "JUNIT", "org.junit");
691             }
692
693             if (pluginVariables != null)
694             {
695               for (Iterator JavaDoc i = pluginVariables.iterator(); i.hasNext(); )
696               {
697                 Object JavaDoc variable = i.next();
698                 if (variable instanceof IClasspathEntry)
699                 {
700                   classpathEntries.add(variable);
701                 }
702                 else if (variable instanceof String JavaDoc)
703                 {
704                   String JavaDoc pluginVariable = (String JavaDoc)variable;
705                   String JavaDoc name;
706                   String JavaDoc id;
707                   int index = pluginVariable.indexOf("=");
708                   if (index == -1)
709                   {
710                     name = pluginVariable.replace('.','_').toUpperCase();
711                     id = pluginVariable;
712                   }
713                   else
714                   {
715                     name = pluginVariable.substring(0, index);
716                     id = pluginVariable.substring(index + 1);
717                   }
718                   CodeGenUtil.addClasspathEntries(classpathEntries, name, id);
719                 }
720               }
721             }
722           }
723         }
724
725         javaProject.setRawClasspath
726           ((IClasspathEntry [])classpathEntries.toArray(new IClasspathEntry [classpathEntries.size()]),
727            new SubProgressMonitor(progressMonitor, 1));
728       }
729
730       if (isInitiallyEmpty)
731       {
732         javaProject.setOutputLocation(new Path("/" + javaSource.segment(0) + "/bin"), new SubProgressMonitor(progressMonitor, 1));
733       }
734     }
735     catch (Exception JavaDoc exception)
736     {
737       exception.printStackTrace();
738       CodeGenEcorePlugin.INSTANCE.log(exception);
739     }
740     finally
741     {
742       progressMonitor.done();
743     }
744
745     return project;
746   }
747
748   public void printStatus(String JavaDoc prefix, IStatus status)
749   {
750     System.err.print(prefix);
751     System.err.println(status.getMessage());
752     IStatus [] children = status.getChildren();
753     String JavaDoc childPrefix = " " + prefix;
754     for (int i = 0; i < children.length; ++i)
755     {
756       printStatus(childPrefix, children[i]);
757     }
758   }
759
760   public static void setSDODefaults(GenModel genModel)
761   {
762     genModel.setRootExtendsInterface("");
763     genModel.setRootImplementsInterface("org.eclipse.emf.ecore.sdo.InternalEDataObject");
764     genModel.setRootExtendsClass("org.eclipse.emf.ecore.sdo.impl.EDataObjectImpl");
765     genModel.setFeatureMapWrapperInterface("commonj.sdo.Sequence");
766     genModel.setFeatureMapWrapperInternalInterface("org.eclipse.emf.ecore.sdo.util.ESequence");
767     genModel.setFeatureMapWrapperClass("org.eclipse.emf.ecore.sdo.util.BasicESequence");
768     genModel.setSuppressEMFTypes(true);
769
770     genModel.getModelPluginVariables().add("EMF_COMMONJ_SDO=org.eclipse.emf.commonj.sdo");
771     genModel.getModelPluginVariables().add("EMF_ECORE_SDO=org.eclipse.emf.ecore.sdo");
772
773     genModel.getStaticPackages().add("http://www.eclipse.org/emf/2003/SDO");
774   }
775   
776   /**
777    * This parses a code formatter profile file, recording the options it sepecifies in a map.
778    */

779   static class CodeFormatterProfileParser extends DefaultHandler JavaDoc
780   {
781     private Map JavaDoc options = null;
782
783     private String JavaDoc SETTING = "setting";
784     private String JavaDoc ID = "id";
785     private String JavaDoc VALUE = "value";
786     private String JavaDoc EMPTY = "";
787
788     public void startDocument()
789     {
790       options = new HashMap JavaDoc();
791     }
792
793     public void startElement(String JavaDoc namespaceURI, String JavaDoc localName, String JavaDoc qualifiedName, Attributes JavaDoc atts)
794     {
795       if (EMPTY.equals(namespaceURI) && SETTING.equals(localName))
796       {
797         String JavaDoc id = atts.getValue(EMPTY, ID);
798         String JavaDoc value = atts.getValue(EMPTY, VALUE);
799
800         if (id != null && value != null)
801         {
802           options.put(id, value);
803         }
804       }
805     }
806
807    public Map JavaDoc getOptions()
808    {
809      return options;
810    }
811
812    public static Map JavaDoc parse(String JavaDoc systemID)
813    {
814      try
815      {
816        XMLReader JavaDoc parser = XMLReaderFactory.createXMLReader();
817        CodeFormatterProfileParser handler = new CodeFormatterProfileParser();
818        parser.setContentHandler(handler);
819        parser.parse(systemID);
820        return handler.getOptions();
821      }
822      catch (Exception JavaDoc e)
823      {
824      }
825      return null;
826    }
827   }
828 }
829
Popular Tags