d54b06405d5a627a0047b3581ff6a71156c79615
[phpeclipse.git] / archive / net.sourceforge.phpeclipse.wiki / src / net / sourceforge / phpeclipse / wiki / actions / mediawiki / post / StoreWikipediaAction.java
1 package net.sourceforge.phpeclipse.wiki.actions.mediawiki.post;
2
3 //Parts of this sources are copied and modified from the jEdit Wikipedia plugin:
4 //http://www.djini.de/software/wikipedia/index.html
5 //
6 //The modified sources are available under the "Common Public License"
7 //with permission from the original author: Daniel Wunsch
8
9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.io.InputStreamReader;
12 import java.io.StringWriter;
13 import java.lang.reflect.InvocationTargetException;
14 import java.util.ArrayList;
15 import java.util.Collections;
16 import java.util.Date;
17 import java.util.List;
18
19 import net.sourceforge.phpeclipse.wiki.actions.mediawiki.config.IWikipedia;
20 import net.sourceforge.phpeclipse.wiki.actions.mediawiki.connect.Content;
21 import net.sourceforge.phpeclipse.wiki.actions.mediawiki.connect.MediaWikiConnector;
22 import net.sourceforge.phpeclipse.wiki.editor.WikiEditor;
23 import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin;
24 import net.sourceforge.phpeclipse.wiki.internal.Configuration;
25 import net.sourceforge.phpeclipse.wiki.internal.ConfigurationManager;
26 import net.sourceforge.phpeclipse.wiki.internal.IConfiguration;
27 import net.sourceforge.phpeclipse.wiki.preferences.Util;
28 import net.sourceforge.phpeclipse.wiki.velocity.EditorText;
29
30 import org.apache.velocity.VelocityContext;
31 import org.apache.velocity.app.Velocity;
32 import org.eclipse.core.resources.IFile;
33 import org.eclipse.core.runtime.CoreException;
34 import org.eclipse.jface.action.IAction;
35 import org.eclipse.jface.text.IDocument;
36 import org.eclipse.jface.text.ITextSelection;
37 import org.eclipse.jface.text.TextSelection;
38 import org.eclipse.jface.viewers.ISelection;
39 import org.eclipse.jface.viewers.LabelProvider;
40 import org.eclipse.jface.window.Window;
41 import org.eclipse.ui.IEditorActionDelegate;
42 import org.eclipse.ui.IEditorPart;
43 import org.eclipse.ui.IFileEditorInput;
44 import org.eclipse.ui.IWorkbenchWindow;
45 import org.eclipse.ui.dialogs.ListSelectionDialog;
46 import org.eclipse.ui.internal.dialogs.ListContentProvider;
47 import org.eclipse.ui.texteditor.AbstractTextEditor;
48
49 public class StoreWikipediaAction implements IEditorActionDelegate {
50
51   /**
52    * Constant for an empty char array
53    */
54   public static final char[] NO_CHAR = new char[0];
55
56   private static final int DEFAULT_READING_SIZE = 8192;
57
58   private AbstractTextEditor fEditor;
59
60   private EditorText text;
61
62   private IWorkbenchWindow window;
63
64   public void dispose() {
65   }
66
67   public String generateUrl(Configuration config, String template, String wikiname) {
68
69     /* first, we init the runtime engine. Defaults are fine. */
70
71     try {
72       Velocity.init();
73
74       /* lets make a Context and put data into it */
75
76       VelocityContext context = new VelocityContext();
77
78       context.put("config", config);
79       text.clear();
80       text.setWikiname(wikiname);
81       context.put("text", text);
82
83       /* lets make our own string to render */
84       StringWriter w = new StringWriter();
85       w = new StringWriter();
86       Velocity.evaluate(context, w, "mystring", template);
87       return w.toString();
88
89     } catch (Exception e) {
90       // TODO Auto-generated catch block
91       e.printStackTrace();
92     }
93     return template;
94   }
95
96   protected Configuration getConfigurationPrefix(String prefix) {
97
98     List allConfigsList = ConfigurationManager.getInstance().getConfigurations();
99     ArrayList configsList = new ArrayList();
100     for (int i = 0; i < allConfigsList.size(); i++) {
101       IConfiguration temp = (IConfiguration) allConfigsList.get(i);
102       if (temp.getType().startsWith(prefix)) {
103         configsList.add(temp);
104       }
105     }
106     if (configsList.size() == 1) {
107       return (Configuration) configsList.get(0);
108     }
109     Collections.sort(configsList);
110     Configuration configuration = null;
111     ListSelectionDialog listSelectionDialog = new ListSelectionDialog(WikiEditorPlugin.getDefault().getWorkbench()
112         .getActiveWorkbenchWindow().getShell(), configsList, new ListContentProvider(), new LabelProvider(),
113         "Select the refresh URL.");
114     listSelectionDialog.setTitle("Multiple active configuration found");
115     if (listSelectionDialog.open() == Window.OK) {
116       Object[] locations = listSelectionDialog.getResult();
117       if (locations != null) {
118         for (int i = 0; i < locations.length; i++) {
119           configuration = (Configuration) locations[i];
120           break;
121         }
122       }
123     }
124     return configuration;
125   }
126
127   protected Configuration getConfiguration() {
128     return getConfigurationPrefix(WikiEditorPlugin.PREFIX_STORE);
129   }
130
131   public IDocument getDocument() {
132     IDocument doc = fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput());
133     return doc;
134   }
135
136   private String getWikiFile(IFile file) {
137     return Util.getFileWikiName(file);
138   }
139
140   public void init(IWorkbenchWindow window) {
141     this.window = window;
142   }
143
144 //  void postWikiFile(IFile currentFile) {
145 //    String wikiName = getWikiFile(currentFile);
146 //    try {
147 //      if (fEditor != null) {
148 //        selectWiki(currentFile.getContents(), wikiName);
149 //      }
150 //    } catch (Exception e) {
151 //    }
152 //
153 //  }
154
155   public void run(IAction action) {
156     if (fEditor == null) {
157       IEditorPart targetEditor = window.getActivePage().getActiveEditor();
158       if (targetEditor != null && (targetEditor instanceof AbstractTextEditor)) {
159         fEditor = (AbstractTextEditor) targetEditor;
160       }
161     }
162     if (fEditor != null) {
163       Configuration configuration = getConfiguration();
164       if (configuration != null && !configuration.equals("")) {
165         try {
166           String wikiLocale = configuration.getType().substring(WikiEditorPlugin.PREFIX_STORE.length());
167           IWikipedia wikipediaProperties = WikiEditorPlugin.getWikiInstance(wikiLocale);
168           String user = configuration.getUser();
169           String password = configuration.getPassword();
170           if (user == null || password == null || user.equals("") || password.equals("")) {
171             String[] result = new String[2];
172             boolean cache = configuration.promptForPassword(configuration.getUser(), "Set User/Password", true, result);
173             if (result[0] == null || result[1] == null) {
174               return;
175             }
176             if (result[0].equals("") || result[1].equals("")) {
177               return;
178             }
179             user = result[0];
180             password = result[1];
181           }
182 //          IDocument doc = getDocument();
183 //          ITextSelection selection = (ITextSelection) fEditor.getSelectionProvider().getSelection();
184 //          int pos = selection.getOffset();
185           if (fEditor.getEditorInput() instanceof IFileEditorInput) {
186             IFileEditorInput ei = (IFileEditorInput) fEditor.getEditorInput();
187             IFile currentFile = ei.getFile();
188             IFile[] files = { currentFile };
189             PostJob job = new PostJob(configuration, wikipediaProperties,  user,  password, files);
190             job.setRule(null);
191             job.setUser(true);
192             job.schedule();
193             
194             String wikiName = getWikiFile(currentFile);
195             if (fEditor != null) {
196               selectWiki(configuration, currentFile.getContents(), wikipediaProperties, user, password, wikiName);
197             }
198           }
199         } catch (CoreException e1) {
200           // TODO Auto-generated catch block
201           e1.printStackTrace();
202         } catch (NoSuchMethodException e) {
203           // TODO Auto-generated catch block
204           e.printStackTrace();
205         } catch (IllegalAccessException e) {
206           // TODO Auto-generated catch block
207           e.printStackTrace();
208         } catch (ClassNotFoundException e) {
209           // TODO Auto-generated catch block
210           e.printStackTrace();
211         } catch (InvocationTargetException e) {
212           // TODO Auto-generated catch block
213           e.printStackTrace();
214         }
215       }
216     }
217   }
218
219   public void selectionChanged(IAction action, ISelection selection) {
220     if (selection.isEmpty()) {
221       return;
222     }
223     if (selection instanceof TextSelection) {
224       action.setEnabled(true);
225       return;
226     }
227     if (window.getActivePage() != null && window.getActivePage().getActivePart() != null) {
228       action.setEnabled(window.getActivePage().getActivePart().getClass().equals(WikiEditor.class));
229     }
230   }
231
232   private void selectWiki(Configuration configuration, InputStream is, IWikipedia wikipediaProperties, String user, String password, String wikiName) {
233
234     try {
235       //        IDocument doc = fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput());
236       String url = generateUrl(configuration, configuration.getURL(), wikiName);
237
238       MediaWikiConnector connector = new MediaWikiConnector();
239       String actionUrl = configuration.getURL();
240       if (actionUrl == null || actionUrl.equals("")) {
241         // fall back to default settings
242         actionUrl = wikipediaProperties.getActionUrl();
243       }
244       Date d = new Date();
245
246       Content content = new Content(String.valueOf(d.getTime()), getInputStreamAsString(is, wikipediaProperties.getCharSet()));
247
248       boolean success = connector.login(wikipediaProperties, actionUrl, user, password, false);
249       if (success) {
250         connector.store(wikipediaProperties, actionUrl, wikiName, content, "", false, false);
251         connector.logout(wikipediaProperties, actionUrl);
252       }
253     } catch (Exception e) {
254       e.printStackTrace();
255       WikiEditorPlugin.getDefault()
256           .reportError("Exception occured: ", e.getMessage() + "\nSee stacktrace in /.metadata/.log file.");
257     }
258   }
259
260   public void setActiveEditor(IAction action, IEditorPart targetEditor) {
261     if (targetEditor != null && (targetEditor instanceof AbstractTextEditor)) {
262       fEditor = (AbstractTextEditor) targetEditor;
263       text = new EditorText(targetEditor);
264     }
265   }
266
267   /**
268    * Returns the given input stream's contents as a character array. If a length is specified (ie. if length != -1), only length
269    * chars are returned. Otherwise all chars in the stream are returned. Note this doesn't close the stream.
270    * 
271    * @throws IOException
272    *           if a problem occured reading the stream.
273    */
274   public static String getInputStreamAsString(InputStream stream, String encoding) throws IOException {
275     char[] array = getInputStreamAsCharArray(stream, -1, encoding);
276     if (array != null) {
277       return new String(array);
278     }
279     return null;
280   }
281
282   /**
283    * Returns the given input stream's contents as a character array. If a length is specified (ie. if length != -1), only length
284    * chars are returned. Otherwise all chars in the stream are returned. Note this doesn't close the stream.
285    * 
286    * @throws IOException
287    *           if a problem occured reading the stream.
288    */
289   public static char[] getInputStreamAsCharArray(InputStream stream, int length, String encoding) throws IOException {
290     InputStreamReader reader = null;
291     reader = encoding == null ? new InputStreamReader(stream) : new InputStreamReader(stream, encoding);
292     char[] contents;
293     if (length == -1) {
294       contents = NO_CHAR;
295       int contentsLength = 0;
296       int amountRead = -1;
297       do {
298         int amountRequested = Math.max(stream.available(), DEFAULT_READING_SIZE); // read at least 8K
299
300         // resize contents if needed
301         if (contentsLength + amountRequested > contents.length) {
302           System.arraycopy(contents, 0, contents = new char[contentsLength + amountRequested], 0, contentsLength);
303         }
304
305         // read as many chars as possible
306         amountRead = reader.read(contents, contentsLength, amountRequested);
307
308         if (amountRead > 0) {
309           // remember length of contents
310           contentsLength += amountRead;
311         }
312       } while (amountRead != -1);
313
314       // resize contents if necessary
315       if (contentsLength < contents.length) {
316         System.arraycopy(contents, 0, contents = new char[contentsLength], 0, contentsLength);
317       }
318     } else {
319       contents = new char[length];
320       int len = 0;
321       int readSize = 0;
322       while ((readSize != -1) && (len != length)) {
323         // See PR 1FMS89U
324         // We record first the read size. In this case len is the actual read size.
325         len += readSize;
326         readSize = reader.read(contents, len, length - len);
327       }
328       // See PR 1FMS89U
329       // Now we need to resize in case the default encoding used more than one byte for each
330       // character
331       if (len != length)
332         System.arraycopy(contents, 0, (contents = new char[len]), 0, len);
333     }
334
335     return contents;
336   }
337 }