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