Search in sources :

Example 31 with JsonValue

use of com.eclipsesource.json.JsonValue in project zencash-swing-wallet-ui by ZencashOfficial.

the class StartupProgressDialog method waitForStartup.

public void waitForStartup() throws IOException, InterruptedException, WalletCallException, InvocationTargetException {
    // special handling of Windows/Mac OS app launch
    OS_TYPE os = OSUtil.getOSType();
    if ((os == OS_TYPE.WINDOWS) || (os == OS_TYPE.MAC_OS)) {
        ProvingKeyFetcher keyFetcher = new ProvingKeyFetcher();
        keyFetcher.fetchIfMissing(this);
    }
    Log.info("Splash: checking if zend is already running...");
    boolean shouldStartZCashd = false;
    try {
        clientCaller.getDaemonRawRuntimeInfo();
    } catch (IOException e) {
        // may be thrown for an unexpected reason!!! - so message is checked
        if (e.getMessage() != null && e.getMessage().toLowerCase(Locale.ROOT).contains("error: couldn't connect to server")) {
            shouldStartZCashd = true;
        }
    }
    if (!shouldStartZCashd) {
        Log.info("Splash: zend already running...");
    // What if started by hand but taking long to initialize???
    // doDispose();
    // return;
    } else {
        Log.info("Splash: zend will be started...");
    }
    final Process daemonProcess = shouldStartZCashd ? clientCaller.startDaemon() : null;
    // just a little extra
    Thread.sleep(POLL_PERIOD);
    int iteration = 0;
    while (true) {
        iteration++;
        Thread.sleep(POLL_PERIOD);
        JsonObject info = null;
        try {
            info = clientCaller.getDaemonRawRuntimeInfo();
        } catch (IOException e) {
            if (iteration > 4) {
                throw e;
            } else {
                continue;
            }
        }
        JsonValue code = info.get("code");
        if (code == null || (code.asInt() != STARTUP_ERROR_CODE))
            break;
        final String message = info.getString("message", "???");
        setProgressText(message);
    }
    if (// Shutdown only if we started it
    daemonProcess != null)
        Runtime.getRuntime().addShutdownHook(new Thread() {

            public void run() {
                Log.info("Stopping zend because we started it - now it is alive: " + StartupProgressDialog.this.isAlive(daemonProcess));
                try {
                    clientCaller.stopDaemon();
                    long start = System.currentTimeMillis();
                    while (!StartupProgressDialog.this.waitFor(daemonProcess, 3000)) {
                        long end = System.currentTimeMillis();
                        Log.info("Waiting for " + ((end - start) / 1000) + " seconds for zend to exit...");
                        if (end - start > 15 * 1000) {
                            clientCaller.stopDaemon();
                            daemonProcess.destroy();
                        }
                        if (end - start > 1 * 60 * 1000) {
                            break;
                        }
                    }
                    if (StartupProgressDialog.this.isAlive(daemonProcess)) {
                        Log.info("zend is still alive although we tried to stop it. " + "Hopefully it will stop later!");
                    // System.out.println("zend is still alive, killing forcefully");
                    // daemonProcess.destroyForcibly();
                    } else
                        Log.info("zend shut down successfully");
                } catch (Exception bad) {
                    Log.error("Couldn't stop zend!", bad);
                }
            }
        });
}
Also used : OS_TYPE(com.vaklinov.zcashui.OSUtil.OS_TYPE) JsonValue(com.eclipsesource.json.JsonValue) JsonObject(com.eclipsesource.json.JsonObject) IOException(java.io.IOException) IOException(java.io.IOException) WalletCallException(com.vaklinov.zcashui.ZCashClientCaller.WalletCallException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 32 with JsonValue

use of com.eclipsesource.json.JsonValue in project zencash-swing-wallet-ui by ZencashOfficial.

the class ZCashClientCaller method isWalletEncrypted.

// Wallet locks check - an unencrypted wallet will give an error
// zcash-cli walletlock
// error: {"code":-15,"message":"Error: running with an unencrypted wallet, but walletlock was called."}
public synchronized boolean isWalletEncrypted() throws WalletCallException, IOException, InterruptedException {
    String[] params = new String[] { this.zcashcli.getCanonicalPath(), "walletlock" };
    CommandExecutor caller = new CommandExecutor(params);
    String strResult = caller.execute();
    if (strResult.trim().length() <= 0) {
        // If it could be locked with no result - obviously encrypted
        return true;
    } else if (strResult.trim().toLowerCase(Locale.ROOT).startsWith("error:")) {
        // Expecting an error of an unencrypted wallet
        String jsonPart = strResult.substring(strResult.indexOf("{"));
        JsonValue response = null;
        try {
            response = Json.parse(jsonPart);
        } catch (ParseException pe) {
            throw new WalletCallException(jsonPart + "\n" + pe.getMessage() + "\n", pe);
        }
        JsonObject respObject = response.asObject();
        if ((respObject.getDouble("code", -1) == -15) && (respObject.getString("message", "ERR").indexOf("unencrypted wallet") != -1)) {
            // Obviously unencrupted
            return false;
        } else {
            throw new WalletCallException("Unexpected response from wallet: " + strResult);
        }
    } else if (strResult.trim().toLowerCase(Locale.ROOT).startsWith("error code:")) {
        JsonObject respObject = Util.getJsonErrorMessage(strResult);
        if ((respObject.getDouble("code", -1) == -15) && (respObject.getString("message", "ERR").indexOf("unencrypted wallet") != -1)) {
            // Obviously unencrupted
            return false;
        } else {
            throw new WalletCallException("Unexpected response from wallet: " + strResult);
        }
    } else {
        throw new WalletCallException("Unexpected response from wallet: " + strResult);
    }
}
Also used : JsonValue(com.eclipsesource.json.JsonValue) JsonObject(com.eclipsesource.json.JsonObject) ParseException(com.eclipsesource.json.ParseException)

Example 33 with JsonValue

use of com.eclipsesource.json.JsonValue in project zencash-swing-wallet-ui by ZencashOfficial.

the class ZCashClientCaller method importPrivateKey.

// Imports a private key - tries both possibilities T/Z
public synchronized String importPrivateKey(String key) throws WalletCallException, IOException, InterruptedException {
    // First try a Z key
    String[] params = new String[] { this.zcashcli.getCanonicalPath(), "-rpcclienttimeout=5000", "z_importkey", wrapStringParameter(key) };
    CommandExecutor caller = new CommandExecutor(params);
    String strResult = caller.execute();
    if (Util.stringIsEmpty(strResult) || (!strResult.trim().toLowerCase(Locale.ROOT).contains("error"))) {
        return strResult == null ? "" : strResult.trim();
    }
    // Obviously we have an error trying to import a Z key
    if (strResult.trim().toLowerCase(Locale.ROOT).startsWith("error") && (strResult.indexOf("{") != -1)) {
        // Expecting an error of a T address key
        String jsonPart = strResult.substring(strResult.indexOf("{"));
        JsonValue response = null;
        try {
            response = Json.parse(jsonPart);
        } catch (ParseException pe) {
            throw new WalletCallException(jsonPart + "\n" + pe.getMessage() + "\n", pe);
        }
        JsonObject respObject = response.asObject();
        if ((respObject.getDouble("code", +123) == -1) && (respObject.getString("message", "ERR").indexOf("wrong network type") != -1)) {
        // Obviously T address - do nothing here
        } else {
            throw new WalletCallException("Unexpected response from wallet: " + strResult);
        }
    } else if (strResult.trim().toLowerCase(Locale.ROOT).startsWith("error code:")) {
        JsonObject respObject = Util.getJsonErrorMessage(strResult);
        if ((respObject.getDouble("code", +123) == -1) && (respObject.getString("message", "ERR").indexOf("wrong network type") != -1)) {
        // Obviously T address - do nothing here
        } else {
            throw new WalletCallException("Unexpected response from wallet: " + strResult);
        }
    } else {
        throw new WalletCallException("Unexpected response from wallet: " + strResult);
    }
    // Second try a T key
    strResult = this.executeCommandAndGetSingleStringResponse("-rpcclienttimeout=5000", "importprivkey", wrapStringParameter(key));
    if (Util.stringIsEmpty(strResult) || (!strResult.trim().toLowerCase(Locale.ROOT).contains("error"))) {
        return strResult == null ? "" : strResult.trim();
    }
    // Obviously an error
    throw new WalletCallException("Unexpected response from wallet: " + strResult);
}
Also used : JsonValue(com.eclipsesource.json.JsonValue) JsonObject(com.eclipsesource.json.JsonObject) ParseException(com.eclipsesource.json.ParseException)

Example 34 with JsonValue

use of com.eclipsesource.json.JsonValue in project zencash-swing-wallet-ui by ZencashOfficial.

the class ZCashClientCaller method getSuccessfulOperationTXID.

public synchronized String getSuccessfulOperationTXID(String opID) throws WalletCallException, IOException, InterruptedException {
    String TXID = null;
    JsonArray response = this.executeCommandAndGetJsonArray("z_getoperationstatus", wrapStringParameter("[\"" + opID + "\"]"));
    JsonObject jsonStatus = response.get(0).asObject();
    JsonValue opResultValue = jsonStatus.get("result");
    if (opResultValue != null) {
        JsonObject opResult = opResultValue.asObject();
        if (opResult.get("txid") != null) {
            TXID = opResult.get("txid").asString();
        }
    }
    return TXID;
}
Also used : JsonArray(com.eclipsesource.json.JsonArray) JsonValue(com.eclipsesource.json.JsonValue) JsonObject(com.eclipsesource.json.JsonObject)

Example 35 with JsonValue

use of com.eclipsesource.json.JsonValue in project kontraktor by RuedigerMoeller.

the class JSXIntrinsicTranspiler method resolveImportSpec.

private File resolveImportSpec(File requiringFile, ImportSpec importSpec, FileResolver resolver, Map<String, Object> alreadyResolved, Set ignoredRequires) throws IOException {
    String from = importSpec.getFrom();
    File toReadFrom = requiringFile;
    // node package entry processing
    String toReadFromName = null;
    if (importSpec.isRequire()) {
        if (ignoredRequires.contains(importSpec.getFrom()))
            return null;
        if (dev && getConfig().getIgnoredDevRequires().contains(importSpec.getFrom())) {
            Log.Info(this, "omit " + importSpec.getFrom() + " caused by jnpm.kson");
            return null;
        }
        if (!dev && getConfig().getIgnoredProdRequires().contains(importSpec.getFrom())) {
            Log.Info(this, "omit " + importSpec.getFrom() + " caused by jnpm.kson");
            return null;
        }
        String canonicalF = findNodeSubDir(requiringFile);
        if (canonicalF != null) {
            // check for ignored requires in browser entry of package.json
            String key = "browser_" + canonicalF + "_" + from;
            JsonValue o = (JsonValue) alreadyResolved.get(key);
            if (o != null) {
                if (o.isString()) {
                    String oldFrom = from;
                    from = o.asString();
                    Log.Info(this, "mapping package.json/browser:" + oldFrom + " to " + from);
                } else if (o.isBoolean()) {
                    if (!o.asBoolean()) {
                        Log.Info(this, "ignoring because of package.json/browser:" + from);
                        return null;
                    }
                } else
                    Log.Warn(this, "unrecognized browser entry in package.json:" + o + ". file:" + requiringFile.getAbsolutePath());
            } else {
            // System.out.println("key lookup == null for browser setting :"+key);
            }
        } else {
            Log.Warn(this, "node module dir could not be resolved " + requiringFile.getAbsolutePath());
            return null;
        }
    }
    File resolvedFile;
    if (importSpec.isRequire()) {
        resolvedFile = findNodeModulesNearestMatch(requiringFile, from);
        if (resolvedFile != null) {
            toReadFromName = resolvedFile.getName();
            toReadFrom = resolvedFile;
        } else {
            int debug = 1;
        }
    } else {
        resolvedFile = resolver.resolveFile(requiringFile.getParentFile(), from);
    }
    if (resolvedFile != null && resolvedFile.isDirectory()) {
        if (isNotInNodeModules(requiringFile)) {
            String tlFrom = importSpec.getFrom();
            nodeTopLevelImports.put(tlFrom, resolvedFile);
        }
        File indexFile = processNodeDir(resolvedFile, resolver, alreadyResolved);
        if (indexFile == falseFile) {
            return null;
        }
        if (indexFile == null) {
            Log.Warn(this, "node directory could not be resolved to a resource :" + resolvedFile.getCanonicalPath());
            return null;
        } else {
            toReadFrom = indexFile;
            toReadFromName = indexFile.getName();
        }
    } else {
        // fixme: hasExtension
        if (!from.endsWith(".js") && !from.endsWith(".jsx") && !from.endsWith(".json")) {
            from += ".js";
        }
    }
    byte[] resolved = resolver.resolve(toReadFrom.getParentFile(), toReadFromName != null ? toReadFromName : from, alreadyResolved);
    if (resolved == null && from.endsWith(".js")) {
        // try jsx
        from = from.substring(0, from.length() - 3) + ".jsx";
        resolved = resolver.resolve(requiringFile.getParentFile(), from, alreadyResolved);
    }
    if (resolved != null) {
        if (resolved.length > 0) {
            // need re-resolve as extension might have changed
            resolvedFile = resolver.resolveFile(toReadFrom.getParentFile(), toReadFromName != null ? toReadFromName : from);
            String name = null;
            if (resolvedFile.getName().endsWith(".json")) {
                name = constructLibName(resolvedFile, resolver) + ".json";
                ByteArrayOutputStream jsonBao = new ByteArrayOutputStream(resolved.length + 100);
                jsonBao.write("(function(exports, require, module, __filename, __dirname) { module.exports = \n".getBytes("UTF-8"));
                jsonBao.write(resolved);
                String s = constructLibName(requiringFile, resolver);
                jsonBao.write(("})( kgetModule('" + s + "').exports, krequire, kgetModule('" + s + "'), '', '' );").getBytes("UTF-8"));
                resolver.install("/debug/" + name, jsonBao.toByteArray());
            }
        }
    } else {
        if (autoJNPM && jnpmNodeModulesDir != null) {
            String required = importSpec.getFrom();
            int i = required.indexOf("/");
            if (i >= 0) {
                required = required.substring(0, i);
            }
            // single file can't be a node module
            if (required.indexOf(".") < 0) {
                JNPMConfig config = getConfig();
                Log.Info(this, importSpec.getFrom() + " not found. installing .. '" + required + "'");
                try {
                    JNPM.InstallResult await = JNPM.Install(required, null, jnpmNodeModulesDir, config).await(180_000);
                    if (await == JNPM.InstallResult.INSTALLED)
                        return resolveImportSpec(requiringFile, importSpec, resolver, alreadyResolved, ignoredRequires);
                } catch (Throwable kt) {
                    kt.printStackTrace();
                    Log.Error(this, "jnpm install timed out. Check Proxy JVM settings, internet connectivity or just retry");
                }
            }
        }
        Log.Warn(this, importSpec.getFrom() + " not found. requiredBy:" + requiringFile.getCanonicalPath());
    }
    return requiringFile;
}
Also used : JNPM(org.nustaq.kontraktor.webapp.npm.JNPM) JNPMConfig(org.nustaq.kontraktor.webapp.npm.JNPMConfig) JsonValue(com.eclipsesource.json.JsonValue)

Aggregations

JsonValue (com.eclipsesource.json.JsonValue)43 JsonObject (com.eclipsesource.json.JsonObject)19 JsonArray (com.eclipsesource.json.JsonArray)12 HashMap (java.util.HashMap)6 ParseException (com.eclipsesource.json.ParseException)4 IOException (java.io.IOException)4 InetSocketAddress (java.net.InetSocketAddress)3 Member (com.eclipsesource.json.JsonObject.Member)2 JsonUtil.getString (com.hazelcast.util.JsonUtil.getString)2 WalletCallException (com.vaklinov.zcashui.ZCashClientCaller.WalletCallException)2 FileInputStream (java.io.FileInputStream)2 InputStreamReader (java.io.InputStreamReader)2 Reader (java.io.Reader)2 PublicKey (java.security.PublicKey)2 X509EncodedKeySpec (java.security.spec.X509EncodedKeySpec)2 ArrayList (java.util.ArrayList)2 Collection (java.util.Collection)2 Map (java.util.Map)2 EndpointContext (org.eclipse.californium.elements.EndpointContext)2 Link (org.eclipse.leshan.Link)2