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