Search in sources :

Example 16 with JsonValue

use of com.eclipsesource.json.JsonValue in project leshan by eclipse.

the class DownlinkRequestSerDes method deserialize.

public static DownlinkRequest<?> deserialize(JsonObject o) {
    String kind = o.getString("kind", null);
    String path = o.getString("path", null);
    switch(kind) {
        case "observe":
            {
                int format = o.getInt("contentFormat", ContentFormat.TLV.getCode());
                return new ObserveRequest(ContentFormat.fromCode(format), path);
            }
        case "delete":
            return new DeleteRequest(path);
        case "discover":
            return new DiscoverRequest(path);
        case "create":
            {
                int format = o.getInt("contentFormat", ContentFormat.TLV.getCode());
                int instanceId = o.getInt("instanceId", LwM2mObjectInstance.UNDEFINED);
                Collection<LwM2mResource> resources = new ArrayList<>();
                JsonArray jResources = (JsonArray) o.get("resources");
                for (JsonValue jResource : jResources) {
                    LwM2mResource resource = (LwM2mResource) LwM2mNodeSerDes.deserialize((JsonObject) jResource);
                    resources.add(resource);
                }
                return new CreateRequest(ContentFormat.fromCode(format), path, new LwM2mObjectInstance(instanceId, resources));
            }
        case "execute":
            String parameters = o.getString("parameters", null);
            return new ExecuteRequest(path, parameters);
        case "writeAttributes":
            {
                String observeSpec = o.getString("observeSpec", null);
                return new WriteAttributesRequest(path, ObserveSpec.parse(observeSpec));
            }
        case "write":
            {
                int format = o.getInt("contentFormat", ContentFormat.TLV.getCode());
                Mode mode = o.getString("mode", "REPLACE").equals("REPLACE") ? Mode.REPLACE : Mode.UPDATE;
                LwM2mNode node = LwM2mNodeSerDes.deserialize((JsonObject) o.get("node"));
                return new WriteRequest(mode, ContentFormat.fromCode(format), path, node);
            }
        case "read":
            {
                int format = o.getInt("contentFormat", ContentFormat.TLV.getCode());
                return new ReadRequest(ContentFormat.fromCode(format), path);
            }
        default:
            throw new IllegalStateException("Invalid request missing kind attribute");
    }
}
Also used : CreateRequest(org.eclipse.leshan.core.request.CreateRequest) WriteRequest(org.eclipse.leshan.core.request.WriteRequest) Mode(org.eclipse.leshan.core.request.WriteRequest.Mode) JsonValue(com.eclipsesource.json.JsonValue) JsonObject(com.eclipsesource.json.JsonObject) LwM2mNode(org.eclipse.leshan.core.node.LwM2mNode) ObserveRequest(org.eclipse.leshan.core.request.ObserveRequest) LwM2mResource(org.eclipse.leshan.core.node.LwM2mResource) WriteAttributesRequest(org.eclipse.leshan.core.request.WriteAttributesRequest) JsonArray(com.eclipsesource.json.JsonArray) ExecuteRequest(org.eclipse.leshan.core.request.ExecuteRequest) LwM2mObjectInstance(org.eclipse.leshan.core.node.LwM2mObjectInstance) DiscoverRequest(org.eclipse.leshan.core.request.DiscoverRequest) Collection(java.util.Collection) DeleteRequest(org.eclipse.leshan.core.request.DeleteRequest) ReadRequest(org.eclipse.leshan.core.request.ReadRequest)

Example 17 with JsonValue

use of com.eclipsesource.json.JsonValue in project lite-apps by chimbori.

the class TestHelpers method assertJsonIsWellFormedAndReformat.

