package mediawiki; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Map.Entry; import org.json.JSONObject; import javat.xml.Document; public class MediaWikiPostRequest extends PostRequest { public static final int MAXLAG_RETRY_LIMIT = 3; private MediaWikiConnection con = null; public MediaWikiPostRequest(MediaWikiConnection c) throws UnsupportedEncodingException { super(c.getApihref()); this.con = c; if(c.isLoggedIn()) putData("assert",(c.isBot() ? "bot" : "user")); if(c.isBot()){ putData("bot",""); // putData("apihighlimits","1"); } putData("maxlag", c.getMaxlag()+""); for(Entry<String, String> t : c.getCookies().entrySet()){ putCookie(t.getKey(), t.getValue()); } } @Override public String request() throws IOException { String a; boolean lag; int i = -1; do { lag = false; i++; a = super.request(); if(i >= MAXLAG_RETRY_LIMIT) { throw new MediaWikiException("slaves are still lagging, limit exceeded"); } if(getResponseHeader().containsKey("Retry-After") || getResponseHeader().containsKey("X-Database-Lag")) { lag = true; System.err.println("The server slaves are lagging. The server want's me to waid for "+getResponseHeader().get("Retry-After").get(0)+" seconds."); try { Thread.currentThread().sleep(Long.parseLong(getResponseHeader().get("Retry-After").get(0))*1000L); } catch (NumberFormatException | InterruptedException e) { throw new MediaWikiException("exception while waiting for server slaves to stop lagging", e); } } if(getResponseHeader().get("Set-Cookie") != null){ for(String s : getResponseHeader().get("Set-Cookie")){ con.putCookie(s.split("=")[0], s.split("=")[1].substring(0, s.split("=")[1].indexOf(';'))); } } } while(lag); return a; } public Document requestDocument() throws Exception { putData("format", "xml"); String a = request(); Document d = Document.load(new ByteArrayInputStream(a.getBytes())); if(d.getRootElement().getChildren("error").size() > 0){ String error = d.getRootElement().getChildren("error").get(0).getAttribute("info").getValue(); if(error.indexOf("Please try again in a few minutes.") > 0){ System.out.println("Relogin initiated..."); con.relogin(); } throw new MediaWikiException("Server Message from "+con.getApihref()+": "+error); } return d; } public JSONObject requestJSONObject() throws Exception { putData("format", "json"); String a = request(); JSONObject o = new JSONObject(a); if(o.has("error")) { throw new MediaWikiException("Server Message from "+con.getApihref()+": "+o.getJSONObject("error").getString("info")); } return o; } }