Search in sources :

Example 6 with JSONStreamAware

use of org.json.simple.JSONStreamAware in project elastic-core-maven by OrdinaryDude.

the class PeerServlet method doPost.

/**
 * Process WebSocket POST request
 *
 * @param   webSocket           WebSocket for the connection
 * @param   requestId           Request identifier
 * @param   request             Request message
 */
void doPost(PeerWebSocket webSocket, long requestId, String request) {
    JSONStreamAware jsonResponse;
    // 
    // Process the peer request
    // 
    InetSocketAddress socketAddress = webSocket.getRemoteAddress();
    if (socketAddress == null) {
        return;
    }
    String remoteAddress = socketAddress.getHostString();
    PeerImpl peer = Peers.findOrCreatePeer(remoteAddress);
    if (peer == null) {
        jsonResponse = UNKNOWN_PEER;
    } else {
        peer.setInboundWebSocket(webSocket);
        jsonResponse = process(peer, new StringReader(request));
    }
    // 
    try {
        StringWriter writer = new StringWriter(1000);
        JSON.writeJSONString(jsonResponse, writer);
        String response = writer.toString();
        webSocket.sendResponse(requestId, response);
        if (peer != null) {
            peer.updateUploadedVolume(response.length());
        }
    } 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);
        }
    }
}
Also used : StringWriter(java.io.StringWriter) InetSocketAddress(java.net.InetSocketAddress) StringReader(java.io.StringReader) IOException(java.io.IOException) JSONStreamAware(org.json.simple.JSONStreamAware)

Example 7 with JSONStreamAware

use of org.json.simple.JSONStreamAware in project elastic-core-maven by OrdinaryDude.

the class Peers method sendToSomePeers.

private static void sendToSomePeers(final JSONObject request) {
    sendingService.submit(() -> {
        final JSONStreamAware jsonRequest = JSON.prepareRequest(request);
        int successful = 0;
        List<Future<JSONObject>> expectedResponses = new ArrayList<>();
        for (final Peer peer : peers.values()) {
            if (Peers.enableHallmarkProtection && peer.getWeight() < Peers.pushThreshold) {
                continue;
            }
            if (!peer.isBlacklisted() && peer.getState() == Peer.State.CONNECTED && peer.getAnnouncedAddress() != null && peer.getBlockchainState() != Peer.BlockchainState.LIGHT_CLIENT) {
                Future<JSONObject> futureResponse = peersService.submit(() -> peer.send(jsonRequest));
                expectedResponses.add(futureResponse);
            }
            if (expectedResponses.size() >= Peers.sendToPeersLimit - successful) {
                for (Future<JSONObject> future : expectedResponses) {
                    try {
                        JSONObject response = future.get();
                        if (response != null && response.get("error") == null) {
                            successful += 1;
                        }
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    } catch (ExecutionException e) {
                        Logger.logDebugMessage("Error in sendToSomePeers", e);
                    }
                }
                expectedResponses.clear();
            }
            if (successful >= Peers.sendToPeersLimit) {
                return;
            }
        }
    });
}
Also used : JSONObject(org.json.simple.JSONObject) ArrayList(java.util.ArrayList) Future(java.util.concurrent.Future) JSONStreamAware(org.json.simple.JSONStreamAware) ExecutionException(java.util.concurrent.ExecutionException)

Example 8 with JSONStreamAware

use of org.json.simple.JSONStreamAware in project elastic-core-maven by OrdinaryDude.

the class UserServlet method process.

private void process(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
    resp.setHeader("Pragma", "no-cache");
    resp.setDateHeader("Expires", 0);
    User user = null;
    try {
        String userPasscode = req.getParameter("user");
        if (userPasscode == null) {
            return;
        }
        user = Users.getUser(userPasscode);
        if (Users.allowedUserHosts != null && !Users.allowedUserHosts.contains(req.getRemoteHost())) {
            user.enqueue(DENY_ACCESS);
            return;
        }
        String requestType = req.getParameter("requestType");
        if (requestType == null) {
            user.enqueue(INCORRECT_REQUEST);
            return;
        }
        UserRequestHandler userRequestHandler = userRequestHandlers.get(requestType);
        if (userRequestHandler == null) {
            user.enqueue(INCORRECT_REQUEST);
            return;
        }
        if (enforcePost && userRequestHandler.requirePost() && !"POST".equals(req.getMethod())) {
            user.enqueue(POST_REQUIRED);
            return;
        }
        JSONStreamAware response = userRequestHandler.processRequest(req, user);
        if (response != null) {
            user.enqueue(response);
        }
    } catch (RuntimeException | NxtException e) {
        Logger.logMessage("Error processing GET request", e);
        if (user != null) {
            JSONObject response = new JSONObject();
            response.put("response", "showMessage");
            response.put("message", e.toString());
            user.enqueue(response);
        }
    } finally {
        if (user != null) {
            user.processPendingResponses(req, resp);
        }
    }
}
Also used : JSONObject(org.json.simple.JSONObject) NxtException(org.xel.NxtException) JSONStreamAware(org.json.simple.JSONStreamAware)

