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