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