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