Search in sources :

Example 1 with JSONStreamAware

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);
            }
        }
    }
}
Also used : JSONObject(org.json.simple.JSONObject) NxtException(org.xel.NxtException) JSONStreamAware(org.json.simple.JSONStreamAware) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) NxtException(org.xel.NxtException) Writer(java.io.Writer)

Example 2 with JSONStreamAware

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);
    }
}
Also used : JSONObject(org.json.simple.JSONObject) JSONArray(org.json.simple.JSONArray) JSONStreamAware(org.json.simple.JSONStreamAware) Writer(java.io.Writer)

Example 3 with JSONStreamAware

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;
}
Also used : Filter(org.xel.util.Filter) Attachment(org.xel.Attachment) HttpServletRequest(javax.servlet.http.HttpServletRequest) List(java.util.List) NxtException(org.xel.NxtException) JSONObject(org.json.simple.JSONObject) Blockchain(org.xel.Blockchain) JSONStreamAware(org.json.simple.JSONStreamAware) Nxt(org.xel.Nxt) Appendix(org.xel.Appendix) TaggedData(org.xel.TaggedData) JSONArray(org.json.simple.JSONArray) JSONObject(org.json.simple.JSONObject) Blockchain(org.xel.Blockchain) JSONArray(org.json.simple.JSONArray) Appendix(org.xel.Appendix)

Example 4 with JSONStreamAware

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;
}
Also used : JSONStreamAware(org.json.simple.JSONStreamAware)

Example 5 with JSONStreamAware

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;
    }
}
Also used : IOException(java.io.IOException) JSONStreamAware(org.json.simple.JSONStreamAware) CountingOutputWriter(org.xel.util.CountingOutputWriter)

Aggregations

JSONStreamAware (org.json.simple.JSONStreamAware)13 JSONObject (org.json.simple.JSONObject)7 IOException (java.io.IOException)5 Writer (java.io.Writer)4 JSONArray (org.json.simple.JSONArray)4 NxtException (org.xel.NxtException)3 StringWriter (java.io.StringWriter)2 PrintWriter (java.io.PrintWriter)1 StringReader (java.io.StringReader)1 InetSocketAddress (java.net.InetSocketAddress)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 ExecutionException (java.util.concurrent.ExecutionException)1 Future (java.util.concurrent.Future)1 ServletException (javax.servlet.ServletException)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 Test (org.junit.Test)1 Appendix (org.xel.Appendix)1 Attachment (org.xel.Attachment)1 Blockchain (org.xel.Blockchain)1