KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > emf > examples > jet > article2 > actionexample > EmitAction


1 package org.eclipse.emf.examples.jet.article2.actionexample;
2
3
4 import java.io.ByteArrayInputStream JavaDoc;
5 import java.io.File JavaDoc;
6 import java.io.IOException JavaDoc;
7 import java.io.InputStream JavaDoc;
8 import java.io.PrintWriter JavaDoc;
9 import java.io.StringWriter JavaDoc;
10 import java.lang.reflect.InvocationTargetException JavaDoc;
11 import java.util.Collections JavaDoc;
12 import java.util.Iterator JavaDoc;
13 import java.util.List JavaDoc;
14 import java.util.StringTokenizer JavaDoc;
15
16 import org.eclipse.core.resources.IContainer;
17 import org.eclipse.core.resources.IFile;
18 import org.eclipse.core.runtime.CoreException;
19 import org.eclipse.core.runtime.IPath;
20 import org.eclipse.core.runtime.IProgressMonitor;
21 import org.eclipse.core.runtime.IStatus;
22 import org.eclipse.core.runtime.MultiStatus;
23 import org.eclipse.core.runtime.Path;
24 import org.eclipse.core.runtime.Status;
25 import org.eclipse.emf.codegen.jet.JETEmitter;
26 import org.eclipse.emf.examples.jet.article2.TypesafeEnumPlugin;
27
28 import org.eclipse.jface.action.IAction;
29 import org.eclipse.jface.dialogs.ErrorDialog;
30 import org.eclipse.jface.dialogs.ProgressMonitorDialog;
31 import org.eclipse.jface.viewers.ISelection;
32 import org.eclipse.jface.viewers.IStructuredSelection;
33 import org.eclipse.swt.widgets.Shell;
34 import org.eclipse.ui.IActionDelegate;
35 import org.eclipse.ui.actions.WorkspaceModifyOperation;
36
37
38
39 /**
40  * Example action that translates and generates text with selected JET
41  * templates.
42  *
43  * @author Remko Popma
44  * @version $Revision: 1.2 $ ($Date: 2004/06/01 16:17:41 $)
45  */

