public QueryResult updatePage(
EnumWikipedia wikipedia, Page page,
String newContents, String comment,
boolean forceWatch) throws APIException {
if (page == null) {
throw new APIException("Page is null");
}
if (newContents == null) {
throw new APIException("Contents is null");
}
if (comment == null) {
throw new APIException("Comment is null");
}
if (wikipedia.getConnection().getLgToken() == null) {
throw new APIException("You must be logged in to update pages");
}
int attemptNumber = 0;
QueryResult result = null;
do {
attemptNumber++;
Map<String, String> properties = getProperties(ApiRequest.ACTION_EDIT, true);
properties.put("assert", "user");
if (page.getContentsTimestamp() != null) {
properties.put("basetimestamp", page.getContentsTimestamp());
}
properties.put("bot", "");
properties.put("minor", "");
if (page.getStartTimestamp() != null) {
properties.put("starttimestamp", page.getStartTimestamp());
}
properties.put("summary", comment);
properties.put("text", newContents);
properties.put("title", page.getTitle());
if (wikipedia.getConnection().getEditToken() != null) {
properties.put("token", wikipedia.getConnection().getEditToken());
}
properties.put("watchlist", forceWatch ? "watch" : "nochange");
checkTimeForEdit(wikipedia.getConnection().getUser(), page.getNamespace());
try {
boolean hasCaptcha = false;
do {
hasCaptcha = false;
try {
result = constructEdit(
getRoot(wikipedia, properties, 1),
"/api/edit");
} catch (CaptchaException e) {
String captchaAnswer = getCaptchaAnswer(wikipedia, e);
if (captchaAnswer != null) {
properties.put("captchaid", e.getId());
properties.put("captchaword", captchaAnswer);
hasCaptcha = true;
} else {
throw new APIException("CAPTCHA", e);
}
}
} while (hasCaptcha);
} catch (APIException e) {
if (e.getHttpStatus() == HttpStatus.SC_GATEWAY_TIMEOUT) {
log.warn("Gateway timeout, waiting to see if modification has been taken into account");
waitBeforeRetrying();
Page tmpPage = page.replicatePage();
retrieveContents(wikipedia, Collections.singletonList(tmpPage), false, false);
String tmpContents = tmpPage.getContents();
if ((tmpContents != null) &&
(tmpContents.equals(newContents))) {
return QueryResult.createCorrectQuery(
tmpPage.getPageId(), tmpPage.getTitle(),
page.getPageId(), tmpPage.getPageId());
}
}
if (attemptNumber > 1) {
throw e;
}
if (e.getQueryResult() == EnumQueryResult.BAD_TOKEN) {
waitBeforeRetrying();
log.warn("Retrieving tokens after a BAD_TOKEN answer");
retrieveTokens(wikipedia);
}
} catch (JDOMParseException e) {
log.error("Error updating page: " + e.getMessage());
throw new APIException("Error parsing XML", e);
}
} while (result == null);
return result;
}