KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > emf > codegen > jet > JETCompileTemplateOperation


1 /**
2  * <copyright>
3  *
4  * Copyright (c) 2002-2004 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: JETCompileTemplateOperation.java,v 1.4 2005/06/08 06:15:57 nickb Exp $
16  */

17 package org.eclipse.emf.codegen.jet;
18
19
20 import java.io.ByteArrayInputStream JavaDoc;
21 import java.io.ByteArrayOutputStream JavaDoc;
22 import java.io.File JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.io.InputStream JavaDoc;
25 import java.util.ArrayList JavaDoc;
26 import java.util.Arrays JavaDoc;
27 import java.util.Collection JavaDoc;
28 import java.util.HashSet JavaDoc;
29 import java.util.Iterator JavaDoc;
30 import java.util.List JavaDoc;
31 import java.util.ListIterator JavaDoc;
32 import java.util.StringTokenizer JavaDoc;
33
34 import org.eclipse.core.resources.IContainer;
35 import org.eclipse.core.resources.IFile;
36 import org.eclipse.core.resources.IFolder;
37 import org.eclipse.core.resources.IProject;
38 import org.eclipse.core.resources.IResource;
39 import org.eclipse.core.resources.IWorkspaceRoot;
40 import org.eclipse.core.resources.IWorkspaceRunnable;
41 import org.eclipse.core.resources.IncrementalProjectBuilder;
42 import org.eclipse.core.resources.ResourcesPlugin;
43 import org.eclipse.core.runtime.CoreException;
44 import org.eclipse.core.runtime.IPath;
45 import org.eclipse.core.runtime.IProgressMonitor;
46 import org.eclipse.core.runtime.Path;
47 import org.eclipse.core.runtime.SubProgressMonitor;
48
49 import org.eclipse.emf.codegen.CodeGenPlugin;
50 import org.eclipse.emf.common.CommonPlugin;
51 import org.eclipse.emf.common.util.URI;
52
53
54 public class JETCompileTemplateOperation implements IWorkspaceRunnable
55 {
56   protected static final String JavaDoc JET_EXTENSION = "jet";
57
58   protected IProject project;
59   protected Collection JavaDoc containers;
60   protected List JavaDoc files = new ArrayList JavaDoc();
61   protected boolean inBuild;
62
63   /**
64    * Creates an instance given the collection of resources.
65    */

66   public JETCompileTemplateOperation(IProject project, Collection JavaDoc containers) throws CoreException
67   {
68     this.project = project;
69     this.containers = containers;
70     for (Iterator JavaDoc i = containers.iterator(); i.hasNext(); )
71     {
72       Object JavaDoc container = i.next();
73       if (container instanceof IContainer)
74       {
75         consider((IContainer)container);
76       }
77       else
78       {
79         consider(container.toString());
80       }
81     }
82   }
83
84   /**
85    * Creates an instance given the collection of resources.
86    */

87   public JETCompileTemplateOperation(IProject project, Collection JavaDoc containers, Collection JavaDoc resources) throws CoreException
88   {
89     super();
90
91     this.project = project;
92     this.containers = containers;
93     for (Iterator JavaDoc i = resources.iterator(); i.hasNext(); )
94     {
95       Object JavaDoc object = i.next();
96       if (object instanceof IFile)
97       {
98         IFile file = (IFile)object;
99         for (IContainer container = file.getParent(); container != null; container = container.getParent())
100         {
101           if (containers.contains(container))
102           {
103             consider(file);
104             break;
105           }
106         }
107       }
108       else if (object instanceof IContainer)
109       {
110         for (IContainer container = (IContainer)object; container != null; container = container.getParent())
111         {
112           if (containers.contains(container))
113           {
114             consider(container);
115             break;
116           }
117         }
118       }
119     }
120   }
121   
122   /**
123    * Returns true if there are files to compile.
124    */

125   public boolean shouldCompile()
126   {
127     return !files.isEmpty();
128   }
129
130   /**
131    * Adds the URI.
132    */

133   protected void consider(String JavaDoc uri)
134   {
135     URI baseURI = URI.createURI(uri);
136     URI localURI = CommonPlugin.asLocalURI(baseURI);
137     if (localURI.isFile() && !localURI.isRelative())
138     {
139       File JavaDoc file = new File JavaDoc(localURI.toFileString());
140       if (file.isDirectory() && !uri.endsWith("/"))
141       {
142         baseURI = URI.createURI(uri + "/");
143       }
144       consider(baseURI, localURI, new File JavaDoc(localURI.toFileString()));
145     }
146   }
147
148   protected void consider(URI baseURI, URI localURI, File JavaDoc file)
149   {
150     if (file.isDirectory())
151     {
152       File JavaDoc [] files = file.listFiles();
153       for (int i = 0; i < files.length; ++i)
154       {
155         consider(baseURI, localURI, files[i]);
156       }
157     }
158     else if (file.isFile() && file.getName().endsWith(JET_EXTENSION) && file.getName().indexOf('.') != -1)
159     {
160       files.add(URI.createFileURI(file.getAbsolutePath()).deresolve(localURI).resolve(baseURI));
161     }
162   }
163
164   /**
165    * Adds the file to {@link #files} the file ends with the {@link #JET_EXTENSION} extension.
166    */

167   protected void consider(IFile file)
168   {
169     if (file.getFileExtension() != null && file.getFileExtension().endsWith(JET_EXTENSION))
170     {
171       files.add(file);
172     }
173   }
174
175   /**
176    * Considers all the files of a container and all it's subcontainer.
177    */

178   protected void consider(IContainer container) throws CoreException
179   {
180     IResource[] children = container.members();
181     if (children != null)
182     {
183       for (int i = 0; i < children.length; ++i)
184       {
185         IResource resource = children[i];
186         if (resource instanceof IFile)
187         {
188           consider((IFile)resource);
189         }
190         else if (resource instanceof IContainer)
191         {
192           consider((IContainer)resource);
193         }
194       }
195     }
196   }
197
198   /**
199    */

200   public void run(IProgressMonitor progressMonitor) throws CoreException
201   {
202     try
203     {
204       progressMonitor.beginTask("", 3 * files.size());
205       progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETCompilingTemplates_message"));
206
207       IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
208       Collection JavaDoc jetProjects = new HashSet JavaDoc();
209
210       HashSet JavaDoc visitedRelativePaths = new HashSet JavaDoc();
211       for (Iterator JavaDoc i = files.iterator(); i.hasNext(); )
212       {
213         Object JavaDoc file = i.next();
214         String JavaDoc fileName = file instanceof IFile ? ((IFile)file).getName() : file.toString();
215
216         progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETCompile_message", new Object JavaDoc [] { fileName }));
217
218         JETNature nature = JETNature.getRuntime(project);
219         IContainer directory = nature.getJavaSourceContainer();
220
221         IPath filePath = file instanceof IFile ? ((IFile)file).getFullPath() : new Path(file.toString());
222         List JavaDoc templateContainers = nature.getTemplateContainers();
223         List JavaDoc templateSourceContainers = nature.getTemplateSourceContainers();
224
225         String JavaDoc [] containerLocations = new String JavaDoc [templateContainers.size()];
226         for (ListIterator JavaDoc j = templateContainers.listIterator(); j.hasNext(); )
227         {
228           Object JavaDoc container = j.next();
229           if (container instanceof IContainer)
230           {
231             containerLocations[j.previousIndex()] = "platform:/resource" + ((IContainer)container).getFullPath();
232           }
233           else
234           {
235             containerLocations[j.previousIndex()] = container.toString();
236           }
237         }
238
239         for (Iterator JavaDoc j = templateSourceContainers.iterator(); j.hasNext(); )
240         {
241           Object JavaDoc container = j.next();
242           IPath containerPath = container instanceof IContainer ? ((IContainer)container).getFullPath() : new Path(container.toString());
243           if (containerPath.isPrefixOf(filePath))
244           {
245             String JavaDoc relativePath = filePath.removeFirstSegments(containerPath.segmentCount()).setDevice(null).toString();
246             if (visitedRelativePaths.add(relativePath))
247             {
248               JETCompiler compiler = new JETCompiler(containerLocations, relativePath);
249               compiler.parse();
250   
251               ByteArrayOutputStream JavaDoc arrayOutputStream = new ByteArrayOutputStream JavaDoc();
252               compiler.generate(arrayOutputStream);
253   
254               JETSkeleton skeleton = compiler.getSkeleton();
255               if (skeleton.getClassName().equals(""))
256               {
257                 skeleton.setClassName(fileName.substring(0, fileName.indexOf('.')));
258               }
259               if (skeleton.getPackageName() != null)
260               {
261                 directory = getPackageContainer(directory, skeleton.getPackageName(), new SubProgressMonitor(progressMonitor, 1));
262               }
263               else
264               {
265                 progressMonitor.worked(1);
266               }
267   
268               IFile outputFile =
269                 workspaceRoot.getFile(directory.getFullPath().append(skeleton.getClassName() + ".java"));
270   
271               progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETUpdate_message", new Object JavaDoc [] { fileName }));
272   
273               if (!outputFile.exists())
274               {
275                 outputFile.create(new ByteArrayInputStream JavaDoc(arrayOutputStream.toByteArray()), true, progressMonitor);
276               }
277               else
278               {
279                 boolean changed = true;
280                 byte [] newBytes = arrayOutputStream.toByteArray();
281                 try
282                 {
283                   InputStream JavaDoc inputStream = outputFile.getContents();
284                   byte [] oldBytes = new byte[inputStream.available()];
285                   inputStream.read(oldBytes);
286                   inputStream.close();
287                   changed = !Arrays.equals(oldBytes, newBytes);
288                 }
289                 catch (IOException JavaDoc exception)
290                 {
291                 }
292   
293                 if (changed)
294                 {
295                   outputFile.setContents(new ByteArrayInputStream JavaDoc(arrayOutputStream.toByteArray()), true, true, progressMonitor);
296                 }
297               }
298   
299               jetProjects.add(outputFile.getProject());
300   
301               progressMonitor.worked(1);
302   
303               break;
304             }
305           }
306         }
307       }
308
309       // Kick of a Java build if not already in a build.
310
//
311
if (!isInBuild())
312       {
313         for (Iterator JavaDoc projects = jetProjects.iterator(); projects.hasNext(); )
314         {
315           IProject project = (IProject) projects.next();
316           progressMonitor.subTask
317             (CodeGenPlugin.getPlugin().getString("_UI_JETJavaCompileProject_message", new Object JavaDoc [] { project.getFullPath() }));
318           project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, new SubProgressMonitor(progressMonitor, 1));
319         }
320       }
321     }
322     finally
323     {
324       progressMonitor.done();
325     }
326   }
327
328   protected IContainer getPackageContainer(IContainer root, String JavaDoc packagename, IProgressMonitor monitor) throws CoreException
329   {
330     for (StringTokenizer JavaDoc stringTokenizer = new StringTokenizer JavaDoc(packagename, "."); stringTokenizer.hasMoreTokens(); )
331     {
332       IFolder newContainer = root.getFolder(new Path(stringTokenizer.nextToken()));
333       if (!newContainer.exists())
334       {
335         newContainer.create(true, true, monitor);
336       }
337       root = newContainer;
338     }
339
340     return root;
341   }
342
343   public boolean isInBuild()
344   {
345     return inBuild;
346   }
347
348   public void setInBuild(boolean build)
349   {
350     inBuild = build;
351   }
352 }
353
Popular Tags