Enable word wrapping with preference key editor.wrap.words (false by default)
[phpeclipse.git] / archive / net.sourceforge.phpeclipse.wiki / src / net / sourceforge / phpeclipse / wiki / actions / mediawiki / connect / MediaWikiConnector.java
1 package net.sourceforge.phpeclipse.wiki.actions.mediawiki.connect;
2
3 //Parts of this sources are copied and modified from the jEdit Wikipedia plugin:
4 //http://www.djini.de/software/wikipedia/index.html
5 //
6 //The modified sources are available under the "Common Public License"
7 //with permission from the original author: Daniel Wunsch
8
9 import java.io.IOException;
10 import java.io.StringReader;
11 import java.io.UnsupportedEncodingException;
12 import java.net.URLDecoder;
13 import java.util.ArrayList;
14 import java.util.regex.Matcher;
15 import java.util.regex.Pattern;
16
17 import net.sourceforge.phpeclipse.wiki.actions.mediawiki.config.IWikipedia;
18 import net.sourceforge.phpeclipse.wiki.actions.mediawiki.exceptions.MethodException;
19 import net.sourceforge.phpeclipse.wiki.actions.mediawiki.exceptions.PageNotEditableException;
20 import net.sourceforge.phpeclipse.wiki.actions.mediawiki.exceptions.UnexpectedAnswerException;
21 import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin;
22
23 import org.apache.commons.httpclient.ConnectMethod;
24 import org.apache.commons.httpclient.HostConfiguration;
25 import org.apache.commons.httpclient.HttpClient;
26 import org.apache.commons.httpclient.HttpConnection;
27 import org.apache.commons.httpclient.HttpException;
28 import org.apache.commons.httpclient.HttpMethod;
29 import org.apache.commons.httpclient.HttpState;
30 import org.apache.commons.httpclient.HttpStatus;
31 import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
32 import org.apache.commons.httpclient.NameValuePair;
33 import org.apache.commons.httpclient.URI;
34 import org.apache.commons.httpclient.UsernamePasswordCredentials;
35 import org.apache.commons.httpclient.methods.GetMethod;
36 import org.apache.commons.httpclient.methods.PostMethod;
37 import org.apache.commons.httpclient.protocol.Protocol;
38 import org.apache.commons.httpclient.util.EncodingUtil;
39 import org.eclipse.core.runtime.CoreException;
40 import org.eclipse.core.runtime.Preferences;
41
42 /**
43  * This class gets the wikitext from a wikipedia edit page
44  * 
45  * The basic coding was copied from the commons-httpclient example <code>MediaWikiConnector.java</code>
46  */
47 public class MediaWikiConnector {
48   //pattern used to scarp an edit page
49   private static final Pattern BODY_PATTERN = Pattern.compile(
50   /*
51    * action=".*?title=(.*?)(&amp;|\") <form id="editform" name="editform" method="post"
52    * action="/w/wiki.phtml?title=Ammersee&amp;action=submit" locked pages: <textarea cols='80' rows='25' readonly>
53    */
54   ".*<form[^>]*\\sid=\"editform\"[^>]*title=(.*?)&amp;[^>]*>" + ".*<textarea[^>]*\\sname=\"wpTextbox1\"[^>]*>(.*?)</textarea>"
55       + ".*<input[^>]*\\svalue=\"(\\d*)\"[^>]*\\sname=\"wpEdittime\"[^>]*>" + ".*", Pattern.DOTALL);
56
57   //  <input type='hidden' value="53ee6d8b42ff9b7d" name="wpEditToken" />
58   private static final Pattern EDIT_TOKEN = Pattern.compile(
59       ".*<input\\stype='hidden'\\svalue=\"(.*?)\"\\sname=\"wpEditToken\"\\s/>.*", Pattern.DOTALL);
60
61   //setup default user agent
62   final static public String userAgent = "plog4u.org/0.0";
63
64   // create a ConnectionManager
65   private MultiThreadedHttpConnectionManager manager;
66
67   private HttpClient client;
68
69   /**
70    * Delay a new store to 1 second
71    */
72   private Throttle storeThrottle = new Throttle(1000);
73
74   class Throttle {
75     private long nextTime = 0;
76
77     private final long minimumDelay;
78
79     public Throttle(long minimumDelay) {
80       this.minimumDelay = minimumDelay;
81     }
82
83     /** this is called from the client */
84     public synchronized void delay() throws InterruptedException {
85       long delay = nextTime - System.currentTimeMillis();
86       if (delay > 0)
87         Thread.sleep(delay);
88       nextTime = System.currentTimeMillis() + minimumDelay;
89     }
90   }
91
92   public MediaWikiConnector() {
93     // <a href="javascript:window.location.href='http://127.0.0.1:8009/open/?' + window.location.href">bookmarklet</a>
94     manager = new MultiThreadedHttpConnectionManager();
95     manager.setMaxConnectionsPerHost(6);
96     manager.setMaxTotalConnections(18);
97     manager.setConnectionStaleCheckingEnabled(true);
98     // open the conversation
99     client = new HttpClient(manager);
100     setHTTPClientParameters(client);
101     //client.State.CookiePolicy = CookiePolicy.COMPATIBILITY;
102     //client.HostConfiguration.setHost(LOGON_SITE, LOGON_PORT, "http");
103   }
104
105   /** destructor freeing all resources. the Connection is not usable any more after calling this method */
106   public void destroy() {
107     manager.shutdown();
108   }
109
110   /** log in - returns success */
111   public boolean login(IWikipedia config, String actionUrl, String user, String password, boolean remember)
112       throws UnexpectedAnswerException, MethodException {
113     PostMethod method = new PostMethod(actionUrl);
114     method.setFollowRedirects(false);
115     method.addRequestHeader("User-Agent", userAgent);
116     NameValuePair[] params = new NameValuePair[] {
117         new NameValuePair("title", config.getLoginTitle()),
118         new NameValuePair("action", "submit"),
119         new NameValuePair("wpName", user),
120         new NameValuePair("wpPassword", password),
121         new NameValuePair("wpRemember", remember ? "1" : "0"),
122         new NameValuePair("wpLoginattempt", "submit") };
123     method.addParameters(params);
124
125     boolean result;
126     try {
127       int responseCode = client.executeMethod(method);
128       String responseBody = method.getResponseBodyAsString();
129
130       //### debugging
131       //log(responseBody);
132       //                        log(method);
133
134       if (responseCode == 302 && responseBody.length() == 0 || responseCode == 200
135           && responseBody.matches(config.getLoginSuccess())) {
136         result = true;
137       } else if (responseCode == 200 && responseBody.matches(config.getLoginWrongPw()) || responseCode == 200
138           && responseBody.matches(config.getLoginNoUser())) {
139         result = false;
140         if (responseBody.matches(config.getLoginNoUser())) {
141           throw new UnexpectedAnswerException("login not successful: wrong user name: " + user);
142         } else if (responseBody.matches(config.getLoginWrongPw())) {
143           throw new UnexpectedAnswerException("login not successful: wrong password for user: " + user);
144         } else {
145           throw new UnexpectedAnswerException("logout not successful: responseCode == 200");
146         }
147       } else {
148         throw new UnexpectedAnswerException("login not successful: " + method.getStatusLine());
149       }
150     } catch (HttpException e) {
151       throw new MethodException("method failed", e);
152     } catch (IOException e) {
153       throw new MethodException("method failed", e);
154     } finally {
155       method.releaseConnection();
156     }
157     /*
158      * // display cookies System.err.println("login: " + result); for (var cookie : client.State.Cookies) {
159      * System.err.println("cookie: " + cookie); }
160      */
161
162     // remember state
163     SiteState state = SiteState.siteState(config);
164     state.loggedIn = result;
165     state.userName = user;
166
167     return result;
168   }
169
170   /** log out - return success */
171   public boolean logout(IWikipedia config, String actionUrl) throws UnexpectedAnswerException, MethodException {
172     GetMethod method = new GetMethod(actionUrl);
173     method.setFollowRedirects(false);
174     method.addRequestHeader("User-Agent", userAgent);
175     NameValuePair[] params = new NameValuePair[] {
176         new NameValuePair("title", config.getLogoutTitle()),
177         new NameValuePair("action", "submit") };
178     method.setQueryString(EncodingUtil.formUrlEncode(params, config.getCharSet()));
179
180     boolean result;
181     try {
182       int responseCode = client.executeMethod(method);
183       String responseBody = method.getResponseBodyAsString();
184       //                        log(method);
185
186       if (responseCode == 302 && responseBody.length() == 0 || responseCode == 200
187           && responseBody.matches(config.getLogoutSuccess())) {
188         //                              config.getloggedIn = false;
189         result = true;
190       } else if (responseCode == 200) {
191         //### should check for a failure message
192         result = false;
193         throw new UnexpectedAnswerException("logout not successful: responseCode == 200");
194       } else {
195         throw new UnexpectedAnswerException("logout not successful: " + method.getStatusLine());
196       }
197     } catch (HttpException e) {
198       throw new MethodException("method failed", e);
199     } catch (IOException e) {
200       throw new MethodException("method failed", e);
201     } finally {
202       method.releaseConnection();
203     }
204
205     // remember state
206     SiteState state = SiteState.siteState(config);
207     state.loggedIn = false;
208
209     return result;
210   }
211
212   /** parses a returned editform for the sessions wpEditToken */
213   private String parseEditToken(String charSet, String responseBody) throws PageNotEditableException {
214     Matcher matcher = EDIT_TOKEN.matcher(responseBody);
215     if (!matcher.matches()) {
216       return null;
217     }
218
219     return matcher.group(1);
220   }
221
222   /**
223    * returns the edit token or <code>null</code> if no token is available
224    * 
225    * @param actionURL
226    * @param charSet
227    * @param title
228    * @return
229    * @throws UnexpectedAnswerException
230    * @throws MethodException
231    * @throws PageNotEditableException
232    */
233   public String loadEditToken(String actionURL, String charSet, String title) throws UnexpectedAnswerException, MethodException,
234       PageNotEditableException {
235     GetMethod method = new GetMethod(actionURL);
236     method.setFollowRedirects(false);
237     method.addRequestHeader("User-Agent", userAgent);
238     NameValuePair[] params = new NameValuePair[] { new NameValuePair("title", title), new NameValuePair("action", "edit") };
239     method.setQueryString(EncodingUtil.formUrlEncode(params, charSet));
240
241     try {
242       int responseCode = client.executeMethod(method);
243       String responseBody = method.getResponseBodyAsString();
244       //                        log(method);
245
246       if (responseCode == 200) {
247         String parsed = parseEditToken(charSet, responseBody);
248         if (parsed != null && parsed.length() == 0) {
249           return null;
250         }
251         return parsed;
252       } else {
253         throw new UnexpectedAnswerException("load not successful: expected 200 OK, got " + method.getStatusLine());
254       }
255     } catch (HttpException e) {
256       throw new MethodException("method failed", e);
257     } catch (IOException e) {
258       throw new MethodException("method failed", e);
259     } finally {
260       method.releaseConnection();
261     }
262   }
263
264   /** parses a returned editform into a Content object with UNIX-EOLs ("\n") */
265   private Parsed parseBody(String charSet, String responseBody) throws PageNotEditableException, UnsupportedEncodingException {
266     Matcher matcher = BODY_PATTERN.matcher(responseBody);
267     if (!matcher.matches())
268       throw new PageNotEditableException("cannot find editform form");
269
270     String title = matcher.group(1);
271     String body = matcher.group(2);
272     String timestamp = matcher.group(3);
273     String tokenEdit = null;
274     //    String tokenEdit = matcher.group(4);
275     title = URLDecoder.decode(title, charSet);
276     body = body.replaceAll("&quot;", "\"").replaceAll("&apos;", "'").replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll(
277         "&amp;", "&").replaceAll("\r\n", "\n").replace('\r', '\n');
278
279     return new Parsed(timestamp, title, body, tokenEdit);
280   }
281
282   /** load a Page Version - returns a Loaded Object */
283   public Loaded load(String actionURL, String charSet, String title) throws UnexpectedAnswerException, MethodException,
284       PageNotEditableException {
285     GetMethod method = new GetMethod(actionURL);
286     method.setFollowRedirects(false);
287     method.addRequestHeader("User-Agent", userAgent);
288     NameValuePair[] params = new NameValuePair[] { new NameValuePair("title", title), new NameValuePair("action", "edit") };
289     method.setQueryString(EncodingUtil.formUrlEncode(params, charSet));
290
291     Loaded result;
292     try {
293       int responseCode = client.executeMethod(method);
294       String responseBody = method.getResponseBodyAsString();
295       //                        log(method);
296
297       if (responseCode == 200) {
298         Parsed parsed = parseBody(charSet, responseBody);
299         Content content = new Content(parsed.timestamp, parsed.body);
300         result = new Loaded(actionURL, charSet, parsed.title, content);
301       } else {
302         throw new UnexpectedAnswerException("load not successful: expected 200 OK, got " + method.getStatusLine());
303       }
304     } catch (HttpException e) {
305       throw new MethodException("method failed", e);
306     } catch (IOException e) {
307       throw new MethodException("method failed", e);
308     } finally {
309       method.releaseConnection();
310     }
311     return result;
312   }
313
314   public Loaded loadCategory(String actionURL, String charSet, String title) throws UnexpectedAnswerException, MethodException,
315       PageNotEditableException {
316     GetMethod method = new GetMethod(actionURL);
317     method.setFollowRedirects(false);
318     method.addRequestHeader("User-Agent", userAgent);
319     NameValuePair[] params = new NameValuePair[] { new NameValuePair("title", title) };
320     method.setQueryString(EncodingUtil.formUrlEncode(params, charSet));
321
322     Loaded result;
323     try {
324       int responseCode = client.executeMethod(method);
325       String responseBody = method.getResponseBodyAsString();
326       //                        log(method);
327
328       if (responseCode == 200) {
329         Parsed parsed = parseBody(charSet, responseBody);
330         Content content = new Content(parsed.timestamp, parsed.body);
331         result = new Loaded(actionURL, charSet, parsed.title, content);
332       } else {
333         throw new UnexpectedAnswerException("load not successful: expected 200 OK, got " + method.getStatusLine());
334       }
335     } catch (HttpException e) {
336       throw new MethodException("method failed", e);
337     } catch (IOException e) {
338       throw new MethodException("method failed", e);
339     } finally {
340       method.releaseConnection();
341     }
342     return result;
343   }
344
345   public ArrayList loadXML(IWikipedia config, String actionURL, String pages) throws UnexpectedAnswerException, MethodException,
346       InterruptedException {
347     storeThrottle.delay();
348     PostMethod method = new PostMethod(actionURL);
349     method.setFollowRedirects(false);
350     method.addRequestHeader("User-Agent", userAgent);
351     method.addRequestHeader("Content-Type", PostMethod.FORM_URL_ENCODED_CONTENT_TYPE + "; charset=" + config.getCharSet());
352
353     NameValuePair[] params = new NameValuePair[] {
354         new NameValuePair("pages", pages),
355         new NameValuePair("curonly", "X"),
356         new NameValuePair("action", "submit") };
357     method.addParameters(params);
358     try {
359       int responseCode = client.executeMethod(method);
360       String responseBody = method.getResponseBodyAsString();
361
362       if (responseCode == 200) {
363         StringReader reader = new StringReader(responseBody);
364         return XMLReader.readFromStream(reader);
365       } else {
366         throw new UnexpectedAnswerException("XML load not successful: expected 200 OK, got " + method.getStatusLine());
367       }
368     } catch (CoreException e) {
369       throw new UnexpectedAnswerException("XML load method failed" + e.getMessage());
370     } catch (HttpException e) {
371       throw new MethodException("XML load method failed", e);
372     } catch (IOException e) {
373       throw new MethodException("XML load method failed", e);
374     } finally {
375       method.releaseConnection();
376     }
377   }
378
379   /**
380    * store a Page Version - returns a Stored object
381    * 
382    * @param config -
383    *          WiKipedia predefined properties
384    * @param actionURL
385    * @param title
386    * @param content
387    * @param summary
388    * @param minorEdit
389    * @param watchThis
390    * @return
391    * @throws UnexpectedAnswerException
392    * @throws MethodException
393    * @throws PageNotEditableException
394    * @throws InterruptedException
395    */
396   public Stored store(IWikipedia config, String editToken, String actionUrl, String title, Content content, String summary,
397       boolean minorEdit, boolean watchThis) throws UnexpectedAnswerException, MethodException, PageNotEditableException,
398       InterruptedException {
399     //### workaround: prevent too many stores at a time
400     storeThrottle.delay();
401
402     PostMethod method = new PostMethod(actionUrl);
403
404     method.setFollowRedirects(false);
405     method.addRequestHeader("User-Agent", userAgent);
406     method.addRequestHeader("Content-Type", PostMethod.FORM_URL_ENCODED_CONTENT_TYPE + "; charset=" + config.getCharSet());
407     if (editToken == null) {
408       // in some versions editToken isn't supported
409       editToken = " ";
410     }
411     NameValuePair[] params = new NameValuePair[] {
412         // new NameValuePair("wpSection", ""),
413         // new NameValuePair("wpPreview", "Vorschau zeigen"),
414         // new NameValuePair("wpSave", "Artikel speichern"),
415         new NameValuePair("title", title),
416         new NameValuePair("wpTextbox1", content.body),
417         new NameValuePair("wpEdittime", content.timestamp),
418         new NameValuePair("wpSummary", summary),
419         new NameValuePair("wpEditToken", editToken),
420         new NameValuePair("wpSave", "yes"),
421         new NameValuePair("action", "submit") };
422     method.addParameters(params);
423     if (minorEdit)
424       method.addParameter("wpMinoredit", "1");
425     if (watchThis)
426       method.addParameter("wpWatchthis", "1");
427
428     Stored result;
429     try {
430       int responseCode = client.executeMethod(method);
431       String responseBody = method.getResponseBodyAsString();
432       //                        log(method);
433
434       // since 11dec04 there is a single linefeed instead of an empty page.. trim() helps.
435       if (responseCode == 302 && responseBody.trim().length() == 0) {
436         //                              log("store successful, reloading");
437         Loaded loaded = load(actionUrl, config.getCharSet(), title);
438         result = new Stored(actionUrl, config.getCharSet(), loaded.title, loaded.content, false);
439       } else if (responseCode == 200) {
440         //        log("store not successful, conflict detected");
441         Parsed parsed = parseBody(config.getCharSet(), responseBody);
442         Content cont = new Content(parsed.timestamp, parsed.body);
443         result = new Stored(actionUrl, config.getCharSet(), parsed.title, cont, true);
444       } else {
445         throw new UnexpectedAnswerException("store not successful: expected 200 OK, got " + method.getStatusLine());
446       }
447     } catch (HttpException e) {
448       throw new MethodException("method failed", e);
449     } catch (IOException e) {
450       throw new MethodException("method failed", e);
451     } finally {
452       method.releaseConnection();
453     }
454     return result;
455   }
456
457   /**
458    * Get the text of a wikimedia article
459    *  
460    */
461   public String getWikiRawText(String wikiname, String urlStr) {
462     // examples
463     // http://en.wikipedia.org/w/wiki.phtml?title=Main_Page&action=raw
464     // http://en.wikibooks.org/w/index.php?title=Programming:PHP:SQL_Injection&action=raw
465     // http://en.wikipedia.org/w/wiki.phtml?title=Talk:Division_by_zero&action=raw
466     HttpMethod method = null;
467     try {
468       if (urlStr == null) {
469         WikiEditorPlugin.getDefault().reportError("No Wikipedia URL configured", "URL-String == null");
470         //        urlStr = "http://en.wikipedia.org/w/wiki.phtml?title=" + wikiname + "&action=raw";
471       }
472       URI uri = new URI(urlStr.toCharArray());
473
474       String schema = uri.getScheme();
475       if ((schema == null) || (schema.equals(""))) {
476         schema = "http";
477       }
478       Protocol protocol = Protocol.getProtocol(schema);
479
480       method = new GetMethod(uri.toString());
481       String host = uri.getHost();
482       int port = uri.getPort();
483
484       HttpConnection connection = new HttpConnection(host, port, protocol);
485       HttpState state = setHTTPParameters(connection);
486
487       if (connection.isProxied() && connection.isSecure()) {
488         method = new ConnectMethod(method);
489       }
490
491       method.execute(state, connection);
492       //      client.executeMethod(method);
493
494       if (method.getStatusCode() == HttpStatus.SC_OK) {
495         // get the wiki text now:
496         String wikiText = method.getResponseBodyAsString();
497         return wikiText;
498       }
499     } catch (Throwable e) {
500       WikiEditorPlugin.log(e);
501       WikiEditorPlugin.getDefault().reportError("Exception occured", e.getMessage() + "\nSee stacktrace in /.metadata/.log file.");
502     } finally {
503       if (method != null) {
504         method.releaseConnection();
505       }
506     }
507     return null; // no success in getting wiki text
508   }
509
510   //  public static String getWikiEditTextarea(String wikiname, String urlStr) {
511   //    // examples
512   //    // http://en.wikipedia.org/w/wiki.phtml?title=Main_Page&action=edit
513   //    // http://en.wikibooks.org/w/wiki.phtml?title=Programming:PHP:SQL_Injection&action=edit
514   //    // http://en.wikipedia.org/w/wiki.phtml?title=Talk:Division_by_zero&action=edit
515   //    HttpMethod method = null;
516   //    try {
517   //      if (urlStr == null) {
518   //        urlStr = "http://en.wikipedia.org/w/wiki.phtml?title=" + wikiname + "&action=edit";
519   //      }
520   //      // else {
521   //      // urlStr = urlStr + "?title=" + wikiname + "&action=edit";
522   //      // }
523   //      URI uri = new URI(urlStr.toCharArray());
524   //
525   //      String schema = uri.getScheme();
526   //      if ((schema == null) || (schema.equals(""))) {
527   //        schema = "http";
528   //      }
529   //      Protocol protocol = Protocol.getProtocol(schema);
530   //
531   //      HttpState state = new HttpState();
532   //
533   //      method = new GetMethod(uri.toString());
534   //      String host = uri.getHost();
535   //      int port = uri.getPort();
536   //
537   //      HttpConnection connection = new HttpConnection(host, port, protocol);
538   //
539   //      connection.setProxyHost(System.getProperty("http.proxyHost"));
540   //      connection.setProxyPort(Integer.parseInt(System.getProperty("http.proxyPort", "80")));
541   //
542   //      if (System.getProperty("http.proxyUserName") != null) {
543   //        state.setProxyCredentials(null, null, new UsernamePasswordCredentials(System.getProperty("http.proxyUserName"), System
544   //            .getProperty("http.proxyPassword")));
545   //      }
546   //
547   //      if (connection.isProxied() && connection.isSecure()) {
548   //        method = new ConnectMethod(method);
549   //      }
550   //
551   //      method.execute(state, connection);
552   //
553   //      if (method.getStatusCode() == HttpStatus.SC_OK) {
554   //        // get the textareas wiki text now:
555   //        InputStream stream = method.getResponseBodyAsStream();
556   //        int byteLen = stream.available();
557   //        int count = 1;
558   //        byte[] buffer = new byte[byteLen];
559   //        stream.read(buffer, 0, byteLen);
560   //        String wikiText = new String(buffer);
561   //        // String wikiText = method.getResponseBodyAsString();
562   //        int start = wikiText.indexOf("<textarea");
563   //        if (start != (-1)) {
564   //          start = wikiText.indexOf(">", start + 1);
565   //          if (start != (-1)) {
566   //            int end = wikiText.indexOf("</textarea>");
567   //            wikiText = wikiText.substring(start + 1, end);
568   //          }
569   //        }
570   //        return wikiText;
571   //        // System.out.println(wikiText);
572   //
573   //      }
574   //    } catch (Exception e) {
575   //      e.printStackTrace();
576   //    } finally {
577   //      if (method != null) {
578   //        method.releaseConnection();
579   //      }
580   //    }
581   //    return null; // no success in getting wiki text
582   //  }
583
584   /**
585    * @param state
586    * @param connection
587    */
588   private HttpState setHTTPParameters(HttpConnection connection) {
589     HttpState state = new HttpState();
590     Preferences prefs = WikiEditorPlugin.getDefault().getPluginPreferences();
591     String timeout = prefs.getString(WikiEditorPlugin.HTTP_TIMEOUT);
592     String proxyHost = prefs.getString(WikiEditorPlugin.HTTP_PROXYHOST);
593
594     try {
595       // timeout after xx seconds
596       connection.setConnectionTimeout(Integer.parseInt(timeout));
597
598       if (proxyHost.length() > 0) {
599         String proxyPort = prefs.getString(WikiEditorPlugin.HTTP_PROXYPORT);
600         connection.setProxyHost(proxyHost);
601         connection.setProxyPort(Integer.parseInt(proxyPort));
602
603         String proxyUserName = prefs.getString(WikiEditorPlugin.HTTP_PROXYUSERNAME);
604         if (proxyUserName.length() > 0) {
605           String proxyPassWord = prefs.getString(WikiEditorPlugin.HTTP_PROXYPASSWORD);
606           state.setProxyCredentials(null, null, new UsernamePasswordCredentials(proxyUserName, proxyPassWord));
607         }
608       }
609
610     } catch (Exception e) {
611
612     }
613     return state;
614   }
615
616   private void setHTTPClientParameters(HttpClient client) {
617
618     Preferences prefs = WikiEditorPlugin.getDefault().getPluginPreferences();
619     String timeout = prefs.getString(WikiEditorPlugin.HTTP_TIMEOUT);
620     String proxyHost = prefs.getString(WikiEditorPlugin.HTTP_PROXYHOST);
621
622     try {
623       // timeout after xx seconds
624       client.setConnectionTimeout(Integer.parseInt(timeout));
625
626       if (proxyHost.length() > 0) {
627         String proxyPort = prefs.getString(WikiEditorPlugin.HTTP_PROXYPORT);
628         HostConfiguration conf = new HostConfiguration();
629         client.setHostConfiguration(conf);
630         conf.setProxy(proxyHost, Integer.parseInt(proxyPort));
631
632         String proxyUserName = prefs.getString(WikiEditorPlugin.HTTP_PROXYUSERNAME);
633         if (proxyUserName.length() > 0) {
634           HttpState state = new HttpState();
635           String proxyPassWord = prefs.getString(WikiEditorPlugin.HTTP_PROXYPASSWORD);
636           state.setProxyCredentials(null, null, new UsernamePasswordCredentials(proxyUserName, proxyPassWord));
637           client.setState(state);
638         }
639       }
640
641     } catch (Exception e) {
642
643     }
644
645   }
646
647   public static void main(String[] args) {
648     MediaWikiConnector mwc = new MediaWikiConnector();
649     try {
650       IWikipedia wp = null;
651       ArrayList list = mwc.loadXML(wp, "http://www.plog4u.de/wiki/index.php/Spezial:Export", "Mechanisches Fernsehen\nSynästhesie");
652       for (int i = 0; i < list.size(); i++) {
653         System.out.println(list.get(i).toString());
654       }
655     } catch (UnexpectedAnswerException e) {
656       // TODO Auto-generated catch block
657       e.printStackTrace();
658     } catch (Exception e) {
659       // TODO Auto-generated catch block
660       e.printStackTrace();
661     }
662   }
663 }
664