integrated velocity engine for URL templates
[phpeclipse.git] / archive / net.sourceforge.phpeclipse.wiki / src / net / sourceforge / phpeclipse / wiki / actions / mediawiki / DownloadWikipediaAction.java
1 package net.sourceforge.phpeclipse.wiki.actions.mediawiki;
2
3 import java.io.ByteArrayInputStream;
4 import java.io.StringWriter;
5 import java.util.ArrayList;
6 import java.util.Collections;
7 import java.util.List;
8
9 import net.sourceforge.phpeclipse.wiki.editor.WikiEditor;
10 import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin;
11 import net.sourceforge.phpeclipse.wiki.internal.Configuration;
12 import net.sourceforge.phpeclipse.wiki.internal.ConfigurationManager;
13 import net.sourceforge.phpeclipse.wiki.internal.ConfigurationWorkingCopy;
14 import net.sourceforge.phpeclipse.wiki.internal.IConfiguration;
15 import net.sourceforge.phpeclipse.wiki.preferences.Util;
16 import net.sourceforge.phpeclipse.wiki.velocity.EditorText;
17
18 import org.apache.velocity.VelocityContext;
19 import org.apache.velocity.app.Velocity;
20 import org.eclipse.core.resources.IContainer;
21 import org.eclipse.core.resources.IFile;
22 import org.eclipse.core.resources.IFolder;
23 import org.eclipse.core.resources.IResource;
24 import org.eclipse.core.resources.IResourceStatus;
25 import org.eclipse.core.runtime.CoreException;
26 import org.eclipse.core.runtime.IPath;
27 import org.eclipse.core.runtime.IProgressMonitor;
28 import org.eclipse.core.runtime.SubProgressMonitor;
29 import org.eclipse.jface.action.IAction;
30 import org.eclipse.jface.text.IDocument;
31 import org.eclipse.jface.text.ITextSelection;
32 import org.eclipse.jface.text.TextSelection;
33 import org.eclipse.jface.viewers.ISelection;
34 import org.eclipse.jface.viewers.LabelProvider;
35 import org.eclipse.jface.window.Window;
36 import org.eclipse.ui.IEditorActionDelegate;
37 import org.eclipse.ui.IEditorPart;
38 import org.eclipse.ui.IFileEditorInput;
39 import org.eclipse.ui.IWorkbenchWindow;
40 import org.eclipse.ui.dialogs.ListSelectionDialog;
41 import org.eclipse.ui.internal.dialogs.ListContentProvider;
42 import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin;
43 import org.eclipse.ui.texteditor.AbstractTextEditor;
44
45 public class DownloadWikipediaAction implements IEditorActionDelegate {
46
47   private AbstractTextEditor fEditor;
48
49   private EditorText text;
50
51   private IWorkbenchWindow window;
52
53   private void createFolder(IFolder folderHandle, IProgressMonitor monitor) throws CoreException {
54     try {
55       // Create the folder resource in the workspace
56       // Recursive to create any folders which do not exist already
57       if (!folderHandle.exists()) {
58         IContainer parent = folderHandle.getParent();
59         if (parent instanceof IFolder && (!((IFolder) parent).exists())) {
60           createFolder((IFolder) parent, monitor);
61         }
62         folderHandle.create(false, true, monitor);
63       }
64     } catch (CoreException e) {
65       // If the folder already existed locally, just refresh to get contents
66       if (e.getStatus().getCode() == IResourceStatus.PATH_OCCUPIED)
67         folderHandle.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 500));
68       else
69         throw e;
70     }
71   }
72
73   /**
74    * Creates a folder resource handle for the folder with the given workspace path. This method does not create the folder resource;
75    * this is the responsibility of <code>createFolder</code>.
76    * 
77    * @param folderPath
78    *          the path of the folder resource to create a handle for
79    * @return the new folder resource handle
80    * @see #createFolder
81    */
82   private IFolder createFolderHandle(IPath folderPath) {
83     return IDEWorkbenchPlugin.getPluginWorkspace().getRoot().getFolder(folderPath);
84   }
85
86   private void createNewFileIfNeeded(IFile file, String word) throws CoreException {
87     if (!file.exists()) {
88       createWikiFile(file, word);
89     }
90   }
91
92   private void createWikiFile(IFile file, String word) throws CoreException {
93     IContainer parent = file.getParent();
94     if (parent instanceof IFolder && (!((IFolder) parent).exists())) {
95       createFolder((IFolder) parent, null);
96     }
97     String newText = "<!--" + word + "-->";
98     byte[] buffer = newText.getBytes();
99     ByteArrayInputStream source = new ByteArrayInputStream(buffer);
100     file.create(source, true, null);
101   }
102
103   public void dispose() {
104   }
105
106   public String generateUrl(Configuration config, String template, String wikiname) {
107
108     /* first, we init the runtime engine. Defaults are fine. */
109
110     try {
111       Velocity.init();
112
113       /* lets make a Context and put data into it */
114
115       VelocityContext context = new VelocityContext();
116
117       context.put("config", config);
118       text.clear();
119       text.setWikiname(wikiname);
120       context.put("text", text);
121
122       /* lets make our own string to render */
123       StringWriter w = new StringWriter();
124       w = new StringWriter();
125       Velocity.evaluate(context, w, "mystring", template);
126       return w.toString();
127
128     } catch (Exception e) {
129       // TODO Auto-generated catch block
130       e.printStackTrace();
131     }
132     return template;
133   }
134
135   protected Configuration getConfiguration(){
136     List allConfigsList = ConfigurationManager.getInstance().getConfigurations();
137     ArrayList configsList = new ArrayList();
138     for (int i = 0; i < allConfigsList.size(); i++) {
139       IConfiguration temp = (IConfiguration) allConfigsList.get(i);
140       if (temp.getType().equals(WikiEditorPlugin.WIKIPEDIA_GET_TEXT)) {
141         configsList.add(temp);
142       }
143     }
144     Collections.sort(configsList);
145     Configuration configuration = null;
146     ListSelectionDialog listSelectionDialog = new ListSelectionDialog(WikiEditorPlugin.getDefault().getWorkbench()
147         .getActiveWorkbenchWindow().getShell(), configsList, new ListContentProvider(), new LabelProvider(),
148         "Select the refresh URL.");
149     listSelectionDialog.setTitle("Multiple active configuration found");
150     if (listSelectionDialog.open() == Window.OK) {
151       Object[] locations = listSelectionDialog.getResult();
152       if (locations != null) {
153         for (int i = 0; i < locations.length; i++) {
154           configuration = (Configuration) locations[i];
155           break;
156         }
157       }
158     }
159     return configuration;
160   }
161
162   public IDocument getDocument() {
163     IDocument doc = fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput());
164     return doc;
165   }
166
167   private String getWikiFile(IFile file) {
168     return Util.getFileWikiName(file, WikiEditorPlugin.HTML_OUTPUT_PATH);
169   }
170
171   public void init(IWorkbenchWindow window) {
172     this.window = window;
173   }
174
175   void openWikiFile(IFile cfile) {
176     String wikiName = getWikiFile(cfile);
177     try {
178       if (fEditor != null) {
179         selectWiki(wikiName);
180       }
181     } catch (Exception e) {
182     }
183
184   }
185
186   public void openWikiLinkOnSelection() {
187     IDocument doc = getDocument();
188     ITextSelection selection = (ITextSelection) fEditor.getSelectionProvider().getSelection();
189     int pos = selection.getOffset();
190     IFileEditorInput ei = (IFileEditorInput) fEditor.getEditorInput();
191     openWikiFile(ei.getFile());
192   }
193
194   public void run(IAction action) {
195     if (fEditor == null) {
196       IEditorPart targetEditor = window.getActivePage().getActiveEditor();
197       if (targetEditor != null && (targetEditor instanceof AbstractTextEditor)) {
198         fEditor = (AbstractTextEditor) targetEditor;
199       }
200     }
201     if (fEditor != null) {
202       openWikiLinkOnSelection();
203     }
204   }
205
206   public void selectionChanged(IAction action, ISelection selection) {
207     if (selection.isEmpty()) {
208       return;
209     }
210     if (selection instanceof TextSelection) {
211       action.setEnabled(true);
212       return;
213     }
214     if (window.getActivePage() != null && window.getActivePage().getActivePart() != null) {
215       action.setEnabled(window.getActivePage().getActivePart().getClass().equals(WikiEditor.class));
216     }
217   }
218   
219   private void selectWiki(String wikiName) {
220     Configuration configuration = getConfiguration();
221     if (configuration != null && !configuration.equals("")) {
222       String url = generateUrl(configuration, configuration.getURL(), wikiName);
223       String wikiContent = MediaWikiConnector.getWikiText(wikiName, url);
224       if (wikiContent != null) {
225         IDocument doc = fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput());
226         doc.set(wikiContent);
227       }
228     }
229   }
230
231   public void setActiveEditor(IAction action, IEditorPart targetEditor) {
232     if (targetEditor != null && (targetEditor instanceof AbstractTextEditor)) {
233       fEditor = (AbstractTextEditor) targetEditor;
234       text = new EditorText(targetEditor);
235     }
236   }
237 }