Example usage for com.google.gson JsonObject getAsJsonPrimitive

List of usage examples for com.google.gson JsonObject getAsJsonPrimitive

Introduction

In this page you can find the example usage for com.google.gson JsonObject getAsJsonPrimitive.

Prototype

public JsonPrimitive getAsJsonPrimitive(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonPrimitive element.

Usage

From source file:hello.Hello.java

License:Apache License

public static JsonObject main(JsonObject args) {
    String name;/*from  w  w  w .  j  a  v  a 2s  .c  om*/

    try {
        name = args.getAsJsonPrimitive("name").getAsString();
    } catch (Exception e) {
        name = "stranger";
    }

    JsonObject response = new JsonObject();
    response.addProperty("greeting", "Hello " + name + "!");
    return response;
}

From source file:ideal.showcase.coach.marshallers.marshaller.java

License:Open Source License

public @Nullable datastore_state unmarshal_state(json_data the_data) {
    if (the_data == null) {
        return null;
    }/*from w w w . j av a 2  s.  c om*/

    JsonObject obj = the_data.the_object;

    String source_version = null;
    if (obj.has(SOURCE_VERSION.s())) {
        source_version = obj.getAsJsonPrimitive(SOURCE_VERSION.s()).getAsString();
    }

    string version_id;
    if (obj.has(VERSION_ID.s())) {
        version_id = new base_string(obj.getAsJsonPrimitive(VERSION_ID.s()).getAsString());
    } else {
        // Compatibility with old data format
        version_id = new base_string(the_schema.version, "/null");
    }

    datastore_state world = the_schema.new_value(new base_string(source_version), version_id);

    JsonArray values = obj.getAsJsonArray(DATA);

    // We need to do this in two passes to handle forward references correctly.
    // First pass: create data values with IDs only
    for (JsonElement val : values) {
        if (val instanceof JsonObject) {
            JsonObject val_object = (JsonObject) val;
            String val_type = val_object.get(DATA_TYPE).getAsString();
            data_type dt = the_schema.lookup_data_type(new base_string(val_type));
            if (dt == null) {
                continue;
            }
            data_value dv = dt.new_value(world);
            string_value id = from_json_string(val_object.get(DATA_ID));
            dv.put_var(the_schema.data_id_field(), id);
            world.do_add_data(dv);
        }
    }

    // Second pass: parse data values
    for (JsonElement val : values) {
        if (val instanceof JsonObject) {
            JsonObject val_object = (JsonObject) val;
            string_value id = from_json_string(val_object.get(DATA_ID));
            data_value dv = world.get_data_by_id(id.unwrap());
            if (dv != null) {
                read_from_json(dv, val_object, world);
            }
        }
    }

    // put_field()s might have reset the version_id, so we set it again.
    world.set_version_id(version_id);

    return world;
}

From source file:io.flutter.preview.PreviewArea.java

License:Open Source License

private void fillIdToRenderObject(@NotNull JsonObject renderJson) {
    rootRenderObject = null;/*from  w  w  w.j av a  2  s  .co  m*/
    idToRenderObject.clear();
    for (Map.Entry<String, JsonElement> entry : renderJson.entrySet()) {
        try {
            final int id = Integer.parseInt(entry.getKey());

            final JsonObject widgetObject = (JsonObject) entry.getValue();

            final JsonObject boundsObject = widgetObject.getAsJsonObject("globalBounds");
            final int left = boundsObject.getAsJsonPrimitive("left").getAsInt();
            final int top = boundsObject.getAsJsonPrimitive("top").getAsInt();
            final int width = boundsObject.getAsJsonPrimitive("width").getAsInt();
            final int height = boundsObject.getAsJsonPrimitive("height").getAsInt();
            final Rectangle rect = new Rectangle(left, top, width, height);

            final RenderObject renderObject = new RenderObject(rect);

            if (rootRenderObject == null) {
                rootWidgetId = id;
                rootRenderObject = renderObject;
            }

            idToRenderObject.put(id, renderObject);
        } catch (Throwable ignored) {
        }
    }
}

From source file:io.flutter.run.daemon.DaemonApi.java

License:Open Source License

/**
 * Parses some JSON and handles it as either a command's response or an event.
 *///from  w  w w.j  a  v  a 2 s  .c o  m
void dispatch(@NotNull String json, @Nullable DaemonEvent.Listener listener) {
    final JsonObject obj;
    try {
        final JsonParser jp = new JsonParser();
        final JsonElement elem = jp.parse(json);
        obj = elem.getAsJsonObject();
    } catch (JsonSyntaxException e) {
        LOG.error("Unable to parse response from Flutter daemon", e);
        return;
    }

    final JsonPrimitive primId = obj.getAsJsonPrimitive("id");
    if (primId == null) {
        // It's an event.
        if (listener != null) {
            DaemonEvent.dispatch(obj, listener);
        } else {
            LOG.info("ignored event from Flutter daemon: " + json);
        }
        return;
    }

    final int id;
    try {
        id = primId.getAsInt();
    } catch (NumberFormatException e) {
        LOG.error("Unable to parse response from Flutter daemon", e);
        return;
    }

    final JsonElement error = obj.get("error");
    if (error != null) {
        LOG.warn("Flutter process returned an error: " + json);
        final Command cmd = takePending(id);
        if (cmd != null) {
            cmd.completeExceptionally(new IOException("unexpected response: " + json));
        }
    }

    final JsonElement result = obj.get("result");
    complete(id, result);
}

From source file:io.flutter.run.daemon.DaemonEvent.java

License:Open Source License

/**
 * Parses an event and sends it to the listener.
 *///from   w w w .  j  a  va 2s . co  m
static void dispatch(@NotNull JsonObject obj, @NotNull Listener listener) {
    final JsonPrimitive primEvent = obj.getAsJsonPrimitive("event");
    if (primEvent == null) {
        LOG.error("Missing event field in JSON from flutter process: " + obj);
        return;
    }

    final String eventName = primEvent.getAsString();
    if (eventName == null) {
        LOG.error("Unexpected event field in JSON from flutter process: " + obj);
        return;
    }

    final JsonObject params = obj.getAsJsonObject("params");
    if (params == null) {
        LOG.error("Missing parameters in event from flutter process: " + obj);
        return;
    }

    final DaemonEvent event = create(eventName, params);
    if (event == null) {
        return; // Drop unknown event.
    }

    event.accept(listener);
}

From source file:io.flutter.run.daemon.FlutterAppManager.java

License:Open Source License

void processInput(@NotNull String string, @NotNull FlutterDaemonController controller) {
    try {// ww  w .j  a v a2s . c om
        JsonParser jp = new JsonParser();
        JsonElement elem = jp.parse(string);
        JsonObject obj = elem.getAsJsonObject();
        JsonPrimitive primId = obj.getAsJsonPrimitive("id");
        if (primId == null) {
            handleEvent(obj, controller, string);
        } else {
            handleResponse(primId.getAsInt(), obj, controller);
        }
    } catch (JsonSyntaxException ex) {
        myLogger.error(ex);
    }
}

From source file:io.flutter.run.daemon.FlutterAppManager.java

License:Open Source License

void handleEvent(@NotNull JsonObject obj, @NotNull FlutterDaemonController controller, @NotNull String json) {
    JsonPrimitive primEvent = obj.getAsJsonPrimitive("event");
    if (primEvent == null) {
        myLogger.error("Invalid JSON from flutter: " + json);
        return;//from www .  j a  va  2 s. c  o m
    }
    String eventName = primEvent.getAsString();
    JsonObject params = obj.getAsJsonObject("params");
    if (eventName == null || params == null) {
        myLogger.error("Bad event from flutter: " + json);
        return;
    }
    Event eventHandler = eventHandler(eventName, json);
    if (eventHandler == null)
        return;
    eventHandler.from(params).process(this, controller);
}

From source file:io.flutter.sdk.FlutterSdk.java

License:Open Source License

private String queryFlutterConfigImpl(String key) {
    final FlutterCommand command = flutterConfig("--machine");
    final OSProcessHandler process = command.startProcess(false);

    if (process == null) {
        return null;
    }//from   www.  ja  v  a 2  s .  com

    final StringBuilder stdout = new StringBuilder();
    process.addProcessListener(new ProcessAdapter() {
        boolean hasSeenStartingBrace = false;

        @Override
        public void onTextAvailable(@NotNull ProcessEvent event, @NotNull Key outputType) {
            // {"android-studio-dir":"/Applications/Android Studio 3.0 Preview.app/Contents"}
            if (outputType == ProcessOutputTypes.STDOUT) {
                // Ignore any non-json starting lines (like "Building flutter tool...").
                if (event.getText().startsWith("{")) {
                    hasSeenStartingBrace = true;
                }
                if (hasSeenStartingBrace) {
                    stdout.append(event.getText());
                }
            }
        }
    });

    LOG.info("Calling config --machine");
    final long start = System.currentTimeMillis();

    process.startNotify();

    if (process.waitFor(5000)) {
        final long duration = System.currentTimeMillis() - start;
        LOG.info("flutter config --machine: " + duration + "ms");

        final Integer code = process.getExitCode();
        if (code != null && code == 0) {
            try {
                final JsonParser jp = new JsonParser();
                final JsonElement elem = jp.parse(stdout.toString());
                final JsonObject obj = elem.getAsJsonObject();
                final JsonPrimitive primitive = obj.getAsJsonPrimitive(key);
                if (primitive != null) {
                    return primitive.getAsString();
                }
            } catch (JsonSyntaxException ignored) {
            }
        } else {
            LOG.info("Exit code from flutter config --machine: " + code);
        }
    } else {
        LOG.info("Timeout when calling flutter config --machine");
    }

    return null;
}

From source file:io.github.prison.adapters.LocationAdapter.java

License:Open Source License

@Override
public Location deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    if (!json.isJsonObject())
        return null;
    JsonObject object = json.getAsJsonObject();

    String worldName = object.getAsJsonPrimitive(WORLD).getAsString();
    World world = Prison.getInstance().getPlatform().getWorld(worldName);

    double x = object.getAsJsonPrimitive(X).getAsDouble();
    double y = object.getAsJsonPrimitive(Y).getAsDouble();
    double z = object.getAsJsonPrimitive(Z).getAsDouble();
    float pitch = object.getAsJsonPrimitive(PITCH).getAsFloat();
    float yaw = object.getAsJsonPrimitive(YAW).getAsFloat();

    return new Location(world, x, y, z, pitch, yaw);
}