static void assertJsonIsWellFormedAndReformat(File file) throws IOException {
    try {
        // Use a stricter parser than {@code Gson}, so we can catch issues such as
        // extra commas after the last element.
        JsonValue manifest = Json.parse(FileUtils.readFully(new FileInputStream(file)));
        // Re-indent the <b>source file</b> by saving the JSON back to the same file.
        FileUtils.writeFile(file, manifest.toString(WriterConfig.PRETTY_PRINT));
    } catch (ParseException e) {
        fail(String.format("%s: %s", file.getPath(), e.getMessage()));
    }
}
Also used : JsonValue(com.eclipsesource.json.JsonValue) ParseException(com.eclipsesource.json.ParseException) FileInputStream(java.io.FileInputStream)

Example 18 with JsonValue

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

the class MessageValidator method read.

public <T> Object read(Class<T> targetType, JsonObject parsed) throws ValidationException, ClassNotFoundException, IllegalAccessException, InstantiationException {
    if (targetType == null) {
        JsonValue jtype = parsed.get("type");
        if (jtype == null || !jtype.isString()) {
            throw new ValidationException("missing type information " + parsed.toString());
        }
        String jtstring = jtype.asString();
        if (type2Clazz.containsKey(jtstring)) {
            targetType = type2Clazz.get(jtstring);
        } else {
            targetType = (Class<T>) Class.forName(jtstring);
        }
    }
    Object target = targetType.newInstance();
    FSTClazzInfo classInfo = conf.getClassInfo(target.getClass());
    FSTClazzInfo.FSTFieldInfo[] fields = classInfo.getFieldInfo();
    for (int i = 0; i < fields.length; i++) {
        FSTClazzInfo.FSTFieldInfo field = fields[i];
        if (field.isPrimitive() || field.getType() == String.class || field.getType().isEnum()) {
            JsonValue jsonValue = parsed.get(field.getName());
            correlatePrimitiveValue(target, field, jsonValue);
        } else if (field.getField().getAnnotation(JsonOption.class) == null)
            throw new ValidationException("unhandled field '" + field.getName() + "' on " + target.getClass());
    }
    Set<String> names = Arrays.stream(fields).map(x -> x.getName()).collect(Collectors.toSet());
    names.add("type");
    String unknown = parsed.names().stream().filter(name -> !names.contains(name)).collect(Collectors.joining(","));
    if (unknown.length() > 0)
        throw new ValidationException("unknown fields in message:" + unknown);
    return target;
}
Also used : Arrays(java.util.Arrays) FSTClazzInfo(org.nustaq.serialization.FSTClazzInfo) Map(java.util.Map) JsonObject(com.eclipsesource.json.JsonObject) FSTConfiguration(org.nustaq.serialization.FSTConfiguration) Set(java.util.Set) HashMap(java.util.HashMap) Collectors(java.util.stream.Collectors) JsonValue(com.eclipsesource.json.JsonValue) JsonValue(com.eclipsesource.json.JsonValue) JsonObject(com.eclipsesource.json.JsonObject) FSTClazzInfo(org.nustaq.serialization.FSTClazzInfo)

Example 19 with JsonValue

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

the class UndertowRESTHandler method parseAndDispatch.

