*/
public static CharSequence renderJsonResponse(
DataSourceParameters dsParams,
ResponseStatus responseStatus,
DataTable data) {
StrBuilder sb = new StrBuilder();
boolean isJsonp = dsParams.getOutputType() == OutputType.JSONP;
if (isJsonp) {
sb.append(dsParams.getResponseHandler()).append("(");
}
sb.append("{\"version\":\"0.6\"");
// If no reqId found in the request, do not return reqId in the response.
String requestId = dsParams.getRequestId();
if (requestId != null) {
sb.append(",\"reqId\":\"").append(EscapeUtil.jsonEscape(requestId)).append("\"");
}
// Check signature.
String previousSignature = dsParams.getSignature();
if (responseStatus == null) {
if (!StringUtils.isEmpty(previousSignature) && (data != null)
&& (JsonRenderer.getSignature(data).equals(previousSignature))) {
responseStatus = new ResponseStatus(StatusType.ERROR, ReasonType.NOT_MODIFIED, null);
} else {
responseStatus = new ResponseStatus(StatusType.OK, null, null);
}
}
StatusType statusType = responseStatus.getStatusType();
sb.append(",\"status\":\"").append(statusType.lowerCaseString()).append("\"");
// There are reason and messages if the status is WARNING/ERROR.
if (statusType != StatusType.OK) {
// Status is warning or error.
if (statusType == StatusType.WARNING) {
List<Warning> warnings = data.getWarnings();
List<String> warningJsonStrings = Lists.newArrayList();
if (warnings != null) {
for (Warning warning : warnings) {
warningJsonStrings.add(getFaultString(warning.getReasonType(), warning.getMessage()));
}
}
sb.append(",\"warnings\":[").appendWithSeparators(warningJsonStrings, ",").append("]");
} else { // Status is error.
sb.append(",\"errors\":[");
sb.append(getFaultString(responseStatus.getReasonType(), responseStatus.getDescription()));
sb.append("]");
}
}
if ((statusType != StatusType.ERROR) && (data != null)) {
// MessageType OK or WARNING,
// so need to attach a data table (and a signature).
sb.append(",\"sig\":\"").append(JsonRenderer.getSignature(data)).append("\"");
sb.append(",\"table\":").append(JsonRenderer.renderDataTable(data, true, true, isJsonp));
}
sb.append("}");
if (isJsonp) {
sb.append(");");
}
return sb.toString();
}