46 public class EmitAction implements IActionDelegate
47 {
48   protected ISelection selection;
49
50   public void selectionChanged(IAction action, ISelection selection)
51   {
52     this.selection = selection;
53     action.setEnabled(true);
54   }
55
56   public void run(IAction action)
57   {
58     List JavaDoc files = (selection instanceof IStructuredSelection) ? ((IStructuredSelection)selection).toList() : Collections.EMPTY_LIST;
59
60     for (Iterator JavaDoc i = files.iterator(); i.hasNext();)
61     {
62       IFile file = (IFile)i.next();
63       IPath fullPath = file.getFullPath();
64
65       String JavaDoc templateURI = "platform:/resource" + fullPath;
66       ClassLoader JavaDoc classloader = getClass().getClassLoader();
67       JETEmitter emitter = new JETEmitter(templateURI, classloader);
68
69       // or: use anonymous subclass
70
//JETEmitter emitter = new JETEmitter(templateURI) {}; // notice the
71
// brackets
72

73       try
74       {
75         String JavaDoc[] arguments = new String JavaDoc []{ "hi" };
76         generate(emitter, arguments, file);
77
78       }
79       catch (Exception JavaDoc e)
80       {
81         handleException(e);
82       }
83     }
84   }
85
86   /**
87    * Wraps text generation and save in a <code>WorkspaceModifyOperation</code>,
88    * and runs this operation in a <code>ProgressMonitorDialog</code>.
89    *
90    * @param emitter
91    * generates text to save
92    * @param arguments
93    * arguments to pass to the emitter
94    * @param file
95    * the original template file
96    * @throws CoreException
97    * @throws InvocationTargetException
98    * @throws InterruptedException
99    */

100   private void generate(final JETEmitter emitter, final Object JavaDoc[] arguments, final IFile file) throws CoreException,
101     InvocationTargetException JavaDoc,
102     InterruptedException JavaDoc
103   {
104
105     WorkspaceModifyOperation op = new WorkspaceModifyOperation()
106       {
107         public void execute(IProgressMonitor monitor) throws CoreException, InvocationTargetException JavaDoc, InterruptedException JavaDoc
108         {
109           try
110           {
111             String JavaDoc generated = emitter.generate(monitor, arguments);
112             saveGenerated(generated, file, monitor);
113
114           }
115           catch (IOException JavaDoc ioe)
116           {
117             throw new InvocationTargetException JavaDoc(ioe);
118           }
119         }
120       };
121
122     Shell shell = TypesafeEnumPlugin.getActiveWorkbenchShell();
123     ProgressMonitorDialog dialog = new ProgressMonitorDialog(shell);
124     dialog.run(false, true, op);
125   }
126
127   /**
128    * Save the generated text to a file in the same location as the specified
129    * file.
130    *
131    * @param generated
132    * the generated text to save
133    * @param file
134    * the original template file
135    * @param monitor
136    * @throws IOException
137    * @throws CoreException
138    */

139   private void saveGenerated(String JavaDoc generated, IFile file, IProgressMonitor monitor) throws IOException JavaDoc, CoreException
140   {
141
142     InputStream JavaDoc contents = new ByteArrayInputStream JavaDoc(generated.getBytes());
143
144     IContainer parent = file.getParent();
145     IFile target = parent.getFile(new Path(file.getName() + ".txt"));
146
147     if (target.exists())
148     {
149       target.setContents(contents, true, false, monitor);
150     }
151     else
152     {
153       File JavaDoc systemFile = target.getLocation().toFile();
154       if (systemFile.exists())
155       { // check if out of sync
156
parent.refreshLocal(1, monitor); // not user-friendly: user did not
157
// request Refresh...
158
target.setContents(contents, true, false, monitor);
159       }
160       else
161       {
162         target.create(contents, false, monitor);
163       }
164     }
165   }
166
167   /**
168    * Logs the exception and shows an error dialog.
169    *
170    * @param e
171    * the exception to handle
172    */

173   private void handleException(Throwable JavaDoc t)
174   {
175     if (t instanceof InvocationTargetException JavaDoc)
176     {
177       t = ((InvocationTargetException JavaDoc)t).getTargetException();
178     }
179     TypesafeEnumPlugin.log(t);
180     MultiStatus status = createStatus(t);
181
182     Shell shell = TypesafeEnumPlugin.getActiveWorkbenchShell();
183     String JavaDoc title = "Error while emitting template";
184     ErrorDialog.openError(shell, title, null, status);
185   }
186
187   /**
188    * Create a <code>MultiStatus</code> with a <code>Status</code> entry for
189    * every line of the stacktrace of the specified exception, so the the
190    * stacktrace can be shown in the Details of an <code>ErrorDialog</code>.
191    *
192    * @param t
193    * the exception
194    * @return a <code>MultiStatus</code> with a <code>Status</code> entry for
195    * every line of the stacktrace of the specified exception
196    */

197   private MultiStatus createStatus(Throwable JavaDoc t)
198   {
199     String JavaDoc id = TypesafeEnumPlugin.getPluginId();
200     MultiStatus result = new MultiStatus(id, IStatus.ERROR, "Unexpected Error", t);
201
202     StringWriter JavaDoc trace = new StringWriter JavaDoc();
203     t.printStackTrace(new PrintWriter JavaDoc(trace));
204     StringTokenizer JavaDoc tok = new StringTokenizer JavaDoc(trace.toString(), "\r\n");
205
206     while (tok.hasMoreTokens())
207     {
208       String JavaDoc line = tok.nextToken();
209       if (line.charAt(0) == '\t')
210       {
211         line = " " + line.trim();
212       }
213       result.add(new Status(IStatus.ERROR, id, IStatus.ERROR, line, null));
214     }
215     return result;
216   }
217 }
Popular Tags