private void parseAndDispatch(HttpServerExchange exchange, String[] split, String rawPath, Method m, byte[] postData) {
    try {
        Class<?>[] parameterTypes = m.getParameterTypes();
        Annotation[][] parameterAnnotations = m.getParameterAnnotations();
        Object[] args = new Object[parameterTypes.length];
        int splitIndex = 1;
        try {
            for (int i = 0; i < parameterTypes.length; i++) {
                Class<?> parameterType = parameterTypes[i];
                Annotation[] parameterAnnotation = parameterAnnotations[i];
                if (parameterAnnotation != null && parameterAnnotation.length > 0) {
                    if (parameterAnnotation[0].annotationType() == FromQuery.class) {
                        String value = ((FromQuery) parameterAnnotation[0]).value();
                        Deque<String> strings = exchange.getQueryParameters().get(value);
                        if (strings != null) {
                            args[i] = inferValue(parameterType, strings.getFirst());
                        }
                        continue;
                    } else if (parameterAnnotation[0].annotationType() == RequestPath.class) {
                        args[i] = rawPath;
                        continue;
                    }
                }
                if (splitIndex < split.length) {
                    String stringVal = split[splitIndex];
                    Object val = inferValue(parameterType, stringVal);
                    if (val != NOVAL) {
                        args[i] = val;
                        splitIndex++;
                        continue;
                    }
                }
                // specials
                if (parameterType == HeaderMap.class) {
                    args[i] = exchange.getRequestHeaders();
                } else if (parameterType == String[].class) {
                    args[i] = split;
                } else if (parameterType == JsonObject.class || parameterType == JsonValue.class) {
                    args[i] = Json.parse(new String(postData, "UTF-8"));
                } else if (parameterType == byte[].class) {
                    args[i] = postData;
                } else if (parameterType == Map.class) {
                    args[i] = exchange.getQueryParameters();
                } else {
                    System.out.println("unsupported parameter type " + parameterType.getName());
                }
            }
        } catch (Throwable th) {
            th.printStackTrace();
            Log.Warn(this, th, postData != null ? new String(postData, 0) : "");
            exchange.setStatusCode(400);
            exchange.getResponseSender().send("" + th + "\n");
            return;
        }
        // change: allow incomplete parameters
        // if ( splitIndex != split.length ) {
        // exchange.setResponseCode(400);
        // exchange.endExchange();
        // return;
        // }
        Object invoke = m.invoke(facade.getActorRef(), args);
        if (invoke instanceof IPromise) {
            checkExchangeState(exchange);
            ((IPromise) invoke).then((r, e) -> {
                if (e != null) {
                    exchange.setStatusCode(500);
                    exchange.getResponseSender().send("" + e);
                } else {
                    checkExchangeState(exchange);
                    if (r instanceof String) {
                        exchange.setStatusCode(400);
                        exchange.getResponseSender().send("" + e);
                    } else if (r instanceof Integer) {
                        exchange.setStatusCode((Integer) r);
                        exchange.endExchange();
                    } else if (r instanceof Pair) {
                        exchange.setStatusCode((Integer) ((Pair) r).car());
                        exchange.getResponseSender().send("" + ((Pair) r).cdr());
                    } else if (r instanceof JsonValue) {
                        exchange.getResponseSender().send(r.toString());
                    } else if (r instanceof Serializable) {
                        byte[] bytes = jsonConf.asByteArray(r);
                        exchange.getResponseSender().send(ByteBuffer.wrap(bytes));
                    }
                }
            });
        } else if (invoke == null) {
            exchange.setStatusCode(200);
            exchange.endExchange();
        }
    } catch (Exception e) {
        Log.Warn(this, e);
        exchange.setStatusCode(500);
        exchange.getResponseSender().send("" + e);
        exchange.endExchange();
        return;
    }
}
Also used : Serializable(java.io.Serializable) JsonValue(com.eclipsesource.json.JsonValue) JsonObject(com.eclipsesource.json.JsonObject) Annotation(java.lang.annotation.Annotation) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IPromise(org.nustaq.kontraktor.IPromise) JsonObject(com.eclipsesource.json.JsonObject) Pair(org.nustaq.kontraktor.util.Pair)

Example 20 with JsonValue

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

the class JNPM method npmInstall.

