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