4ee5c3573b7297cee370231ccd8dfdc52a29b051
[phpeclipse.git] / archive / net.sourceforge.phpeclipse.wiki / src / net / sourceforge / phpeclipse / wiki / actions / mediawiki / post / PostJob.java
1 package net.sourceforge.phpeclipse.wiki.actions.mediawiki.post;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.io.InputStreamReader;
6 import java.io.StringWriter;
7 import java.util.HashMap;
8
9 import net.sourceforge.phpeclipse.wiki.actions.ProblemConsole;
10 import net.sourceforge.phpeclipse.wiki.actions.mediawiki.config.IWikipedia;
11 import net.sourceforge.phpeclipse.wiki.actions.mediawiki.connect.Content;
12 import net.sourceforge.phpeclipse.wiki.actions.mediawiki.connect.MediaWikiConnector;
13 import net.sourceforge.phpeclipse.wiki.actions.mediawiki.exceptions.MethodException;
14 import net.sourceforge.phpeclipse.wiki.actions.mediawiki.exceptions.PageNotEditableException;
15 import net.sourceforge.phpeclipse.wiki.actions.mediawiki.exceptions.UnexpectedAnswerException;
16 import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin;
17 import net.sourceforge.phpeclipse.wiki.internal.Configuration;
18 import net.sourceforge.phpeclipse.wiki.preferences.Util;
19 import net.sourceforge.phpeclipse.wiki.velocity.EditorText;
20 import net.sourceforge.phpeclipse.wiki.xml.Page;
21 import net.sourceforge.phpeclipse.wiki.xml.XStreamManager;
22
23 import org.apache.velocity.VelocityContext;
24 import org.apache.velocity.app.Velocity;
25 import org.eclipse.core.resources.IFile;
26 import org.eclipse.core.resources.ResourcesPlugin;
27 import org.eclipse.core.resources.WorkspaceJob;
28 import org.eclipse.core.runtime.CoreException;
29 import org.eclipse.core.runtime.IPath;
30 import org.eclipse.core.runtime.IProgressMonitor;
31 import org.eclipse.core.runtime.IStatus;
32 import org.eclipse.core.runtime.Path;
33 import org.eclipse.core.runtime.Status;
34 import org.eclipse.core.runtime.jobs.Job;
35 import org.eclipse.ui.progress.IProgressConstants;
36
37 public class PostJob extends WorkspaceJob {
38   IFile[] files;
39
40   IWikipedia wikipedia;
41
42   Configuration configuration;
43
44   String user;
45
46   String password;
47
48   public PostJob(Configuration configuration, IWikipedia wikipedia, String user, String password, IFile[] files) {
49     super("Refresh Job");
50     this.files = files;
51     this.wikipedia = wikipedia;
52     this.user = user;
53     this.password = password;
54     this.configuration = configuration;
55   }
56
57   public String generateUrl(String template, String wikiname) {
58     EditorText text = new EditorText(null);
59     /* first, we init the runtime engine. Defaults are fine. */
60
61     try {
62       Velocity.init();
63
64       /* lets make a Context and put data into it */
65
66       VelocityContext context = new VelocityContext();
67
68       context.put("config", configuration);
69       text.clear();
70       text.setWikiname(wikiname);
71       context.put("text", text);
72
73       /* lets make our own string to render */
74       StringWriter w = new StringWriter();
75       w = new StringWriter();
76       Velocity.evaluate(context, w, "mystring", template);
77       return w.toString();
78
79     } catch (Exception e) {
80       // TODO Auto-generated catch block
81       e.printStackTrace();
82     }
83     return template;
84   }
85
86   private void uploadWiki(String timestamp, String body, MediaWikiConnector connector, String actionUrl, String wikiName)
87       throws UnexpectedAnswerException, MethodException, PageNotEditableException, InterruptedException {
88
89     String url = generateUrl(configuration.getURL(), wikiName);
90     //      System.out.println(timestamp);
91     Content content = new Content(timestamp, body);
92
93     connector.store(wikipedia, actionUrl, wikiName, content, "", false, false);
94
95   }
96
97   public IStatus runInWorkspace(IProgressMonitor monitor) {
98     boolean success = false;
99     IFile file = null;
100     MediaWikiConnector connector = null;
101     InputStream is = null;
102     ProblemConsole console = new ProblemConsole();
103     String actionUrl = configuration.getURL();
104     if (actionUrl == null || actionUrl.equals("")) {
105       // fall back to default settings
106       actionUrl = wikipedia.getActionUrl();
107     }
108     try {
109       if (files.length > 0) {
110         // prefetch for error messages
111         file = files[0];
112       }
113       monitor.beginTask("Upload Wiki Articles: ", 100);
114       int partWork = 100 / files.length;
115       int work = 0;
116       StringBuffer buffer = new StringBuffer();
117       HashMap map = new HashMap();
118       String wikiURLTitle;
119
120       monitor.subTask("Login user:" + user);
121       connector = new MediaWikiConnector();
122       success = connector.login(wikipedia, actionUrl, user, password, false);
123       if (success) {
124         for (int i = 0; i < files.length; i++) {
125           try {
126             file = files[i];
127             is = file.getContents();
128             wikiURLTitle = Util.getURLWikiName(file);
129             String body = StoreWikipediaAction.getInputStreamAsString(is, wikipedia.getCharSet());
130             char ch;
131             boolean noContent = checkNoContent(body);
132             String srcBasePath = Util.getWikiTextsPath(file);
133             String binBasePath = Util.getProjectsWikiOutputPath(file.getProject(), WikiEditorPlugin.HTML_OUTPUT_PATH);
134
135             String fileXMLName = Util.getXMLFileName(file, binBasePath, srcBasePath);
136             IPath path = new Path(fileXMLName);
137             IFile xmlFile = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(path);
138
139             String timestamp = "";
140             if (xmlFile.exists()) {
141               try {
142                 Page page = XStreamManager.fromXML(xmlFile.getContents());
143                 if (page != null) {
144                   // we've stored information about the article at download time which
145                   // may be more exactly as the standard information
146                   if (!page.isEmpty()) {
147                     // at least one revision exists:
148                     timestamp = page.get(0).getTimestamp();
149                   }
150                   wikiURLTitle = page.getURLTitle();
151                 }
152                 //                timestamp = XMLReader.getDateTimestamp(xmlFile.getContents());
153               } catch (Exception e2) {
154               }
155             }
156
157             if (noContent) {
158               console.println("File: " + file.getLocation().toString() + "\n==>upload not allowed; Wiki text contains no content");
159             } else {
160               monitor.subTask("Upload: " + file.getLocation().toString());
161               uploadWiki(timestamp, body, connector, actionUrl, wikiURLTitle);
162             }
163
164           } catch (CoreException e1) {
165             if (file != null) {
166               console.println("File: " + file.getLocation().toString() + "\n==>CoreException: " + e1.getMessage());
167             }
168           }
169           if (monitor.isCanceled()) {
170             return Status.CANCEL_STATUS;
171           }
172           work += partWork;
173           monitor.worked(work);
174         }
175       }
176
177       if (isModal(this)) {
178         // The progress dialog is still open show the message
179       } else {
180         setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE);
181         //            setProperty(IProgressConstants.ACTION_PROPERTY, getWikisCompletedAction());
182       }
183       return Status.OK_STATUS;
184       //        } catch(CoreException e) {
185       //          return e.getStatus();
186     } catch (IOException e) {
187       if (file != null) {
188         console.println("File: " + file.getLocation().toString());
189       }
190       console.println("==>IOException: " + e.getMessage());
191     } catch (UnexpectedAnswerException e) {
192       console.println("==>UnexpectedAnswerException: " + e.getMessage());
193     } catch (InterruptedException e) {
194       if (file != null) {
195         console.println("File: " + file.getLocation().toString());
196       }
197       console.println("==>InterruptedException: " + e.getMessage());
198     } catch (PageNotEditableException e) {
199       if (file != null) {
200         console.println("File: " + file.getLocation().toString());
201       }
202       console.println("==>PageNotEditableException: " + e.getMessage());
203     } catch (MethodException e) {
204       if (file != null) {
205         console.println("File: " + file.getLocation().toString());
206       }
207       console.println("==>HTTP-MethodException: " + e.getMessage());
208     } finally {
209       monitor.done();
210       if (success && connector != null) {
211         try {
212           monitor.subTask("Logout!");
213           connector.logout(wikipedia, actionUrl);
214         } catch (UnexpectedAnswerException e1) {
215           console.println("==>UnexpectedAnswerException: " + e1.getMessage());
216         } catch (MethodException e1) {
217           console.println("==>HTTP-MethodException: " + e1.getMessage());
218         }
219       }
220       if (is != null) {
221         try {
222           is.close();
223         } catch (IOException e1) {
224         }
225       }
226     }
227     if (isModal(this)) {
228       // The progress dialog is still open show the message
229     }
230     return Status.CANCEL_STATUS;
231   }
232
233   /**
234    * @param body
235    * @param j
236    * @return
237    */
238   private boolean checkNoContent(String body) {
239     char ch;
240     boolean noContent = true;
241     int j = 0;
242     try {
243       while (true) {
244         ch = body.charAt(j++);
245         if (!Character.isWhitespace(ch)) {
246           if (ch == '<' && body.charAt(j) == '!' && body.charAt(j + 1) == '-' && body.charAt(j + 2) == '-') {
247             //<!-- ... -->
248             j += 3;
249             while (true) {
250               ch = body.charAt(j++);
251               if (ch == '-' && body.charAt(j) == '-' && body.charAt(j + 1) == '>') {
252                 j += 2;
253                 break;
254               }
255             }
256           } else if (ch == '<' && body.charAt(j) == 'b' && body.charAt(j + 1) == 'r' && body.charAt(j + 2) == '>') {
257             // <br>
258           } else {
259             noContent = false;
260             break;
261           }
262         }
263       }
264     } catch (IndexOutOfBoundsException e) {
265
266     }
267     return noContent;
268   }
269
270   public boolean isModal(Job job) {
271     Boolean isModal = (Boolean) job.getProperty(IProgressConstants.PROPERTY_IN_DIALOG);
272     if (isModal == null) {
273       return false;
274     }
275     return isModal.booleanValue();
276   }
277
278 }