KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > emf > importer > ModelImporter


1 /**
2  * <copyright>
3  *
4  * Copyright (c) 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: ModelImporter.java,v 1.18 2005/06/28 23:55:17 marcelop Exp $
16  */

17 package org.eclipse.emf.importer;
18
19 import java.io.File JavaDoc;
20 import java.util.ArrayList JavaDoc;
21 import java.util.Collection JavaDoc;
22 import java.util.Collections JavaDoc;
23 import java.util.HashMap JavaDoc;
24 import java.util.HashSet JavaDoc;
25 import java.util.Iterator JavaDoc;
26 import java.util.List JavaDoc;
27 import java.util.Map JavaDoc;
28 import java.util.Set JavaDoc;
29 import java.util.StringTokenizer JavaDoc;
30
31 import org.eclipse.core.resources.IFile;
32 import org.eclipse.core.resources.IProject;
33 import org.eclipse.core.resources.IResource;
34 import org.eclipse.core.resources.IWorkspace;
35 import org.eclipse.core.resources.IWorkspaceRoot;
36 import org.eclipse.core.resources.ResourcesPlugin;
37 import org.eclipse.core.runtime.IPath;
38 import org.eclipse.core.runtime.IProgressMonitor;
39 import org.eclipse.core.runtime.IStatus;
40 import org.eclipse.core.runtime.Path;
41 import org.eclipse.core.runtime.Platform;
42 import org.eclipse.core.runtime.Status;
43
44 import org.eclipse.emf.codegen.ecore.Generator;
45 import org.eclipse.emf.codegen.ecore.genmodel.GenModel;
46 import org.eclipse.emf.codegen.ecore.genmodel.GenModelFactory;
47 import org.eclipse.emf.codegen.ecore.genmodel.GenPackage;
48 import org.eclipse.emf.codegen.util.CodeGenUtil;
49 import org.eclipse.emf.common.CommonPlugin;
50 import org.eclipse.emf.common.util.AbstractTreeIterator;
51 import org.eclipse.emf.common.util.TreeIterator;
52 import org.eclipse.emf.common.util.URI;
53 import org.eclipse.emf.common.util.UniqueEList;
54 import org.eclipse.emf.ecore.EPackage;
55 import org.eclipse.emf.ecore.plugin.EcorePlugin;
56 import org.eclipse.emf.ecore.resource.Resource;
57 import org.eclipse.emf.ecore.resource.ResourceSet;
58 import org.eclipse.emf.importer.util.ImporterUtil;
59
60
61 /**
62  * @since 2.1.0
63  */

