1) Added missing strings for italic, underline and strike through.
[phpeclipse.git] / archive / net.sourceforge.phpeclipse.wiki / src / net / sourceforge / phpeclipse / wiki / actions / mediawiki / RefreshJob.java
1 package net.sourceforge.phpeclipse.wiki.actions.mediawiki;
2
3 import java.io.ByteArrayInputStream;
4 import java.io.UnsupportedEncodingException;
5 import java.util.ArrayList;
6 import java.util.HashMap;
7
8 import net.sourceforge.phpeclipse.wiki.actions.ProblemConsole;
9 import net.sourceforge.phpeclipse.wiki.actions.mediawiki.config.IWikipedia;
10 import net.sourceforge.phpeclipse.wiki.actions.mediawiki.connect.MediaWikiConnector;
11 import net.sourceforge.phpeclipse.wiki.actions.mediawiki.connect.Parsed;
12 import net.sourceforge.phpeclipse.wiki.actions.mediawiki.exceptions.MethodException;
13 import net.sourceforge.phpeclipse.wiki.actions.mediawiki.exceptions.UnexpectedAnswerException;
14 import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin;
15 import net.sourceforge.phpeclipse.wiki.preferences.Util;
16 import net.sourceforge.phpeclipse.wiki.xml.Page;
17 import net.sourceforge.phpeclipse.wiki.xml.XStreamManager;
18
19 import org.eclipse.core.resources.IContainer;
20 import org.eclipse.core.resources.IFile;
21 import org.eclipse.core.resources.IFolder;
22 import org.eclipse.core.resources.ResourcesPlugin;
23 import org.eclipse.core.resources.WorkspaceJob;
24 import org.eclipse.core.runtime.CoreException;
25 import org.eclipse.core.runtime.IPath;
26 import org.eclipse.core.runtime.IProgressMonitor;
27 import org.eclipse.core.runtime.IStatus;
28 import org.eclipse.core.runtime.Path;
29 import org.eclipse.core.runtime.Status;
30 import org.eclipse.core.runtime.jobs.Job;
31 import org.eclipse.ui.progress.IProgressConstants;
32
33 public class RefreshJob extends WorkspaceJob {
34   IFile[] files;
35
36   IWikipedia configuration;
37
38   String actionURL;
39
40   public RefreshJob(IWikipedia configuration, IFile[] files, String actionURL) {
41     super("Refresh Job");
42     this.files = files;
43     this.configuration = configuration;
44     this.actionURL = actionURL;
45   }
46
47   public IStatus runInWorkspace(IProgressMonitor monitor) {
48     ProblemConsole console = new ProblemConsole();
49     IFile file = null;
50
51     try {
52       int totalWork = files.length;
53       if (totalWork <= 0) {
54         totalWork = 100;
55       }
56       monitor.beginTask("Download Wiki Articles: ", totalWork);
57       //      ArrayList wikiTitles = new ArrayList();
58       //      for (int i = 0; i < files.length; i++) {
59       //        wikiTitles.add( Util.getReadableWikiName(files[i]) );
60       //      }
61       StringBuffer buffer = new StringBuffer();
62       HashMap map = new HashMap();
63       MediaWikiConnector mwConnector = new MediaWikiConnector();
64       String wikiTitle;
65       int titleCounter = 0;
66       for (int i = 0; i < files.length; i++) {
67         file = files[i];
68         wikiTitle = createWikiTitle(file, i);
69         buffer.append(wikiTitle);
70         titleCounter++;
71         map.put(wikiTitle, file);
72         if (i != files.length - 1) {
73           buffer.append("\n");
74         }
75         if (i % 5 == 0) {
76           // read only 5 files at a time
77           IStatus status = readWikisFromBuffer(mwConnector, buffer, map, monitor, console);
78           if (status.equals(Status.CANCEL_STATUS)) {
79             return Status.CANCEL_STATUS;
80           }
81           buffer = new StringBuffer();
82           titleCounter = 0;
83         }
84       }
85       if (titleCounter > 0) {
86         IStatus status = readWikisFromBuffer(mwConnector, buffer, map, monitor, console);
87         if (status.equals(Status.CANCEL_STATUS)) {
88           return Status.CANCEL_STATUS;
89         }
90         buffer = new StringBuffer();
91         titleCounter = 0;
92       }
93
94       if (isModal(this)) {
95         // The progress dialog is still open show the message
96       } else {
97         //        setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE);
98         //            setProperty(IProgressConstants.ACTION_PROPERTY, getWikisCompletedAction());
99       }
100       return Status.OK_STATUS;
101       //        } catch(CoreException e) {
102       //          return e.getStatus();
103     } catch (UnexpectedAnswerException e) {
104       if (file != null) {
105         console.println("File: " + file.getLocation().toString() + "\n==>UnexpectedAnswerException: " + e.getMessage());
106       } else {
107         console.println("UnexpectedAnswerException: " + e.getMessage());
108       }
109     } catch (MethodException e) {
110       if (file != null) {
111         console.println("File: " + file.getLocation().toString() + "\n==>HTTP-MethodException: " + e.getMessage());
112       } else {
113         console.println("HTTP-MethodException: " + e.getMessage());
114       }
115     } catch (InterruptedException e) {
116       if (file != null) {
117         console.println("File: " + file.getLocation().toString() + "\n==>InterruptedException: " + e.getMessage());
118       } else {
119         console.println("InterruptedException: " + e.getMessage());
120       }
121     } finally {
122       monitor.done();
123     }
124     if (isModal(this)) {
125       // The progress dialog is still open show the message
126     }
127     return Status.OK_STATUS;
128   }
129
130   /**
131    * @param buffer
132    * @param map
133    * @param monitor
134    * @param console
135    * @param file
136    * @return
137    * @throws UnexpectedAnswerException
138    * @throws MethodException
139    */
140   private IStatus readWikisFromBuffer(MediaWikiConnector mwConnector, StringBuffer buffer, HashMap map, IProgressMonitor monitor,
141       ProblemConsole console) throws UnexpectedAnswerException, InterruptedException, MethodException {
142     String wikiTitle;
143     boolean showConsole = WikiEditorPlugin.getDefault().getPreferenceStore().getBoolean(WikiEditorPlugin.CONSOLE_OUTPUT);
144
145     String url = actionURL;
146     if (url == null) {
147       url = configuration.getActionUrl() + "/" + configuration.getSpecialNs() + ":Export";
148     }
149     // get a list of Parsed elements
150     monitor.subTask("Downloading (XML Import)");
151     if (showConsole) {
152       console.println("Downloading (XML Import):\n" + buffer.toString());
153     }
154     ArrayList list = mwConnector.loadXML(configuration, url, buffer.toString());
155     String body;
156     IFile file = null;
157     for (int i = 0; i < list.size(); i++) {
158       Parsed parsed = (Parsed) list.get(i);
159       wikiTitle = parsed.getTitle();
160       if (wikiTitle != null) {
161         body = parsed.getBody();
162         if (body != null) {
163           file = (IFile) map.get(wikiTitle);
164           if (file != null) {
165             // rearrange parsed data into a page for XStream hamdling:
166             Page page = new Page(parsed.getDateTimestamp(), wikiTitle, body);
167             monitor.subTask("Modify file: " + file.getLocation().toString());
168             if (showConsole) {
169               console.println("Update file: " + file.getLocation().toString());
170             }
171             updateFileContent(console, file, page, body, configuration, monitor);
172           }
173         }
174       }
175       monitor.worked(1);
176       if (monitor.isCanceled()) {
177         return Status.CANCEL_STATUS;
178       }
179     }
180
181     return Status.OK_STATUS;
182   }
183
184   /**
185    * @param file
186    * @param wikiTitle
187    * @param i
188    * @return
189    */
190   private String createWikiTitle(IFile file, int i) {
191     String wikiTitle = null;
192     String srcBasePath = Util.getWikiTextsPath(file);
193     String binBasePath = Util.getProjectsWikiOutputPath(file.getProject(), WikiEditorPlugin.HTML_OUTPUT_PATH);
194
195     String fileXMLName = Util.getXMLFileName(file, binBasePath, srcBasePath);
196     IPath path = new Path(fileXMLName);
197     IFile xmlFile = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(path);
198     if (xmlFile.exists()) {
199       try {
200         Page page = XStreamManager.fromXML(xmlFile.getContents());
201         if (page != null) {
202           wikiTitle = page.getTitle();
203         }
204         //                timestamp = XMLReader.getDateTimestamp(xmlFile.getContents());
205       } catch (Exception e2) {
206       }
207     }
208     if (wikiTitle == null) {
209       // if no XML file exists we create the name from the filename
210       wikiTitle = Util.getReadableWikiName(files[i]);
211     }
212     return wikiTitle;
213   }
214
215   public boolean isModal(Job job) {
216     Boolean isModal = (Boolean) job.getProperty(IProgressConstants.PROPERTY_IN_DIALOG);
217     if (isModal == null) {
218       return false;
219     }
220     return isModal.booleanValue();
221   }
222
223   private static void updateFileContent(ProblemConsole console, IFile file, Page page, String body, IWikipedia wp,
224       IProgressMonitor monitor) {
225     try {
226       if (file.exists()) {
227         if (wp == null) {
228           file.setContents(new ByteArrayInputStream(body.getBytes()), true, false, null);
229         } else {
230           file.setContents(new ByteArrayInputStream(body.getBytes(wp.getCharSet())), true, false, null);
231           file.setCharset(wp.getCharSet(), monitor);
232         }
233       } else {
234         if (wp == null) {
235           file.create(new ByteArrayInputStream(body.getBytes()), false, null);
236         } else {
237           file.create(new ByteArrayInputStream(body.getBytes(wp.getCharSet())), false, null);
238           file.setCharset(wp.getCharSet(), monitor);
239         }
240       }
241       String srcBasePath = Util.getWikiTextsPath(file);
242       String binBasePath = Util.getProjectsWikiOutputPath(file.getProject(), WikiEditorPlugin.HTML_OUTPUT_PATH);
243
244       String filename = Util.getXMLFileName(file, binBasePath, srcBasePath);
245       IPath path = new Path(filename);
246       IFile xmlFile = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(path);
247       IContainer parent = xmlFile.getParent();
248       if (parent instanceof IFolder && (!((IFolder) parent).exists())) {
249         Util.createFolder((IFolder) parent, monitor);
250       }
251       try {
252         //        String xmlData = parsed.getXmlData();
253         //        String charSet = "UTF-8";
254         //        StringBuffer buf = new StringBuffer();
255         //        int index = xmlData.indexOf("<page>");
256         //        if (index<0) {
257         //          console.println("File: " + xmlFile.getLocation().toString() + "\n==>Couldn't create xml file - <page> tag not found");
258         //          return;
259         //        }
260         //        xmlData = xmlData.substring(index);
261         //        buf.append(WikiEditorPlugin.XML_START_1);
262         //        buf.append(charSet);
263         //        buf.append(WikiEditorPlugin.XML_START_2);
264         //        buf.append(xmlData);
265         //        buf.append(WikiEditorPlugin.XML_END);
266
267         //        byte[] buffer = buf.toString().getBytes();
268         byte[] buffer = XStreamManager.toXML(page).getBytes();
269         ByteArrayInputStream source = new ByteArrayInputStream(buffer);
270         if (!xmlFile.exists()) {
271           xmlFile.create(source, true, monitor);
272         } else {
273           xmlFile.setContents(source, true, true, monitor);
274         }
275       } catch (CoreException e) {
276         if (file != null) {
277           console.println("File: " + xmlFile.getLocation().toString() + "\n==>CoreException: " + e.getMessage());
278         }
279       }
280     } catch (UnsupportedEncodingException e) {
281       console.println("File: " + file.getLocation().toString() + "\n==>UnsupportedEncodingException: " + e.getMessage());
282     } catch (Exception e) {
283       console.println("File: " + file.getLocation().toString() + "\n==>Exception: " + e.getMessage());
284     }
285   }
286 }