public IPromise<InstallResult> npmInstall(String module, String versionSpec, File importingModuleDir) {
    if (versionSpec == null) {
        versionSpec = "latest";
    }
    File nodeModule = new File(nodeModulesDir, module);
    boolean installPrivate = false;
    if (nodeModule.exists()) {
        File targetDir = importingModuleDir.getName().equals("node_modules") ? nodeModulesDir : new File(importingModuleDir, "node_modules");
        String moduleKey = createModuleKey(module, targetDir);
        List<Promise> promises = packagesUnderway.get(moduleKey);
        if (promises != null) {
            int debug = 1;
        }
        String finalVersionSpec1 = versionSpec;
        if (// timing: not unpacked
        promises != null && promises.size() > 0) {
            Log.Warn(this, "Delaying because in transfer:" + module + " " + targetDir.getAbsolutePath());
            Promise p = new Promise();
            delayed(1000, () -> npmInstall(module, finalVersionSpec1, importingModuleDir).then(p));
            return p;
        }
        File pack = new File(nodeModule, "package.json");
        if (pack.exists() && versionSpec.indexOf(".") > 0) {
            String version = null;
            String vspec = null;
            try {
                JsonObject pjson = Json.parse(new FileReader(pack)).asObject();
                version = pjson.getString("version", null);
                vspec = versionSpec;
                if (!matches(version, vspec)) {
                    Log.Warn(this, "version mismatch for module '" + module + "'. requested:" + versionSpec + " from '" + importingModuleDir.getName() + "' installed:" + version + ". (delete module dir for update)");
                    if (config.getVersion(module) == null) {
                        installPrivate = true;
                        Log.Warn(this, "   installing private " + module);
                    } else {
                        Log.Warn(this, "   stick with mismatch because of jnpm.kson config entry for " + module);
                    }
                }
            } catch (Exception e) {
                Log.Error(this, "can't parse package.json in " + module + " " + importingModuleDir.getAbsolutePath() + ". Retry");
                Promise p = new Promise();
                delayed(1000, () -> npmInstall(module, finalVersionSpec1, importingModuleDir).then(p));
                return p;
            }
        } else
            return resolve(InstallResult.EXISTS);
    }
    Promise p = new Promise();
    // fire in parallel
    IPromise<List<String>> versionProm = getVersions(module);
    IPromise<JsonObject> distributionsProm = getDistributions(module);
    String finalVersionSpec = versionSpec == null ? "latest" : versionSpec;
    boolean finalInstallPrivate = installPrivate;
    distributionsProm.then((dist, derr) -> {
        if (dist == null) {
            dist = new JsonObject();
            Log.Error(this, "distribution is empty or error " + derr + " in module:" + module);
        }
        JsonObject finalDist = dist;
        versionProm.then((versions, verr) -> {
            if (versions == null) {
                p.reject(verr);
                return;
            }
            String resolvedVersion = getVersion(module, finalVersionSpec, versions, finalDist);
            http.getContent(config.getRepo() + "/" + module + "/" + resolvedVersion).then((cont, err) -> {
                if (cont != null) {
                    JsonObject pkg = Json.parse(cont).asObject();
                    String tarUrl = pkg.get("dist").asObject().get("tarball").asString();
                    JsonValue dependencies = pkg.get("dependencies");
                    if (dependencies == null)
                        dependencies = new JsonObject();
                    else
                        dependencies = dependencies.asObject();
                    JsonValue peerdependencies = pkg.get("peerDependencies");
                    if (peerdependencies != null) {
                        ((JsonObject) dependencies).merge(peerdependencies.asObject());
                    }
                    File targetDir = finalInstallPrivate ? new File(importingModuleDir, "node_modules") : nodeModulesDir;
                    if (finalInstallPrivate)
                        targetDir.mkdirs();
                    IPromise depP = downLoadAndInstall(tarUrl, module, resolvedVersion, targetDir);
                    List deps = new ArrayList<>();
                    deps.add(depP);
                    File importingDir = new File(nodeModulesDir, module);
                    ((JsonObject) dependencies).forEach(member -> {
                        deps.add(npmInstall(member.getName(), member.getValue().asString(), importingDir));
                    });
                    all(deps).then((r, e) -> {
                        p.resolve(InstallResult.INSTALLED);
                    });
                } else {
                    p.reject("no such module");
                }
            });
        });
    });
    return p;
}
Also used : JsonValue(com.eclipsesource.json.JsonValue) JsonObject(com.eclipsesource.json.JsonObject) ArchiveException(org.apache.commons.compress.archivers.ArchiveException) Promise(org.nustaq.kontraktor.Promise) IPromise(org.nustaq.kontraktor.IPromise) IPromise(org.nustaq.kontraktor.IPromise)

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