64 public abstract class ModelImporter
65 {
66   public static class EPackageList extends UniqueEList.FastCompare
67   {
68     public EPackageList()
69     {
70       super();
71     }
72
73     public EPackageList(Collection JavaDoc collection)
74     {
75       super(collection);
76     }
77
78     public EPackageList(int initialCapacity)
79     {
80       super(initialCapacity);
81     }
82
83     protected Object JavaDoc[] newData(int capacity)
84     {
85       return new EPackage [capacity];
86     }
87   }
88
89   public static class GenPackageList extends UniqueEList.FastCompare
90   {
91     public GenPackageList()
92     {
93       super();
94     }
95
96     public GenPackageList(Collection JavaDoc collection)
97     {
98       super(collection);
99     }
100
101     public GenPackageList(int initialCapacity)
102     {
103       super(initialCapacity);
104     }
105
106     protected Object JavaDoc[] newData(int capacity)
107     {
108       return new GenPackage [capacity];
109     }
110   }
111
112   public static class EPackageInfo
113   {
114     protected boolean generate = false;
115     protected String JavaDoc ecoreFileName;
116     protected String JavaDoc basePackage;
117     protected String JavaDoc prefix;
118
119     public String JavaDoc getBasePackage()
120     {
121       return basePackage;
122     }
123
124     public void setBasePackage(String JavaDoc basePackage)
125     {
126       this.basePackage = basePackage;
127     }
128
129     public String JavaDoc getEcoreFileName()
130     {
131       return ecoreFileName;
132     }
133
134     public void setEcoreFileName(String JavaDoc ecoreFileName)
135     {
136       this.ecoreFileName = ecoreFileName;
137     }
138
139     public boolean isGenerate()
140     {
141       return generate;
142     }
143
144     public void setGenerate(boolean generate)
145     {
146       this.generate = generate;
147     }
148
149     public String JavaDoc getPrefix()
150     {
151       return prefix;
152     }
153
154     public void setPrefix(String JavaDoc prefix)
155     {
156       this.prefix = prefix;
157     }
158   }
159   
160   protected static class ShellFinder
161   {
162     public Object JavaDoc getActiveShell()
163     {
164       Object JavaDoc shell = null;
165       try
166       {
167         shell = org.eclipse.swt.widgets.Display.getCurrent().getActiveShell();
168       }
169       catch (Throwable JavaDoc t)
170       {
171       }
172       return shell;
173     }
174   }
175
176   protected List JavaDoc fileExtensions;
177
178   protected IPath originalGenModelPath;
179   protected GenModel originalGenModel;
180
181   protected IPath genModelProjectLocation;
182   protected IPath genModelContainerPath;
183   protected String JavaDoc genModelFileName;
184   protected IPath genModelPath;
185   protected GenModel genModel;
186
187   protected List JavaDoc ePackages;
188   protected Map JavaDoc ePackageToInfoMap;
189
190   protected List JavaDoc referencedGenPackages;
191
192   protected List JavaDoc modelLocationURIs;
193   protected String JavaDoc modelLocation;
194
195   protected String JavaDoc modelPluginID;
196   protected String JavaDoc modelPluginDirectory;
197
198   protected boolean usePlatformURI = true;
199   protected IWorkspaceRoot workspaceRoot;
200   
201   protected ResourceSet externalGenModelResourceSet;
202   protected List JavaDoc externalGenModelList;
203
204   public void dispose()
205   {
206     genModel = null;
207     originalGenModel = null;
208     workspaceRoot = null;
209
210     if (referencedGenPackages != null)
211     {
212       referencedGenPackages.clear();
213       referencedGenPackages = null;
214     }
215     clearEPackagesCollections();
216   }
217
218   public abstract String JavaDoc getID();
219
220   public List JavaDoc getFileExtensions()
221   {
222     if (fileExtensions == null)
223     {
224       fileExtensions = new ArrayList JavaDoc();
225     }
226     return fileExtensions;
227   }
228
229   public boolean usePlatformURI()
230   {
231     return usePlatformURI;
232   }
233
234   public void setUsePlatformURI(boolean usePlatformURI)
235   {
236     this.usePlatformURI = usePlatformURI;
237   }
238
239   public void defineOriginalGenModelPath(IPath path)
240   {
241     if (getOriginalGenModelPath() == null)
242     {
243       originalGenModelPath = path;
244       if (getOriginalGenModelPath() != null)
245       {
246         URI genModelURI = createFileURI(getOriginalGenModelPath().toString());
247         loadOriginalGenModel(genModelURI);
248       }
249     }
250   }
251
252   public IPath getOriginalGenModelPath()
253   {
254     return originalGenModelPath;
255   }
256
257   protected List JavaDoc computeEPackagesBeingReloaded()
258   {
259     if (getOriginalGenModel() != null)
260     {
261       List JavaDoc ePackages = new EPackageList();
262       for (Iterator JavaDoc i = getOriginalGenModel().getGenPackages().iterator(); i.hasNext();)
263       {
264         GenPackage genPackage = (GenPackage)i.next();
265         EPackage originalEPackage = genPackage.getEcorePackage();
266         String JavaDoc nsURI = originalEPackage.getNsURI();
267         if (nsURI != null)
268         {
269           for (Iterator JavaDoc j = getEPackages().iterator(); j.hasNext();)
270           {
271             EPackage ePackage = (EPackage)j.next();
272             if (nsURI.equals(ePackage.getNsURI()))
273             {
274               ePackages.add(ePackage);
275               break;
276             }
277           }
278         }
279       }
280       return ePackages;
281     }
282     else
283     {
284       return Collections.EMPTY_LIST;
285     }
286   }
287
288   public void setGenModelFileName(String JavaDoc name)
289   {
290     genModelFileName = name == null || name.trim().length() == 0 ? null : name;
291     genModelPath = null;
292   }
293
294   public String JavaDoc getGenModelFileName()
295   {
296     return genModelFileName;
297   }
298   
299   public String JavaDoc computeDefaultGenModelFileName()
300   {
301     List JavaDoc modelLocationURIs = getModelLocationURIs();
302     if (!modelLocationURIs.isEmpty())
303     {
304       URI modelURI = (URI)modelLocationURIs.get(0);
305       String JavaDoc name = URI.decode(modelURI.lastSegment());
306       int index = name.lastIndexOf('.');
307       return (index >= 0 ? name.substring(0, index) : name) + ".genmodel";
308     }
309     return null;
310   }
311
312   public IStatus checkGenModelFileName()
313   {
314     String JavaDoc message = null;
315     String JavaDoc name = getGenModelFileName();
316     if (name == null || name.trim().length() == 0)
317     {
318       message = ImporterPlugin.INSTANCE.getString("_UI_GeneratorModelFileNameCannotBeEmpty_message");
319     }
320     else if (!name.endsWith(".genmodel"))
321     {
322       message = ImporterPlugin.INSTANCE.getString("_UI_GeneratorModelFileNameMustEndWithGenModel_message");
323     }
324
325     if (message == null)
326     {
327       return Status.OK_STATUS;
328     }
329     else
330     {
331       return new Status(IStatus.ERROR, ImporterPlugin.ID, ImporterUtil.ACTION_DEFAULT, message, null);
332     }
333   }
334
335   public IStatus checkEcoreModelFileName(String JavaDoc fileName, String JavaDoc packageName)
336   {
337     String JavaDoc message = null;
338
339     if (fileName == null || fileName.equals(""))
340     {
341       message = packageName == null ?
342         ImporterPlugin.INSTANCE.getString("_UI_EcoreModelFileNameCannotBeEmpty_message") :
343         ImporterPlugin.INSTANCE.getString("_UI_EcoreModelFileNameForPackageCannotBeEmpty_message", new Object JavaDoc []{ packageName });
344     }
345     else if (!fileName.endsWith(".ecore"))
346     {
347       message = packageName == null ?
348         ImporterPlugin.INSTANCE.getString("_UI_EcoreModelFileNameMustEndWithEcore_message") :
349         ImporterPlugin.INSTANCE.getString("_UI_EcoreModelFileNameForPackageMustEndWithEcore_message", new Object JavaDoc []{ packageName });
350     }
351     if (message == null)
352     {
353       return Status.OK_STATUS;
354     }
355     else
356     {
357       return new Status(IStatus.ERROR, ImporterPlugin.ID, ImporterUtil.ACTION_DEFAULT, message, null);
358     }
359   }
360
361   public void setGenModelProjectLocation(IPath genModelProjectLocation)
362   {
363     this.genModelProjectLocation = genModelProjectLocation;
364   }
365
366   public IPath getGenModelProjectLocation()
367   {
368     return genModelProjectLocation;
369   }
370   
371   public void setGenModelContainerPath(IPath path)
372   {
373     genModelContainerPath = path;
374     genModelPath = null;
375   }
376
377   public IPath getGenModelContainerPath()
378   {
379     return genModelContainerPath;
380   }
381   
382   public IPath computeGenModelContainerPath(IPath projectPath)
383   {
384     return projectPath == null ? null : projectPath.append(getGenModelDefaultFolderPath());
385   }
386
387   protected IPath getGenModelDefaultFolderPath()
388   {
389     return new Path("model");
390   }
391
392   public IPath getGenModelPath()
393   {
394     if (genModelPath == null && getGenModelFileName() != null && getGenModelContainerPath() != null)
395     {
396       genModelPath = getGenModelContainerPath().append(getGenModelFileName());
397     }
398     return genModelPath;
399   }
400
401   public GenModel getGenModel()
402   {
403     if (genModel == null)
404     {
405       genModel = GenModelFactory.eINSTANCE.createGenModel();
406       genModel.setImporterID(getID());
407     }
408     return genModel;
409   }
410
411   public boolean addGenModelToResource(boolean replace)
412   {
413     GenModel genModel = getGenModel();
414     if (replace || genModel.eResource() == null)
415     {
416       IPath genModelPath = getGenModelPath();
417       if (genModelPath != null)
418       {
419         URI genModelURI = createFileURI(genModelPath.toString());
420         Resource genModelResource = createResourceSet().createResource(genModelURI);
421         genModelResource.getContents().add(genModel);
422         return true;
423       }
424     }
425     return false;
426   }
427
428   public ResourceSet getGenModelResourceSet()
429   {
430     Resource resource = getGenModel().eResource();
431     if (resource == null && addGenModelToResource(false))
432     {
433       resource = getGenModel().eResource();
434     }
435
436     if (resource != null)
437     {
438       return resource.getResourceSet();
439     }
440     else
441     {
442       return null;
443     }
444   }
445
446   protected GenModel getOriginalGenModel()
447   {
448     return originalGenModel;
449   }
450
451   public List JavaDoc getEPackages()
452   {
453     if (ePackages == null)
454     {
455       ePackages = new EPackageList();
456     }
457     return ePackages;
458   }
459
460   protected Map JavaDoc getEPackageToInfoMap()
461   {
462     if (ePackageToInfoMap == null)
463     {
464       ePackageToInfoMap = new HashMap JavaDoc();
465     }
466     return ePackageToInfoMap;
467   }
468
469   public EPackageInfo getEPackageInfo(EPackage ePackage)
470   {
471     EPackageInfo ePackageInfo = (EPackageInfo)getEPackageToInfoMap().get(ePackage);
472     if (ePackageInfo == null)
473     {
474       ePackageInfo = new EPackageInfo();
475       getEPackageToInfoMap().put(ePackage, ePackageInfo);
476     }
477     return ePackageInfo;
478   }
479
480   public List JavaDoc getReferencedGenPackages()
481   {
482     if (referencedGenPackages == null)
483     {
484       referencedGenPackages = new GenPackageList();
485     }
486     return referencedGenPackages;
487   }
488
489   protected GenPackage getGenPackage(EPackage ePackage)
490   {
491     if (getOriginalGenModel() != null && !getOriginalGenModel().getGenPackages().isEmpty())
492     {
493       for (Iterator JavaDoc i = getOriginalGenModel().getGenPackages().iterator(); i.hasNext();)
494       {
495         GenPackage referencedGenPackage = (GenPackage)i.next();
496         if (referencedGenPackage.getEcorePackage() != null && referencedGenPackage.getEcorePackage().getNsURI().equals(ePackage.getNsURI()))
497         {
498           return referencedGenPackage;
499         }
500       }
501     }
502     return null;
503   }
504
505   public void setModelLocation(String JavaDoc location)
506   {
507     modelLocation = location == null || location.trim().length() == 0 ? null : location;
508     modelLocationURIs = null;
509   }
510
511   public String JavaDoc getModelLocation()
512   {
513     return modelLocation;
514   }
515
516   public List JavaDoc getModelLocationURIs()
517   {
518     if (getModelLocation() == null)
519     {
520       return Collections.EMPTY_LIST;
521     }
522     else if (modelLocationURIs == null)
523     {
524       modelLocationURIs = new ArrayList JavaDoc();
525       for (StringTokenizer JavaDoc stringTokenizer = new StringTokenizer JavaDoc(getModelLocation()); stringTokenizer.hasMoreTokens();)
526       {
527         String JavaDoc uri = stringTokenizer.nextToken();
528         modelLocationURIs.add(URI.createURI(uri));
529       }
530     }
531     return modelLocationURIs;
532   }
533   
534   public URI getFirstModelLocationURI(boolean resolve)
535   {
536     List JavaDoc modelLocationURIs = getModelLocationURIs();
537     if (!modelLocationURIs.isEmpty())
538     {
539       URI modelLocationURI = (URI)modelLocationURIs.get(0);
540       return resolve ? CommonPlugin.resolve(modelLocationURI) : modelLocationURI;
541     }
542     return null;
543   }
544
545   public void setModelFile(IFile file)
546   {
547     if (file != null)
548     {
549       URI modelURI = URI.createPlatformResourceURI(file.getFullPath().toString(), true);
550       setModelLocation(modelURI.toString());
551     }
552     else
553     {
554       setModelLocation(null);
555     }
556   }
557
558   public EPackage getReferredEPackage(GenPackage genPackage)
559   {
560     String JavaDoc nsURI = genPackage.getEcorePackage().getNsURI();
561     if (nsURI != null)
562     {
563       for (Iterator JavaDoc j = ePackages.iterator(); j.hasNext();)
564       {
565         EPackage ePackage = (EPackage)j.next();
566         if (nsURI.equals(ePackage.getNsURI()))
567         {
568           return ePackage;
569         }
570       }
571     }
572     return null;
573   }
574
575   public List JavaDoc filterReferencedEPackages(Collection JavaDoc ePackages)
576   {
577     if (ePackages.isEmpty())
578     {
579       return Collections.EMPTY_LIST;
580     }
581     else if (getReferencedGenPackages().isEmpty())
582     {
583       return new ArrayList JavaDoc(ePackages);
584     }
585     else
586     {
587       List JavaDoc filteredEPackages = new EPackageList(ePackages);
588       for (Iterator JavaDoc i = getReferencedGenPackages().iterator(); i.hasNext();)
589       {
590         GenPackage genPackage = (GenPackage)i.next();
591         EPackage ePackage = getReferredEPackage(genPackage);
592         if (ePackage != null)
593         {
594           filteredEPackages.remove(ePackage);
595         }
596       }
597       return filteredEPackages;
598     }
599   }
600   
601   public List JavaDoc getExternalGenModels()
602   {
603     if (externalGenModelList == null)
604     {
605       externalGenModelList = new UniqueEList.FastCompare();
606       if (externalGenModelResourceSet == null)
607       {
608         externalGenModelResourceSet = getOriginalGenModel() != null ? getOriginalGenModel().eResource().getResourceSet() : createResourceSet();
609       }
610       Map JavaDoc ePackageToGenModelMap = EcorePlugin.getEPackageNsURIToGenModelLocationMap();
611       for (Iterator JavaDoc i = getEPackages().iterator(); i.hasNext(); )
612       {
613         EPackage ePackage = (EPackage)i.next();
614         URI genModelURI = (URI)ePackageToGenModelMap.get(ePackage.getNsURI());
615         if (genModelURI != null)
616         {
617           try
618           {
619             Resource genModelResource = externalGenModelResourceSet.getResource(genModelURI, false);
620             if (genModelResource == null)
621             {
622               genModelResource = externalGenModelResourceSet.getResource(genModelURI, true);
623               externalGenModelList.add(genModelResource.getContents().get(0));
624             }
625           }
626           catch (Exception JavaDoc exception)
627           {
628             ImporterPlugin.INSTANCE.log(exception);
629           }
630         }
631       }
632     }
633     return externalGenModelList;
634   }
635   
636   public ResourceSet createResourceSet()
637   {
638     return ImporterUtil.createResourceSet();
639   }
640
641   protected void loadOriginalGenModel(URI genModelURI)
642   {
643     Resource resource = createResourceSet().getResource(genModelURI, true);
644     originalGenModel = (GenModel)resource.getContents().get(0);
645
646     if (getOriginalGenModel() != null)
647     {
648       getOriginalGenModel().reconcile();
649       setGenModelFileName(getOriginalGenModelPath().lastSegment());
650       setGenModelContainerPath(getOriginalGenModelPath().removeLastSegments(1));
651       genModelPath = getOriginalGenModelPath();
652     }
653
654     for (Iterator JavaDoc i = getOriginalGenModel().getUsedGenPackages().iterator(); i.hasNext();)
655     {
656       GenPackage referencedGenPackage = (GenPackage)i.next();
657       getReferencedGenPackages().add(referencedGenPackage);
658     }
659   }
660
661   public IStatus computeEPackages(IProgressMonitor progressMonitor) throws Exception JavaDoc
662   {
663     clearEPackagesCollections();
664     IStatus status = doComputeEPackages(progressMonitor);
665     presetEPackagesToGenerate();
666     return status;
667   }
668   
669   protected void presetEPackagesToGenerate()
670   {
671     int size = getEPackages().size();
672     if (size == 1)
673     {
674       getEPackageInfo((EPackage)getEPackages().get(0)).setGenerate(true);
675     }
676     else if (size > 1)
677     {
678       List JavaDoc ePackagesBeingReloaded = computeEPackagesBeingReloaded();
679       for (Iterator JavaDoc i = ePackagesBeingReloaded.iterator(); i.hasNext();)
680       {
681         getEPackageInfo((EPackage)i.next()).setGenerate(true);
682       }
683     }
684   }
685
686   protected IStatus doComputeEPackages(IProgressMonitor progressMonitor) throws Exception JavaDoc
687   {
688     return Status.OK_STATUS;
689   }
690
691   public void clearEPackagesCollections()
692   {
693     if (ePackages != null)
694     {
695       ePackages.clear();
696       ePackages = null;
697     }
698     if (ePackageToInfoMap != null)
699     {
700       ePackageToInfoMap.clear();
701       ePackageToInfoMap = null;
702     }
703     if (externalGenModelList != null)
704     {
705       externalGenModelList.clear();
706       externalGenModelList = null;
707     }
708   }
709
710   public void adjustEPackages(IProgressMonitor progressMonitor)
711   {
712     TreeIterator ePackagesIterator = new AbstractTreeIterator(getEPackages(), false)
713     {
714       protected Iterator JavaDoc getChildren(Object JavaDoc object)
715       {
716         return object instanceof Collection JavaDoc ?
717           ((Collection JavaDoc)object).iterator() :
718           ((EPackage)object).getESubpackages().iterator();
719       }
720     };
721     
722     while (ePackagesIterator.hasNext())
723     {
724       EPackage ePackage = (EPackage)ePackagesIterator.next();
725       adjustEPackage(progressMonitor, ePackage);
726     }
727     
728     makeEcoreFileNamesUnique();
729   }
730
731   protected void adjustEPackage(IProgressMonitor progressMonitor, EPackage ePackage)
732   {
733     EPackageInfo ePackageInfo = getEPackageInfo(ePackage);
734
735     String JavaDoc name = ePackage.getName();
736     int index = name.lastIndexOf(".");
737     if (index != -1)
738     {
739       String JavaDoc basePackage = ePackageInfo.getBasePackage();
740       String JavaDoc namePackage = name.substring(0, index);
741       name = name.substring(index + 1);
742       
743       if (basePackage != null && !namePackage.startsWith(basePackage))
744       {
745         namePackage = basePackage + "." + namePackage;
746       }
747       ePackageInfo.setBasePackage(namePackage);
748       ePackage.setName(name);
749     }
750
751     if (ePackageInfo.getPrefix() == null)
752     {
753       ePackageInfo.setPrefix(CodeGenUtil.capName(name));
754     }
755
756     if (ePackageInfo.getEcoreFileName() == null)
757     {
758       String JavaDoc ecoreFileName = null;
759       GenPackage genPackage = getGenPackage(ePackage);
760       if (genPackage != null)
761       {
762         String JavaDoc ePackagePath = genPackage.getEcorePackage().eResource().getURI().lastSegment();
763         ecoreFileName = URI.decode(ePackagePath);
764       }
765       else
766       {
767         ecoreFileName = ePackage.eResource() == null ? name + ".ecore" : ePackage.eResource().getURI().lastSegment();
768       }
769       ePackageInfo.setEcoreFileName(ecoreFileName);
770     }
771   }
772
773   protected IWorkspaceRoot getWorkspaceRoot()
774   {
775     if (workspaceRoot == null)
776     {
777       workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
778     }
779     return workspaceRoot;
780   }
781
782   public void prepareGenModelAndEPackages(IProgressMonitor progressMonitor)
783   {
784     ResourceSet resourceSet = getGenModelResourceSet();
785     
786     resourceSet.getURIConverter().getURIMap().remove(URI.createPlatformResourceURI(getModelProjectName() + "/"));
787
788     // Create resources for all the root EPackages.
789
//
790
List JavaDoc ePackages = computeEPackagesToGenerate();
791     for (Iterator JavaDoc i = ePackages.iterator(); i.hasNext();)
792     {
793       EPackage ePackage = (EPackage)i.next();
794       addToResource(ePackage, resourceSet);
795     }
796
797     // Create resources for all the referenced EPackages
798
// The referencedEPackage is a "local" instance of the realEPackage. We
799
// will add the former o a resource that has the same URI of the later.
800
for (Iterator JavaDoc i = getReferencedGenPackages().iterator(); i.hasNext();)
801     {
802       GenPackage genPackage = (GenPackage)i.next();
803       EPackage realEPackage = genPackage.getEcorePackage();
804       EPackage referredEPackage = getReferredEPackage(genPackage);
805       if (referredEPackage != null)
806       {
807         URI ecoreURI = realEPackage.eResource().getURI();
808         Resource resource = resourceSet.createResource(ecoreURI);
809         resource.getContents().add(referredEPackage);
810       }
811     }
812
813     // Initialize the GenModel with all the computed data.
814
//
815
getGenModel().initialize(ePackages);
816     getGenModel().getUsedGenPackages().addAll(getReferencedGenPackages());
817     traverseGenPackages(getGenModel().getGenPackages());
818     adjustGenModel(progressMonitor);
819
820     // Restore all configured settings from the original.
821
//
822
getGenModel().reconcile(getOriginalGenModel());
823   }
824   
825   public void addToResource(EPackage ePackage, ResourceSet resourceSet)
826   {
827     if (ePackage.eResource() == null)
828     {
829       EPackageInfo ePackageInfo = getEPackageInfo(ePackage);
830       String JavaDoc fileName = ePackageInfo.getEcoreFileName();
831       if (fileName != null)
832       {
833         String JavaDoc baseLocation = getGenModelPath().removeLastSegments(1).toString() + "/";
834         String JavaDoc ecoreFileName = baseLocation + fileName;
835         URI ecoreURI = createFileURI(ecoreFileName);
836         Resource resource = resourceSet.getResource(ecoreURI, false);
837         if (resource == null)
838         {
839           resource = resourceSet.createResource(ecoreURI);
840         }
841         resource.getContents().add(ePackage);
842       }
843     }
844   }
845
846   public void saveGenModelAndEPackages(IProgressMonitor progressMonitor) throws Exception JavaDoc
847   {
848     String JavaDoc projectName = getModelProjectName();
849     IProject project = getWorkspaceRoot().getProject(projectName);
850     if (!project.exists())
851     {
852       Set JavaDoc referencedGenModels = new HashSet JavaDoc();
853       for (Iterator JavaDoc i = getGenModel().getUsedGenPackages().iterator(); i.hasNext();)
854       {
855         GenPackage genPackage = (GenPackage)i.next();
856         referencedGenModels.add(genPackage.getGenModel());
857       }
858       createProject(progressMonitor, project, referencedGenModels);
859     }
860
861     
862     List JavaDoc resources = computeResourcesToBeSaved();
863     String JavaDoc readOnlyFiles = validateFiles(resources);
864     if (readOnlyFiles != null)
865     {
866       throw new Exception JavaDoc(ImporterPlugin.INSTANCE.getString("_UI_ReadOnlyFiles_error", new String JavaDoc[]{readOnlyFiles}));
867     }
868     
869     for (Iterator JavaDoc i = resources.iterator(); i.hasNext();)
870     {
871       Resource resource = (Resource)i.next();
872       resource.save(getGenmodelSaveOptions());
873     }
874   }
875   
876   protected List JavaDoc computeResourcesToBeSaved()
877   {
878     List JavaDoc resources = new UniqueEList.FastCompare();
879     Resource genModelResource = getGenModel().eResource();
880     resources.add(genModelResource);
881     for (Iterator JavaDoc i = getGenModel().getGenPackages().iterator(); i.hasNext();)
882     {
883       GenPackage genPackage = (GenPackage)i.next();
884       resources.add(genPackage.getEcorePackage().eResource());
885     }
886     
887     // Handle application genmodel stub
888
//
889
for (Iterator JavaDoc i = getGenModel().getUsedGenPackages().iterator(); i.hasNext();)
890     {
891       GenPackage genPackage = (GenPackage)i.next();
892       if (genPackage.eResource() == genModelResource)
893       {
894         resources.add(genPackage.getEcorePackage().eResource());
895       }
896     }
897     
898     return resources;
899   }
900   
901   /**
902    * Invokes the Platform validateEdit method for all the read-only files
903    * referred by a given resource in the list. Returns null if the resources
904    * can be saved or a comma separated list of the files that are read-only.
905    * @param resources
906    * @return String
907    */

908   protected String JavaDoc validateFiles(List JavaDoc resources)
909   {
910     IWorkspace workspace = ResourcesPlugin.getWorkspace();
911     IWorkspaceRoot workspaceRoot= workspace.getRoot();
912     
913     List JavaDoc workspaceFiles = new ArrayList JavaDoc(resources.size());
914     List JavaDoc extenalFiles = new ArrayList JavaDoc(resources.size());
915     for (Iterator JavaDoc i = resources.iterator(); i.hasNext();)
916     {
917       Resource resource = (Resource)i.next();
918       URI uri = resource.getURI().trimFragment();
919       if (uri.isFile())
920       {
921         File JavaDoc file = new File JavaDoc(uri.toFileString());
922         if (file.isFile() && !file.canWrite())
923         {
924           extenalFiles.add(file);
925         }
926       }
927       else if (uri.toString().startsWith("platform:/resource"))
928       {
929         String JavaDoc path = uri.toString().substring("platform:/resources".length());
930         IResource workspaceResource = workspaceRoot.findMember(new Path(path));
931         if (workspaceResource != null && workspaceResource.getType() == IResource.FILE && workspaceResource.getResourceAttributes().isReadOnly())
932         {
933           workspaceFiles.add(workspaceResource);
934         }
935       }
936     }
937     
938     StringBuffer JavaDoc readOnlyFiles = new StringBuffer JavaDoc();
939     if (!workspaceFiles.isEmpty())
940     {
941       Object JavaDoc context = null;
942       if (Platform.getBundle("org.eclipse.swt") != null)
943       {
944         context = new ShellFinder().getActiveShell();
945       }
946       
947       IFile[] files = (IFile[])workspaceFiles.toArray(new IFile [workspaceFiles.size()]);
948       IStatus status = workspace.validateEdit(files, context);
949       if (!status.isOK())
950       {
951         for (int i = 0; i < files.length; i++)
952         {
953           if (files[i].isReadOnly())
954           {
955             readOnlyFiles.append(", ").append(files[i].getFullPath().toString());
956           }
957         }
958       }
959     }
960     if (!extenalFiles.isEmpty())
961     {
962       for (Iterator JavaDoc i = extenalFiles.iterator(); i.hasNext();)
963       {
964         File JavaDoc file = (File JavaDoc)i.next();
965         readOnlyFiles.append(", ").append(file.getAbsolutePath());
966       }
967     }
968     
969     return readOnlyFiles.length() == 0 ?
970       null :
971       readOnlyFiles.deleteCharAt(0).deleteCharAt(0).toString();
972   }
973
974   protected void createProject(IProgressMonitor progressMonitor, IProject project, Collection JavaDoc referencedGenModels)
975   {
976     IWorkspaceRoot workspaceRoot = getWorkspaceRoot();
977
978     // Determine which projects will need to be referenced.
979
//
980
List JavaDoc referencedModelProjects = new ArrayList JavaDoc();
981     List JavaDoc referencedEditProjects = new ArrayList JavaDoc();
982     for (Iterator JavaDoc i = referencedGenModels.iterator(); i.hasNext();)
983     {
984       GenModel referencedGenModel = (GenModel)i.next();
985       String JavaDoc modelDirectory = referencedGenModel.getModelDirectory();
986       if (modelDirectory != null)
987       {
988         referencedModelProjects.add(workspaceRoot.getProject(new Path(modelDirectory).segment(0)));
989         String JavaDoc editDirectory = referencedGenModel.getEditDirectory();
990         if (editDirectory != null && !modelDirectory.equals(editDirectory))
991         {
992           referencedEditProjects.add(workspaceRoot.getProject(new Path(editDirectory).segment(0)));
993         }
994       }
995     }
996
997     String JavaDoc projectName = project.getName();
998     String JavaDoc path = getGenModel().getModelDirectory();
999     int index = path.indexOf(projectName);
1000    if (index >= 0)
1001    {
1002      path = path.substring(index);
1003    }
1004    char firstChar = path.charAt(0);
1005    if (firstChar != '/' && firstChar != '\\')
1006    {
1007      path = "/" + path;
1008    }
1009
1010    // Create the model project.
1011
//
1012
List JavaDoc referencedProjects = new ArrayList JavaDoc(referencedModelProjects);
1013    Generator.createEMFProject
1014      (new Path(path),
1015       getGenModelProjectLocation(),
1016       referencedProjects,
1017       progressMonitor,
1018       Generator.EMF_MODEL_PROJECT_STYLE | Generator.EMF_EMPTY_PROJECT_STYLE);
1019  }
1020
1021  protected void adjustGenModel(IProgressMonitor progressMonitor)
1022  {
1023    String JavaDoc modelName = URI.decode(getGenModelPath().removeFileExtension().lastSegment());
1024    int index = modelName.lastIndexOf('.');
1025    if (index != -1)
1026    {
1027      modelName = modelName.substring(0, index);
1028    }
1029    modelName = CodeGenUtil.capName(modelName);
1030
1031    GenModel genModel = getGenModel();
1032    genModel.setModelName(modelName);
1033    genModel.setModelPluginID(getModelPluginID());
1034    genModel.setModelDirectory(getModelPluginDirectory());
1035    genModel.getUsedGenPackages().addAll(genModel.computeMissingUsedGenPackages());
1036  }
1037
1038  protected List JavaDoc computeEPackagesToGenerate()
1039  {
1040    List JavaDoc ePackages = new EPackageList();
1041    for (Iterator JavaDoc i = getEPackages().iterator(); i.hasNext();)
1042    {
1043      EPackage ePackage = (EPackage)i.next();
1044      EPackageInfo ePackageInfo = getEPackageInfo(ePackage);
1045      if (ePackageInfo.isGenerate() && ePackageInfo.getEcoreFileName() != null)
1046      {
1047        ePackages.add(ePackage);
1048      }
1049    }
1050    return filterReferencedEPackages(ePackages);
1051  }
1052
1053  public void traverseGenPackages(List JavaDoc genPackages)
1054  {
1055    for (Iterator JavaDoc i = genPackages.iterator(); i.hasNext();)
1056    {
1057      GenPackage genPackage = (GenPackage)i.next();
1058      EPackage ePackage = genPackage.getEcorePackage();
1059      EPackageInfo ePackageInfo = getEPackageInfo(ePackage);
1060
1061      genPackage.setBasePackage(ePackageInfo.getBasePackage());
1062      genPackage.setPrefix(ePackageInfo.getPrefix());
1063
1064      adjustGenPackageDuringTraverse(genPackage);
1065      traverseGenPackages(genPackage.getNestedGenPackages());
1066    }
1067  }
1068
1069  protected void adjustGenPackageDuringTraverse(GenPackage genPackage)
1070  {
1071
1072  }
1073
1074  protected URI makeRelative(URI uri, URI relativeTo)
1075  {
1076    if ("file".equals(uri.scheme()))
1077    {
1078      IFile file = getWorkspaceRoot().getFileForLocation(new Path(uri.toFileString()));
1079      if (file != null)
1080      {
1081        URI platformURI = URI.createPlatformResourceURI(file.getFullPath().toString(), true);
1082        URI result = platformURI.deresolve(relativeTo, false, true, false);
1083        if (result.isRelative())
1084        {
1085          return result;
1086        }
1087      }
1088    }
1089
1090    URI result = uri.deresolve(relativeTo, true, true, false);
1091    if (result.isRelative())
1092    {
1093      return result;
1094    }
1095
1096    return uri;
1097  }
1098
1099  protected URI makeAbsolute(URI uri, URI relativeTo)
1100  {
1101    if (uri.isRelative())
1102    {
1103      return uri.resolve(relativeTo);
1104    }
1105    return uri;
1106  }
1107
1108  public URI createFileURI(String JavaDoc pathName)
1109  {
1110    return usePlatformURI() ? URI.createPlatformResourceURI(pathName, true) : URI.createFileURI(pathName);
1111  }
1112
1113  public String JavaDoc getModelPluginID()
1114  {
1115    return modelPluginID == null ? ImporterUtil.validPluginID(getModelProjectName()) : modelPluginID;
1116  }
1117
1118  public void setModelPluginID(String JavaDoc modelPluginID)
1119  {
1120    this.modelPluginID = modelPluginID;
1121  }
1122
1123  public String JavaDoc getModelPluginDirectory()
1124  {
1125    if (modelPluginDirectory == null)
1126    {
1127      String JavaDoc result = getModelProjectName();
1128      if (result != null)
1129      {
1130        if (result.charAt(0) != '/')
1131        {
1132          result = "/" + result;
1133        }
1134        return result + "/src";
1135      }
1136    }
1137    return modelPluginDirectory;
1138  }
1139
1140  public void setModelPluginDirectory(String JavaDoc modelPluginDirectory)
1141  {
1142    this.modelPluginDirectory = modelPluginDirectory;
1143  }
1144
1145  public String JavaDoc getModelProjectName()
1146  {
1147    IPath path = getGenModelProjectLocation();
1148    if (path != null)
1149    {
1150      return URI.decode(path.lastSegment().toString());
1151    }
1152
1153    IPath genModelPath = getGenModelPath();
1154    if (genModelPath != null)
1155    {
1156      return URI.decode(genModelPath.segment(0).toString());
1157    }
1158
1159    return null;
1160  }
1161  
1162  /**
1163   * Changes the existing EPackage Infos so that no duplicated names
1164   * are used.
1165   */

1166  public void makeEcoreFileNamesUnique()
1167  {
1168    if (ePackageToInfoMap != null)
1169    {
1170      Map JavaDoc counterByEcoreName = new HashMap JavaDoc();
1171      List JavaDoc ePackages = filterReferencedEPackages(ePackageToInfoMap.keySet());
1172      if (!ePackages.isEmpty())
1173      {
1174        List JavaDoc ePackageInfos = new ArrayList JavaDoc(ePackages.size());
1175        for (Iterator JavaDoc i = ePackages.iterator(); i.hasNext();)
1176        {
1177          EPackage ePackage = (EPackage)i.next();
1178          if (ePackage.getESuperPackage() == null || !ePackages.contains(ePackage.getESuperPackage()))
1179          {
1180            EPackageInfo ePackageInfo = (EPackageInfo)ePackageToInfoMap.get(ePackage);
1181            ePackageInfos.add(ePackageInfo);
1182            String JavaDoc fileName = ePackageInfo.getEcoreFileName();
1183            if (fileName != null)
1184            {
1185              counterByEcoreName.put(fileName, null);
1186            }
1187          }
1188        }
1189        
1190        for (Iterator JavaDoc i = ePackageInfos.iterator(); i.hasNext();)
1191        {
1192          EPackageInfo ePackageInfo = (EPackageInfo)i.next();
1193          String JavaDoc fileName = ePackageInfo.getEcoreFileName();
1194          if (fileName != null)
1195          {
1196            Integer JavaDoc counterObject = (Integer JavaDoc)counterByEcoreName.get(fileName);
1197            if (counterObject != null)
1198            {
1199              int counter = counterObject.intValue();
1200              int index = fileName.lastIndexOf(".");
1201              StringBuffer JavaDoc newFileName = null;
1202              do
1203              {
1204                newFileName = new StringBuffer JavaDoc(fileName).insert(index, counter++);
1205              }
1206              while (counterByEcoreName.containsKey(newFileName.toString()));
1207              
1208              ePackageInfo.setEcoreFileName(newFileName.toString());
1209              counterObject = new Integer JavaDoc(counter);
1210              counterByEcoreName.put(newFileName.toString(), new Integer JavaDoc(1));
1211            }
1212            else
1213            {
1214              counterObject = new Integer JavaDoc(1);
1215            }
1216            counterByEcoreName.put(fileName, counterObject);
1217          }
1218        }
1219      }
1220    }
1221  }
1222
1223  protected Map JavaDoc getEcoreSaveOptions()
1224  {
1225    return Collections.EMPTY_MAP;
1226  }
1227
1228  protected Map JavaDoc getGenmodelSaveOptions()
1229  {
1230    return Collections.EMPTY_MAP;
1231  }
1232}
1233
Popular Tags