use of org.json.simple.JSONStreamAware in project elastic-core-maven by OrdinaryDude.
the class APIServlet method process.
private void process(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// Set response values now in case we create an asynchronous context
resp.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
resp.setHeader("Pragma", "no-cache");
resp.setDateHeader("Expires", 0);
resp.setContentType("text/plain; charset=UTF-8");
JSONStreamAware response = JSON.emptyJSON;
long startTime = System.currentTimeMillis();
try {
if (!API.isAllowed(req.getRemoteHost())) {
response = ERROR_NOT_ALLOWED;
return;
}
String requestType = req.getParameter("requestType");
if (requestType == null) {
response = ERROR_INCORRECT_REQUEST;
return;
}
APIRequestHandler apiRequestHandler = apiRequestHandlers.get(requestType);
if (apiRequestHandler == null) {
if (disabledRequestHandlers.containsKey(requestType)) {
response = ERROR_DISABLED;
} else {
response = ERROR_INCORRECT_REQUEST;
}
return;
}
if (Constants.isLightClient && apiRequestHandler.requireFullClient()) {
response = LIGHT_CLIENT_DISABLED_API;
return;
}
if (enforcePost && apiRequestHandler.requirePost() && !"POST".equals(req.getMethod())) {
response = POST_REQUIRED;
return;
}
if (apiRequestHandler.requirePassword()) {
API.verifyPassword(req);
}
final long requireBlockId = apiRequestHandler.allowRequiredBlockParameters() ? ParameterParser.getUnsignedLong(req, "requireBlock", false) : 0;
final long requireLastBlockId = apiRequestHandler.allowRequiredBlockParameters() ? ParameterParser.getUnsignedLong(req, "requireLastBlock", false) : 0;
if (requireBlockId != 0 || requireLastBlockId != 0) {
Nxt.getBlockchain().readLock();
}
try {
try {
if (apiRequestHandler.startDbTransaction()) {
Db.db.beginTransaction();
}
if (requireBlockId != 0 && !Nxt.getBlockchain().hasBlock(requireBlockId)) {
response = REQUIRED_BLOCK_NOT_FOUND;
return;
}
if (requireLastBlockId != 0 && requireLastBlockId != Nxt.getBlockchain().getLastBlock().getId()) {
response = REQUIRED_LAST_BLOCK_NOT_FOUND;
return;
}
response = apiRequestHandler.processRequest(req, resp);
if (requireLastBlockId == 0 && requireBlockId != 0 && response instanceof JSONObject) {
((JSONObject) response).put("lastBlock", Nxt.getBlockchain().getLastBlock().getStringId());
}
} finally {
if (apiRequestHandler.startDbTransaction()) {
Db.db.endTransaction();
}
}
} finally {
if (requireBlockId != 0 || requireLastBlockId != 0) {
Nxt.getBlockchain().readUnlock();
}
}
} catch (ParameterException e) {
response = e.getErrorResponse();
} catch (NxtException | RuntimeException e) {
Logger.logDebugMessage("Error processing API request", e);
JSONObject json = new JSONObject();
JSONData.putException(json, e);
response = JSON.prepare(json);
} catch (ExceptionInInitializerError err) {
Logger.logErrorMessage("Initialization Error", err.getCause());
response = ERROR_INCORRECT_REQUEST;
} catch (Exception e) {
Logger.logErrorMessage("Error processing request", e);
response = ERROR_INCORRECT_REQUEST;
} finally {
// The response will be null if we created an asynchronous context
if (response != null) {
if (response instanceof JSONObject) {
((JSONObject) response).put("requestProcessingTime", System.currentTimeMillis() - startTime);
}
try (Writer writer = resp.getWriter()) {
JSON.writeJSONString(response, writer);
}
}
}
}
use of org.json.simple.JSONStreamAware in project elastic-core-maven by OrdinaryDude.
the class User method processPendingResponses.
synchronized void processPendingResponses(HttpServletRequest req, HttpServletResponse resp) throws IOException {
JSONArray responses = new JSONArray();
JSONStreamAware pendingResponse;
while ((pendingResponse = pendingResponses.poll()) != null) {
responses.add(pendingResponse);
}
if (responses.size() > 0) {
JSONObject combinedResponse = new JSONObject();
combinedResponse.put("responses", responses);
if (asyncContext != null) {
asyncContext.getResponse().setContentType("text/plain; charset=UTF-8");
try (Writer writer = asyncContext.getResponse().getWriter()) {
combinedResponse.writeJSONString(writer);
}
asyncContext.complete();
asyncContext = req.startAsync();
asyncContext.addListener(new UserAsyncListener());
asyncContext.setTimeout(5000);
} else {
resp.setContentType("text/plain; charset=UTF-8");
try (Writer writer = resp.getWriter()) {
combinedResponse.writeJSONString(writer);
}
}
} else {
if (asyncContext != null) {
asyncContext.getResponse().setContentType("text/plain; charset=UTF-8");
try (Writer writer = asyncContext.getResponse().getWriter()) {
JSON.emptyJSON.writeJSONString(writer);
}
asyncContext.complete();
}
asyncContext = req.startAsync();
asyncContext.addListener(new UserAsyncListener());
asyncContext.setTimeout(5000);
}
}
use of org.json.simple.JSONStreamAware in project elastic-core-maven by OrdinaryDude.
the class GetTaggedDataExtendTransactions method processRequest.
@Override
protected JSONStreamAware processRequest(HttpServletRequest req) throws NxtException {
long taggedDataId = ParameterParser.getUnsignedLong(req, "transaction", true);
List<Long> extendTransactions = TaggedData.getExtendTransactionIds(taggedDataId);
JSONObject response = new JSONObject();
JSONArray jsonArray = new JSONArray();
Blockchain blockchain = Nxt.getBlockchain();
Filter<Appendix> filter = (appendix) -> !(appendix instanceof Attachment.TaggedDataExtend);
extendTransactions.forEach(transactionId -> jsonArray.add(JSONData.transaction(blockchain.getTransaction(transactionId), filter)));
response.put("extendTransactions", jsonArray);
return response;
}
use of org.json.simple.JSONStreamAware in project elastic-core-maven by OrdinaryDude.
the class SetLogging method processRequest.
/**
* Process the SetLogging API request
*
* @param req API request
* @return API response
*/
@Override
protected JSONStreamAware processRequest(HttpServletRequest req) {
JSONStreamAware response = null;
//
// Get the log level
//
String value = req.getParameter("logLevel");
if (value != null) {
switch(value) {
case "DEBUG":
Logger.setLevel(Logger.Level.DEBUG);
break;
case "INFO":
Logger.setLevel(Logger.Level.INFO);
break;
case "WARN":
Logger.setLevel(Logger.Level.WARN);
break;
case "ERROR":
Logger.setLevel(Logger.Level.ERROR);
break;
default:
response = INCORRECT_LEVEL;
}
} else {
Logger.setLevel(Logger.Level.INFO);
}
//
if (response == null) {
String[] events = req.getParameterValues("communicationEvent");
if (!Peers.setCommunicationLoggingMask(events))
response = INCORRECT_EVENT;
}
//
if (response == null)
response = LOGGING_UPDATED;
return response;
}
use of org.json.simple.JSONStreamAware in project elastic-core-maven by OrdinaryDude.
the class PeerServlet method doPost.
/**
* Process HTTP POST request
*
* @param req HTTP request
* @param resp HTTP response
* @throws ServletException Servlet processing error
* @throws IOException I/O error
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
JSONStreamAware jsonResponse;
//
// Process the peer request
//
PeerImpl peer = Peers.findOrCreatePeer(req.getRemoteAddr());
if (peer == null) {
jsonResponse = UNKNOWN_PEER;
} else {
jsonResponse = process(peer, req.getReader());
}
//
// Return the response
//
resp.setContentType("text/plain; charset=UTF-8");
try (CountingOutputWriter writer = new CountingOutputWriter(resp.getWriter())) {
JSON.writeJSONString(jsonResponse, writer);
if (peer != null) {
peer.updateUploadedVolume(writer.getCount());
}
} catch (RuntimeException | IOException e) {
if (peer != null) {
if ((Peers.communicationLoggingMask & Peers.LOGGING_MASK_EXCEPTIONS) != 0) {
if (e instanceof RuntimeException) {
Logger.logDebugMessage("Error sending response to peer " + peer.getHost(), e);
} else {
Logger.logDebugMessage(String.format("Error sending response to peer %s: %s", peer.getHost(), e.getMessage() != null ? e.getMessage() : e.toString()));
}
}
peer.blacklist(e);
}
throw e;
}
}
Aggregations