From source file:io.hawkcd.utilities.deserializers.TokenAdapter.java

License:Apache License

public static TokenInfo verifyToken(String token) {
    if (token == null) {
        return null;
    }//from w  ww  . j  a va2 s.co m

    try {
        final Verifier hmacVerifier = new HmacSHA256Verifier(SIGNING_KEY.getBytes());

        VerifierProvider hmacLocator = (id, key) -> Lists.newArrayList(hmacVerifier);
        VerifierProviders locators = new VerifierProviders();
        locators.setVerifierProvider(SignatureAlgorithm.HS256, hmacLocator);

        Checker checker = payload -> {
        };

        JsonTokenParser jsonTokenParser = new JsonTokenParser(locators, checker);
        JsonToken jsonToken;
        try {
            jsonToken = jsonTokenParser.verifyAndDeserialize(token);
        } catch (SignatureException | IllegalArgumentException e) {
            return null;
            //                throw new RuntimeException(e);
        }

        JsonObject payload = jsonToken.getPayloadAsJsonObject();
        TokenInfo t = new TokenInfo();
        String issuer = payload.getAsJsonPrimitive("iss").getAsString();
        String userIdString = payload.getAsJsonObject("info").getAsJsonPrimitive("user").getAsString();

        User user = gson.fromJson(userIdString, User.class);
        Long expireDate = payload.getAsJsonPrimitive("exp").getAsLong();
        if (issuer.equals(ISSUER) && (userIdString != null)) {
            t.setUser(user);
            t.setExpires(getDateTimeFromTimestamp(expireDate));
            return t;
        } else {
            return null;
        }
    } catch (InvalidKeyException e1) {
        throw new RuntimeException(e1);
    }
}