Search in sources :

Example 86 with Binder

use of net.sergeych.tools.Binder in project universa by UniversaBlockchain.

the class BasicHttpClient method command.

/**
 * Execute a command over the authenticated and encrypted connection. In the case of network errors, restarts the
 * command.
 *
 * @param name   command name
 * @param params command params
 *
 * @return decrypted command answer
 *
 * @throws IOException if the commadn can't be executed after several retries or the remote side reports error.
 */
public Binder command(String name, Binder params) throws IOException {
    synchronized (this) {
        if (session == null || session.getSessionKey() == null)
            throw new IllegalStateException("Session does not created or session key is not got yet.");
        Binder call = Binder.fromKeysValues("command", name, "params", params);
        for (int i = 0; i < DEFAULT_RECONNECT_TIMES; i++) {
            ErrorRecord er = null;
            try {
                Answer a = requestOrThrow("command", "command", "command", "params", session.getSessionKey().encrypt(Boss.pack(call)), "session_id", session.getSessionId());
                Binder data = Boss.unpack(session.getSessionKey().decrypt(a.data.getBinaryOrThrow("result")));
                Binder result = data.getBinder("result", null);
                if (result != null)
                    return result;
                System.out.println("result: " + result);
                er = (ErrorRecord) data.get("error");
                if (er == null)
                    er = new ErrorRecord(Errors.FAILURE, "", "unprocessablereply");
            } catch (EndpointException e) {
                // this is not good = we'd better pass it in the encoded block
                ErrorRecord r = e.getFirstError();
                if (r.getError() == Errors.COMMAND_FAILED)
                    throw e;
                System.err.println(r);
            } catch (SocketTimeoutException e) {
                // e.printStackTrace();
                System.err.println("Socket timeout while executing command " + name);
                log.d("Socket timeout while executing command " + name + ": " + e);
            } catch (ConnectException e) {
                // e.printStackTrace();
                System.err.println("Connection refused while executing command " + name);
                log.d("Connection refused while executing command " + name + ": " + e);
            } catch (IOException e) {
                e.printStackTrace();
                log.d("error executing command " + name + ": " + e);
            }
            // if we get here with error, we need to throw it.
            if (er != null)
                throw new CommandFailedException(er);
            // otherwise it is an recoverable error and we must retry
            log.d("repeating command " + name + ", attempt " + (i + 1));
            try {
                Thread.sleep(i * 3 * 100);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            restart();
        }
        throw new IOException("Failed to execute command " + name);
    }
}
Also used : Binder(net.sergeych.tools.Binder) IOException(java.io.IOException) ErrorRecord(com.icodici.universa.ErrorRecord)

Example 87 with Binder

use of net.sergeych.tools.Binder in project universa by UniversaBlockchain.

the class BasicHttpServer method addEndpoint.

public void addEndpoint(String path, Endpoint ep) {
    on(path, (request, response) -> {
        Binder result;
        try {
            Result epResult = new Result();
            // System.out.println("extracted params: " + extractParams(request));
            ep.execute(extractParams(request), epResult);
            result = Binder.of("result", "ok", "response", epResult);
        } catch (Exception e) {
            result = Binder.of("result", "error", "error", e.toString(), "errorClass", e.getClass().getName());
        }
        response.setBody(Boss.pack(result));
    });
}
Also used : Binder(net.sergeych.tools.Binder) IOException(java.io.IOException)

Example 88 with Binder

use of net.sergeych.tools.Binder in project universa by UniversaBlockchain.

the class Client method getState.

public ItemResult getState(HashId itemId) throws ClientError {
    return protect(() -> {
        // for (int i = 0; i < nodes.size(); i++) {
        // System.out.println("checking node " + i);
        // ItemResult r = getClient(i).command("getState",
        // "itemId", itemId).getOrThrow("itemResult");
        // System.out.println(">> " + r);
        // }
        Binder result = httpClient.command("getState", "itemId", itemId);
        Object ir = result.getOrThrow("itemResult");
        if (ir instanceof ItemResult)
            return (ItemResult) ir;
        if (ir instanceof String)
            System.out.println(">> " + ir);
        return ItemResult.UNDEFINED;
    });
}
Also used : Binder(net.sergeych.tools.Binder) ItemResult(com.icodici.universa.node.ItemResult)

Example 89 with Binder

use of net.sergeych.tools.Binder in project universa by UniversaBlockchain.

the class ClientHTTPServer method itemResultOfError.

private ItemResult itemResultOfError(Errors error, String object, String message) {
    Binder binder = new Binder();
    binder.put("state", ItemState.UNDEFINED.name());
    binder.put("haveCopy", false);
    binder.put("createdAt", new Date());
    binder.put("expiresAt", new Date());
    ArrayList<ErrorRecord> errorRecords = new ArrayList<>();
    errorRecords.add(new ErrorRecord(error, object, message));
    binder.put("errors", errorRecords);
    return new ItemResult(binder);
}
Also used : Binder(net.sergeych.tools.Binder) ItemResult(com.icodici.universa.node.ItemResult) ArrayList(java.util.ArrayList) Date(java.util.Date) ErrorRecord(com.icodici.universa.ErrorRecord)

Example 90 with Binder

use of net.sergeych.tools.Binder in project universa by UniversaBlockchain.

the class ClientHTTPServer method on.

@Override
public void on(String path, BasicHTTPService.Handler handler) {
    super.on(path, (request, response) -> {
        if (localCors) {
            Binder hh = response.getHeaders();
            hh.put("Access-Control-Allow-Origin", "*");
            hh.put("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
            hh.put("Access-Control-Allow-Headers", "DNT,X-CustomHeader,Keep-Alive,User-Age  nt,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range");
            hh.put("Access-Control-Expose-Headers", "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range");
        }
        handler.handle(request, response);
    });
}
Also used : Binder(net.sergeych.tools.Binder)

Aggregations

Binder (net.sergeych.tools.Binder)136 Test (org.junit.Test)67 PrivateKey (com.icodici.crypto.PrivateKey)21 Contract (com.icodici.universa.contract.Contract)14 PublicKey (com.icodici.crypto.PublicKey)13 IOException (java.io.IOException)11 KeyRecord (com.icodici.universa.contract.KeyRecord)10 SimpleRole (com.icodici.universa.contract.roles.SimpleRole)10 Yaml (org.yaml.snakeyaml.Yaml)9 Bytes (net.sergeych.utils.Bytes)8 Decimal (com.icodici.universa.Decimal)7 ListRole (com.icodici.universa.contract.roles.ListRole)6 NonNull (org.checkerframework.checker.nullness.qual.NonNull)5 Gson (com.google.gson.Gson)4 GsonBuilder (com.google.gson.GsonBuilder)4 XStream (com.thoughtworks.xstream.XStream)4 DomDriver (com.thoughtworks.xstream.io.xml.DomDriver)4 List (java.util.List)4 RoleLink (com.icodici.universa.contract.roles.RoleLink)3 ItemResult (com.icodici.universa.node.ItemResult)3