915af72860b2049029dd03453862eb8ed4d33cc3
[phpeclipse.git] / archive / net.sourceforge.phpeclipse.wiki / src / net / sourceforge / phpeclipse / wiki / editor / WikiEditorPlugin.java
1 package net.sourceforge.phpeclipse.wiki.editor;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.lang.reflect.InvocationTargetException;
6 import java.lang.reflect.Method;
7 import java.net.MalformedURLException;
8 import java.net.URL;
9 import java.sql.SQLException;
10 import java.text.MessageFormat;
11 import java.util.ArrayList;
12 import java.util.Enumeration;
13 import java.util.Hashtable;
14 import java.util.List;
15 import java.util.MissingResourceException;
16 import java.util.PropertyResourceBundle;
17 import java.util.ResourceBundle;
18
19 import net.sourceforge.phpeclipse.wiki.actions.mediawiki.config.IWikipedia;
20 import net.sourceforge.phpeclipse.wiki.internal.ConfigurationManager;
21 import net.sourceforge.phpeclipse.wiki.internal.IConfigurationWorkingCopy;
22 import net.sourceforge.phpeclipse.wiki.sql.WikipediaDB;
23
24 import org.eclipse.core.resources.IWorkspace;
25 import org.eclipse.core.resources.ResourcesPlugin;
26 import org.eclipse.core.runtime.CoreException;
27 import org.eclipse.core.runtime.IExtension;
28 import org.eclipse.core.runtime.IPluginDescriptor;
29 import org.eclipse.core.runtime.IStatus;
30 import org.eclipse.core.runtime.Path;
31 import org.eclipse.core.runtime.Platform;
32 import org.eclipse.core.runtime.Status;
33 import org.eclipse.jface.dialogs.MessageDialog;
34 import org.eclipse.jface.preference.IPreferenceStore;
35 import org.eclipse.jface.resource.ImageDescriptor;
36 import org.eclipse.jface.text.templates.ContextTypeRegistry;
37 import org.eclipse.jface.text.templates.persistence.TemplateStore;
38 import org.eclipse.swt.graphics.Image;
39 import org.eclipse.swt.widgets.Display;
40 import org.eclipse.swt.widgets.Shell;
41 import org.eclipse.ui.IWorkbenchPage;
42 import org.eclipse.ui.IWorkbenchWindow;
43 import org.eclipse.ui.PlatformUI;
44 import org.eclipse.ui.editors.text.templates.ContributionContextTypeRegistry;
45 import org.eclipse.ui.editors.text.templates.ContributionTemplateStore;
46 import org.eclipse.ui.plugin.AbstractUIPlugin;
47
48 public class WikiEditorPlugin extends AbstractUIPlugin {
49
50   private static WikiEditorPlugin fgPlugin;
51
52   public final static String AUTOMATICALLY_CREATED = "<!-- automatically created -->";
53
54   public final static String WP_EXTENSION = "wp";
55
56   public final static String XML_START_1 = "<?xml version=\"1.0\" encoding=\"";
57
58   public final static String XML_START_2 = "\" ?>\n" + "<mediawiki version=\"0.1\">\n";
59
60   public final static String XML_END = "\n</mediawiki>";
61
62   public static final String PREFIX_LOAD = "Load ";
63
64   public static final String PREFIX_STORE = "Store ";
65
66   public static final String HTTP_QUERY = "HTTP Query";
67
68   //  public static final String WIKIPEDIA_GET_TEXT = "Load WikipediaEN";
69   //
70   //  public static final String WIKIPEDIA_SET_TEXT = "Store WikipediaEN";
71   public static final String WIKIPEDIA_SQL = "Wikipedia SQL access";
72
73   public static final String BLOG_A_WIKI = "Blog as Wiki Text";
74
75   public static final String BLOG_A_HTML = "Blog as HTML Text";
76
77   public static final String PLOG4U_DE_LOAD = PREFIX_LOAD + "Plog4UDE";
78
79   public static final String PLOG4U_DE_STORE = PREFIX_STORE + "Plog4UDE";
80
81   public static final String PLOG4U_ORG_LOAD = PREFIX_LOAD + "Plog4UORG";
82
83   public static final String PLOG4U_ORG_STORE = PREFIX_STORE + "Plog4UORG";
84
85   public static final String[] PREDEFINED_TYPES = {
86       HTTP_QUERY,
87       WIKIPEDIA_SQL,
88       PLOG4U_DE_LOAD,
89       PLOG4U_DE_STORE,
90       PLOG4U_ORG_LOAD,
91       PLOG4U_ORG_STORE,
92       BLOG_A_WIKI,
93       BLOG_A_HTML };
94
95   public static final String[] PREDEFINED_WIKIS = {
96       "WikibooksDE",
97       "WikibooksEN",
98       "WikinewsDE",
99       "WikinewsEN",
100       "WikipediaAR",
101       "WikipediaCA",
102       "WikipediaDE",
103       "WikipediaEN",
104       "WikipediaEO",
105       "WikipediaES",
106       "WikipediaET",
107       "WikipediaFI",
108       "WikipediaFR",
109       "WikipediaHE",
110       "WikipediaIA",
111       "WikipediaIT",
112       "WikipediaJA",
113       "WikipediaNL",
114       "WikipediaPL",
115       "WikipediaPT",
116       "WikipediaRO",
117       "WikipediaSL",
118       "WikipediaSV",
119       "WikipediaZH" };
120
121   public static final ArrayList CONFIGURATION_TYPES = new ArrayList();
122
123   //image paths
124   public static final String ICON_PATH = "icons/full/"; //$NON-NLS-1$
125
126   public final static String PLUGIN_ID = "net.sourceforge.phpeclipse.wiki";
127
128   public final static String HTML_OUTPUT_PATH = "__static_wiki_folder";
129
130   public final static String WIKI_TEXTS_BASE_PATH = "__wiki_texts_base_path";
131
132   public final static String LOCAL_TEMPLATE_FILE_NAME = "__local_template_file_name";
133
134   public final static String EXPORT_TEMPLATE_FILE_NAME = "__export_template_file_name";
135
136   public final static String LOCAL_CSS_URL = "__local_css_url";
137
138   public final static String EXPORT_CSS_URL = "__export_css_url";
139
140   public final static String PREF_STRING_CONFIGURATIONS = "__configurations4";
141
142   public final static String CONSOLE_OUTPUT = "__console_output";
143
144   public final static String HTTP_TIMEOUT = "http.timeout";
145
146   public final static String HTTP_PROXYHOST = "http.proxyHost";
147
148   public final static String HTTP_PROXYPORT = "http.proxyPort";
149
150   public final static String HTTP_PROXYUSERNAME = "http.proxyUserName";
151
152   public final static String HTTP_PROXYPASSWORD = "http.proxyPassword";
153
154   public final static String CONFIG_MEMENTO = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<configurations>"
155       + "<config name=\"Google Search\" type-id=\"HTTP Query\" url=\"http://www.google.com/search?q=$text.selection\"/>"
156       + "<config name=\"Koders.com Search\" type-id=\"HTTP Query\" url=\"http://koders.com/?s=$text.selection\"/>"
157       + "<config name=\"Leo.org Translation\" type-id=\"HTTP Query\" url=\"http://dict.leo.org/?search=$text.selection\"/>"
158
159       + "<config name=\"Plog4U.de Download\" type-id=\"" + PLOG4U_DE_LOAD
160       + "\" url=\"http://www.plog4u.de/index.php/Spezial:Export\"/>" + "<config name=\"Plog4U.org Download\" type-id=\""
161       + PLOG4U_ORG_LOAD + "\" url=\"http://www.plog4u.org/index.php/Special:Export\"/>"
162       + "<config name=\"Plog4U.de Upload\" type-id=\"" + PLOG4U_DE_STORE + "\" url=\"http://www.plog4u.de/index.php\"/>"
163       + "<config name=\"Plog4U.org Upload\" type-id=\"" + PLOG4U_ORG_STORE + "\" url=\"http://www.plog4u.org/index.php\"/>"
164
165       + "<config name=\"WikipediaEN Download\" type-id=\"" + PREFIX_LOAD
166       + "WikipediaEN\" url=\"http://en.wikipedia.org/wiki/Special:Export\"/>" + "<config name=\"WikibooksEN Download\" type-id=\""
167       + PREFIX_LOAD + "WikibooksEN\" url=\"http://en.wikibooks.org/wiki/Special:Export\"/>"
168       + "<config name=\"WikipediaEN Upload\" type-id=\"" + PREFIX_STORE
169       + "WikipediaEN\" url=\"http://en.wikipedia.org/w/index.php\"/>" + "<config name=\"WikibooksEN Upload\" type-id=\""
170       + PREFIX_STORE + "WikibooksEN\" url=\"http://en.wikibooks.org/w/index.php\"/>"
171       + "<config name=\"Wikipedia-SQL\" type-id=\"Wikipedia SQL access\" user=\"root\" url=\"jdbc:mysql://localhost/wikidb\"/>"
172       + "</configurations>";
173
174   public static WikipediaDB fWikiDB = null;
175
176   private static ConfigurationManager manager;
177
178   //
179   //  public static final String IMG_MONITOR_ON = "monitorOn";
180   //
181   //  public static final String IMG_MONITOR_OFF = "monitorOff";
182
183   /**
184    * Creates an image and places it in the image registry.
185    * 
186    * @param id
187    *          the identifier for the image
188    * @param baseURL
189    *          the base URL for the image
190    */
191   protected static void createImageDescriptor(WikiEditorPlugin plugin, String id, URL baseURL) {
192     // Delegate to the plugin instance to avoid concurrent class loading problems
193     plugin.privateCreateImageDescriptor(id, baseURL);
194   }
195
196   public static WikiEditorPlugin getDefault() {
197     return fgPlugin;
198   }
199
200   /**
201    * Returns the image descriptor for the given image ID. Returns null if there is no such image.
202    * 
203    * @param id
204    *          the identifier for the image to retrieve
205    * @return the image associated with the given ID
206    */
207   public static ImageDescriptor getImageDescriptor(String id) {
208     // Delegate to the plugin instance to avoid concurrent class loading problems
209     return getDefault().privateGetImageDescriptor(id);
210   }
211
212   /**
213    * Convenience method to get an image descriptor for an extension
214    * 
215    * @param extension
216    *          the extension declaring the image
217    * @param subdirectoryAndFilename
218    *          the path to the image
219    * @return the image
220    */
221   public static ImageDescriptor getImageDescriptorFromExtension(IExtension extension, String subdirectoryAndFilename) {
222     IPluginDescriptor pluginDescriptor = extension.getDeclaringPluginDescriptor();
223     URL path = pluginDescriptor.getInstallURL();
224     URL fullPathString = null;
225     try {
226       fullPathString = new URL(path, subdirectoryAndFilename);
227       return ImageDescriptor.createFromURL(fullPathString);
228     } catch (MalformedURLException e) {
229     }
230     return null;
231   }
232
233   public static String getResourceString(String key) {
234     ResourceBundle bundle = WikiEditorPlugin.getDefault().getResourceBundle();
235     try {
236       return (bundle != null) ? bundle.getString(key) : key;
237     } catch (MissingResourceException e) {
238       return key;
239     }
240   }
241
242   /**
243    * Returns the standard display to be used. The method first checks, if the thread calling this method has an associated display.
244    * If so, this display is returned. Otherwise the method returns the default display.
245    */
246   public static Display getStandardDisplay() {
247     Display display = Display.getCurrent();
248     if (display == null) {
249       display = Display.getDefault();
250     }
251     return display;
252   }
253
254   private ContributionContextTypeRegistry fContextTypeRegistry;
255
256   private ResourceBundle fResourceBundle;
257
258   private ContributionTemplateStore fTemplateStore;
259
260   private Hashtable imageDescriptors = new Hashtable(20);
261
262   public WikiEditorPlugin(IPluginDescriptor descriptor) {
263     super(descriptor);
264     initializeImages();
265     fgPlugin = this;
266     for (int i = 0; i < PREDEFINED_TYPES.length; i++) {
267       CONFIGURATION_TYPES.add(PREDEFINED_TYPES[i]);
268     }
269
270     for (int i = 0; i < PREDEFINED_WIKIS.length; i++) {
271       CONFIGURATION_TYPES.add(PREFIX_LOAD + PREDEFINED_WIKIS[i]);
272     }
273     for (int i = 0; i < PREDEFINED_WIKIS.length; i++) {
274       CONFIGURATION_TYPES.add(PREFIX_STORE + PREDEFINED_WIKIS[i]);
275     }
276     manager = ConfigurationManager.getInstance();
277     try {
278       fResourceBundle = ResourceBundle.getBundle("net.sourceforge.phpeclipse.wiki.editor.WikiEditorMessages");
279     } catch (MissingResourceException x) {
280       fResourceBundle = null;
281     }
282   }
283
284   /**
285    * Creates an image and places it in the image registry.
286    */
287   protected void createImageDescriptor(String id, URL baseURL) {
288     URL url = null;
289     try {
290       url = new URL(baseURL, ICON_PATH + id);
291     } catch (MalformedURLException e) {
292     }
293     ImageDescriptor desc = ImageDescriptor.createFromURL(url);
294     imageDescriptors.put(id, desc);
295   }
296
297   public IWorkbenchPage getActivePage() {
298     IWorkbenchWindow window = getWorkbench().getActiveWorkbenchWindow();
299     if (window != null)
300       return window.getActivePage();
301     return null;
302   }
303
304   public ContextTypeRegistry getContextTypeRegistry() {
305     if (fContextTypeRegistry == null) {
306       fContextTypeRegistry = new ContributionContextTypeRegistry();
307       fContextTypeRegistry.addContextType("net.sourceforge.phpeclipse.wiki.editor.templates");
308     }
309     return fContextTypeRegistry;
310   }
311
312   public Image getImage(String key) {
313     Image image = getImageRegistry().get(key);
314     if (image == null) {
315       ImageDescriptor d = getImageDescriptor(key);
316       image = d.createImage();
317       getImageRegistry().put(key, image);
318     }
319     return image;
320   }
321
322   public ResourceBundle getResourceBundle() {
323     return fResourceBundle;
324   }
325
326   public TemplateStore getTemplateStore() {
327     if (fTemplateStore == null) {
328       fTemplateStore = new ContributionTemplateStore(getContextTypeRegistry(), getDefault().getPreferenceStore(), "templates");
329       try {
330         fTemplateStore.load();
331       } catch (IOException e) {
332         e.printStackTrace();
333       }
334     }
335
336     return fTemplateStore;
337   }
338
339   private static boolean isDefined(String test) {
340     if (test != null && test.length() > 0) {
341       for (int i = 0; i < test.length(); i++) {
342         if (!Character.isWhitespace(test.charAt(i))) {
343           return false;
344         }
345       }
346     }
347     return true;
348   }
349
350   /*
351    * (non-Javadoc)
352    * 
353    * @see org.eclipse.ui.plugin.AbstractUIPlugin#initializeDefaultPreferences(org.eclipse.jface.preference.IPreferenceStore)
354    */
355   protected void initializeDefaultPreferences(IPreferenceStore store) {
356     store.setDefault(PREF_STRING_CONFIGURATIONS, CONFIG_MEMENTO);
357     store.setDefault(CONSOLE_OUTPUT, "true");
358
359     String operatingSystem = Platform.getOS();
360     // operatingSystem ==> maxosx, linux, solaris, win32,...
361     try {
362       InputStream is = getDefault().openStream(new Path("prefs/default_" + operatingSystem + ".properties"));
363       PropertyResourceBundle resourceBundle = new PropertyResourceBundle(is);
364
365       String key = HTTP_TIMEOUT;
366       try {
367         String timeout = resourceBundle.getString(key);
368         int val = Integer.parseInt(timeout);
369         if (val > 0) {
370           val *= 1000;
371         } else {
372           val = 30000;
373         }
374         store.setDefault(key, Integer.toString(val));
375       } catch (Exception e) {
376         store.setDefault(key, "30000"); // 30 seconds timeout
377       }
378
379       key = HTTP_PROXYHOST;
380       try {
381         String proxyHost = resourceBundle.getString(key);
382         if (isDefined(proxyHost)) {
383           store.setDefault(key, proxyHost);
384         } else {
385           store.setDefault(key, System.getProperty(key, ""));
386         }
387       } catch (Exception e) {
388         store.setDefault(key, System.getProperty(key, ""));
389       }
390
391       key = HTTP_PROXYPORT;
392       try {
393         String proxyPort = resourceBundle.getString(key);
394         if (isDefined(proxyPort)) {
395           // check for integer parse exception:
396           Integer.parseInt(proxyPort);
397           store.setDefault(key, proxyPort);
398         } else {
399           store.setDefault(key, System.getProperty(key, "80"));
400         }
401       } catch (Exception e) {
402         store.setDefault(key, System.getProperty(key, "80"));
403       }
404
405       key = HTTP_PROXYUSERNAME;
406       try {
407         String proxyUserName = resourceBundle.getString(key);
408         if (isDefined(proxyUserName)) {
409           store.setDefault(key, proxyUserName);
410         } else {
411           store.setDefault(key, System.getProperty(key, ""));
412         }
413       } catch (Exception e) {
414         store.setDefault(key, System.getProperty(key, ""));
415       }
416
417       key = HTTP_PROXYPASSWORD;
418       try {
419         String proxyPassWord = resourceBundle.getString(key);
420         if (isDefined(proxyPassWord)) {
421           store.setDefault(key, proxyPassWord);
422         } else {
423           store.setDefault(key, System.getProperty(key, ""));
424         }
425       } catch (Exception e) {
426         store.setDefault(key, System.getProperty(key, ""));
427       }
428       
429     } catch (Exception e) {
430     }
431
432   }
433
434   /*
435    * Initializes the table of images used in this plugin. The plugin is provided because this method is called before the plugin
436    * staic variable has been set. See the comment on the getPlugin() method for a description of why this is required.
437    */
438   private void initializeImages() {
439     URL baseURL = getDescriptor().getInstallURL();
440
441     //  special
442     createImageDescriptor("glyphs/glyph1.gif", baseURL); //$NON-NLS-1$
443     createImageDescriptor("glyphs/glyph2.gif", baseURL); //$NON-NLS-1$
444     createImageDescriptor("glyphs/glyph3.gif", baseURL); //$NON-NLS-1$
445     createImageDescriptor("glyphs/glyph4.gif", baseURL); //$NON-NLS-1$
446     createImageDescriptor("glyphs/glyph5.gif", baseURL); //$NON-NLS-1$
447     createImageDescriptor("glyphs/glyph6.gif", baseURL); //$NON-NLS-1$
448     createImageDescriptor("glyphs/glyph7.gif", baseURL); //$NON-NLS-1$
449     createImageDescriptor("glyphs/glyph8.gif", baseURL); //$NON-NLS-1$
450
451   }
452
453   public void log(String message) {
454     getDefault().getLog().log(new Status(IStatus.OK, PLUGIN_ID, IStatus.OK, message, null));
455   }
456
457   public void log(String message, Exception e) {
458     getDefault().getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, IStatus.OK, "Caught exception", e));
459   }
460
461   public void logAndReport(String title, String message, Exception e) {
462     log(message, e);
463     reportError(title, message);
464   }
465
466   private void privateCreateImageDescriptor(String id, URL baseURL) {
467     URL url = null;
468     try {
469       url = new URL(baseURL, ICON_PATH + id);
470     } catch (MalformedURLException e) {
471     }
472     ImageDescriptor desc = ImageDescriptor.createFromURL(url);
473     imageDescriptors.put(id, desc);
474   }
475
476   private ImageDescriptor privateGetImageDescriptor(String id) {
477     if (!imageDescriptors.containsKey(id)) {
478       URL baseURL = WikiEditorPlugin.getDefault().getDescriptor().getInstallURL();
479       createImageDescriptor(getDefault(), id, baseURL);
480     }
481     return (ImageDescriptor) imageDescriptors.get(id);
482   }
483
484   public void reportError(String title, String message) {
485     try {
486       //      Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
487       MessageDialog.openError(null, title, message);
488     } catch (RuntimeException e) {
489       log(e.getLocalizedMessage(), e);
490     }
491   }
492
493   public void startup() throws CoreException {
494     super.startup();
495   }
496
497   /**
498    * Returns the translated String found with the given key.
499    * 
500    * @return java.lang.String
501    * @param key
502    *          java.lang.String
503    */
504   public static String getResource(String key) {
505     try {
506       return Platform.getResourceString(getDefault().getBundle(), key);
507     } catch (Exception e) {
508       return key;
509     }
510   }
511
512   /**
513    * Returns the translated String found with the given key, and formatted with the given object.
514    * 
515    * @param key
516    *          java.lang.String
517    * @param obj
518    *          java.lang.Object[]
519    * @return java.lang.String
520    */
521   public static String getResource(String key, Object[] obj) {
522     try {
523       return MessageFormat.format(getResource(key), obj);
524     } catch (Exception e) {
525       return key;
526     }
527   }
528
529   /**
530    * Returns the translated String found with the given key, and formatted with the given object.
531    * 
532    * @param key
533    *          java.lang.String
534    * @param s
535    *          java.lang.String
536    * @return java.lang.String
537    */
538   public static String getResource(String key, String s) {
539     try {
540       return MessageFormat.format(getResource(key), new String[] { s });
541     } catch (Exception e) {
542       return key;
543     }
544   }
545
546   /**
547    * Return a list of all the existing configurations.
548    * 
549    * @return java.util.List
550    */
551   public static List getConfigurations() {
552     return manager.getConfigurations();
553   }
554
555   /**
556    * Create a new monitor.
557    * 
558    * @return working copy
559    */
560   public static IConfigurationWorkingCopy createConfiguration() {
561     return manager.createConfiguration();
562   }
563
564   public static ArrayList getTypes() {
565     return CONFIGURATION_TYPES;
566   }
567
568   public static void addType(String type) {
569     CONFIGURATION_TYPES.add(type);
570   }
571
572   /*
573    * (non-Javadoc)
574    * 
575    * @see org.eclipse.core.runtime.Plugin#shutdown()
576    */
577   public void shutdown() throws CoreException {
578     if (fWikiDB != null) {
579       try {
580         fWikiDB.shutdown();
581       } catch (SQLException e) {
582       }
583     }
584     super.shutdown();
585   }
586
587   public static void log(int severity, String message) {
588     Status status = new Status(severity, PLUGIN_ID, IStatus.OK, message, null);
589     log(status);
590   }
591
592   public static void log(IStatus status) {
593     getDefault().getLog().log(status);
594   }
595
596   public static void log(Throwable e) {
597     log(new Status(IStatus.ERROR, PLUGIN_ID, IStatus.ERROR, "PHPeclipsePlugin.internalErrorOccurred", e)); //$NON-NLS-1$
598   }
599
600   /**
601    * Get a IWikpedia singleton instance through reflection (i.e. Method#invoke() )
602    * 
603    * @param wikiLocale
604    * @return
605    * @throws NoSuchMethodException
606    * @throws IllegalAccessException
607    * @throws ClassNotFoundException
608    * @throws InvocationTargetException
609    */
610   public static IWikipedia getWikiInstance(String wikiLocale) throws NoSuchMethodException, IllegalAccessException,
611       ClassNotFoundException, InvocationTargetException {
612     String className = "net.sourceforge.phpeclipse.wiki.actions.mediawiki.config." + wikiLocale;
613     Class cls = Class.forName(className);
614     Method method = cls.getMethod("getInstance", new Class[0]);
615     return (IWikipedia) method.invoke(null, new Object[0]);
616   }
617
618   /**
619    * Returns the workspace instance.
620    */
621   public static IWorkspace getWorkspace() {
622     return ResourcesPlugin.getWorkspace();
623   }
624
625   // test code
626   //  public static void main(String[] args) {
627   //    try {
628   //      getWikiInstance("WikipediaEN");
629   //    } catch (NoSuchMethodException e) {
630   //      // TODO Auto-generated catch block
631   //      e.printStackTrace();
632   //    } catch (IllegalAccessException e) {
633   //      // TODO Auto-generated catch block
634   //      e.printStackTrace();
635   //    } catch (ClassNotFoundException e) {
636   //      // TODO Auto-generated catch block
637   //      e.printStackTrace();
638   //    } catch (InvocationTargetException e) {
639   //      // TODO Auto-generated catch block
640   //      e.printStackTrace();
641   //    }
642   //  }
643
644 }