Example 9 with JSONStreamAware

use of org.json.simple.JSONStreamAware in project elastic-core-maven by OrdinaryDude.

the class APIProxyServlet method service.

@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    JSONStreamAware responseJson = null;
    try {
        if (!API.isAllowed(request.getRemoteHost())) {
            responseJson = ERROR_NOT_ALLOWED;
            return;
        }
        MultiMap<String> parameters = getRequestParameters(request);
        String requestType = getRequestType(parameters);
        if (APIProxy.isActivated() && isForwardable(requestType)) {
            if (parameters.containsKey("secretPhrase") || parameters.containsKey("adminPassword") || parameters.containsKey("sharedKey")) {
                throw new ParameterException(JSONResponses.PROXY_SECRET_DATA_DETECTED);
            }
            if (!initRemoteRequest(request, requestType)) {
                responseJson = JSONResponses.API_PROXY_NO_OPEN_API_PEERS;
            } else {
                super.service(request, response);
            }
        } else {
            APIServlet apiServlet = (APIServlet) request.getServletContext().getAttribute("apiServlet");
            apiServlet.service(request, response);
        }
    } catch (ParameterException e) {
        responseJson = e.getErrorResponse();
    } finally {
        if (responseJson != null) {
            try {
                try (Writer writer = response.getWriter()) {
                    JSON.writeJSONString(responseJson, writer);
                }
            } catch (IOException e) {
                Logger.logInfoMessage("Failed to write response to client", e);
            }
        }
    }
}
Also used : IOException(java.io.IOException) JSONStreamAware(org.json.simple.JSONStreamAware) Writer(java.io.Writer)

Example 10 with JSONStreamAware

use of org.json.simple.JSONStreamAware in project elastic-core-maven by OrdinaryDude.

the class BlockchainProcessorImpl method restorePrunedTransaction.

@Override
public Transaction restorePrunedTransaction(long transactionId) {
    TransactionImpl transaction = TransactionDb.findTransaction(transactionId);
    if (transaction == null) {
        throw new IllegalArgumentException("Transaction not found");
    }
    boolean isPruned = false;
    for (Appendix.AbstractAppendix appendage : transaction.getAppendages(true)) {
        if ((appendage instanceof Appendix.Prunable) && !((Appendix.Prunable) appendage).hasPrunableData()) {
            isPruned = true;
            break;
        }
    }
    if (!isPruned) {
        return transaction;
    }
    List<Peer> peers = Peers.getPeers(chkPeer -> chkPeer.providesService(Peer.Service.PRUNABLE) && !chkPeer.isBlacklisted() && chkPeer.getAnnouncedAddress() != null);
    if (peers.isEmpty()) {
        Logger.logDebugMessage("Cannot find any archive peers");
        return null;
    }
    JSONObject json = new JSONObject();
    JSONArray requestList = new JSONArray();
    requestList.add(Long.toUnsignedString(transactionId));
    json.put("requestType", "getTransactions");
    json.put("transactionIds", requestList);
    JSONStreamAware request = JSON.prepareRequest(json);
    for (Peer peer : peers) {
        if (peer.getState() != Peer.State.CONNECTED) {
            Peers.connectPeer(peer);
        }
        if (peer.getState() != Peer.State.CONNECTED) {
            continue;
        }
        Logger.logDebugMessage("Connected to archive peer " + peer.getHost());
        JSONObject response = peer.send(request);
        if (response == null) {
            continue;
        }
        JSONArray transactions = (JSONArray) response.get("transactions");
        if (transactions == null || transactions.isEmpty()) {
            continue;
        }
        try {
            List<Transaction> processed = Nxt.getTransactionProcessor().restorePrunableData(transactions);
            if (processed.isEmpty()) {
                continue;
            }
            synchronized (prunableTransactions) {
                prunableTransactions.remove(transactionId);
            }
            return processed.get(0);
        } catch (NxtException.NotValidException e) {
            Logger.logErrorMessage("Peer " + peer.getHost() + " returned invalid prunable transaction", e);
            peer.blacklist(e);
        }
    }
    return null;
}
Also used : Peer(org.xel.peer.Peer) JSONArray(org.json.simple.JSONArray) JSONObject(org.json.simple.JSONObject) JSONStreamAware(org.json.simple.JSONStreamAware)

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