Example usage for com.google.gson JsonPrimitive getAsString

List of usage examples for com.google.gson JsonPrimitive getAsString

Introduction

In this page you can find the example usage for com.google.gson JsonPrimitive getAsString.

Prototype

@Override
public String getAsString() 

Source Link

Document

convenience method to get this element as a String.

Usage

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

License:Open Source License

/**
 * Parses an event and sends it to the listener.
 *//*from ww  w .j av  a 2  s.c o  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 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;//  ww w. ja v  a 2 s  . com
    }
    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  .j  a  v a 2 s. c o m

    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.kodokojo.commons.utils.properties.provider.kv.ConsulKvPropertyValueProvider.java

License:Open Source License

@Override
protected String provideValue(String key) {
    if (isBlank(key)) {
        throw new IllegalArgumentException("key must be defined.");
    }//from www  .  j  av  a2 s. co m
    try {
        JsonArray values = consulKvRest.getValueResult(key);
        JsonObject json = values.get(0).getAsJsonObject();

        String res = null;
        if (json != null) {
            JsonPrimitive primitive = json.getAsJsonPrimitive("Value");
            if (primitive != null) {
                String value = primitive.getAsString();
                res = new String(Base64.getDecoder().decode(value));
            }
        }
        return res;
    } catch (RetrofitError e) {
        if ("404 Not Found".equals(e.getMessage())) {
            return null;
        }
        throw e;
    }
}

From source file:io.kodokojo.endpoint.dto.WebSocketMessageGsonAdapter.java

License:Open Source License

@Override
public WebSocketMessage deserialize(JsonElement input, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject json = (JsonObject) input;
    JsonPrimitive jsonEntity = json.getAsJsonPrimitive("entity");
    if (jsonEntity == null) {
        throw new JsonParseException("entity attribute expected.");
    }/*from  www . j a v  a2 s  .com*/
    String entity = jsonEntity.getAsString();
    JsonPrimitive jsonAction = json.getAsJsonPrimitive("action");
    if (jsonAction == null) {
        throw new JsonParseException("action attribute expected.");
    }
    String action = jsonAction.getAsString();
    JsonObject jsonData = json.getAsJsonObject("data");
    if (jsonData == null) {
        throw new JsonParseException("data attribute expected.");
    }

    return new WebSocketMessage(entity, action, jsonData);
}

From source file:io.motown.operatorapi.json.gson.deserializer.AddressTypeAdapterDeserializer.java

License:Apache License

@Override
public Address deserialize(JsonElement jsonElement, Type type,
        JsonDeserializationContext jsonDeserializationContext) {
    JsonObject obj;/* ww  w.j  a v a 2s .c  om*/

    try {
        obj = jsonElement.getAsJsonObject();
        if (obj == null) {
            return null;
        }
    } catch (ClassCastException | IllegalStateException e) {
        throw new JsonParseException("Address must be a JSON object", e);
    }

    String addressLine1 = obj.getAsJsonPrimitive("addressLine1").getAsString();
    String city = obj.getAsJsonPrimitive("city").getAsString();
    String country = obj.getAsJsonPrimitive("country").getAsString();

    JsonPrimitive addressLine2Obj = obj.getAsJsonPrimitive("addressLine2"),
            postalCodeObj = obj.getAsJsonPrimitive("postalCode"), regionObj = obj.getAsJsonPrimitive("region");

    String addressLine2 = addressLine2Obj != null ? addressLine2Obj.getAsString() : "";
    String postalCode = postalCodeObj != null ? postalCodeObj.getAsString() : "";
    String region = regionObj != null ? regionObj.getAsString() : "";

    return new Address(addressLine1, addressLine2, postalCode, city, region, country);
}

From source file:io.motown.operatorapi.json.gson.deserializer.TextualTokenTypeAdapterDeserializer.java

License:Apache License

@Override
public TextualToken deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
    JsonObject obj;/*  ww w .j ava  2 s  .  c o  m*/
    String token;

    try {
        obj = json.getAsJsonObject();
    } catch (ClassCastException | IllegalStateException e) {
        throw new JsonParseException("TextualToken must be a JSON object", e);
    }

    try {
        token = obj.getAsJsonPrimitive(TOKEN_MEMBER) != null
                ? obj.getAsJsonPrimitive(TOKEN_MEMBER).getAsString()
                : "";
    } catch (ClassCastException | IllegalStateException e) {
        throw new JsonParseException("token must be a JSON string", e);
    }

    try {
        JsonPrimitive authenticationStatus = obj.getAsJsonPrimitive("status");
        if (authenticationStatus != null) {
            String status = authenticationStatus.getAsString();
            return new TextualToken(token, IdentifyingToken.AuthenticationStatus.valueOf(status));
        }
    } catch (ClassCastException | IllegalStateException e) {
        throw new JsonParseException("status must be a JSON string", e);
    }

    return new TextualToken(token);
}

From source file:io.soliton.protobuf.json.JsonRpcRequest.java

License:Apache License

public static JsonRpcRequest fromJson(JsonElement root) throws JsonRpcError {
    if (!root.isJsonObject()) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "Received payload is not a JSON Object");
    }/*from   w  w  w . j  a  v  a 2  s.  c  o  m*/

    JsonObject request = root.getAsJsonObject();
    JsonElement id = request.get(JsonRpcProtocol.ID);
    JsonElement methodNameElement = request.get(JsonRpcProtocol.METHOD);
    JsonElement paramsElement = request.get(JsonRpcProtocol.PARAMETERS);

    if (id == null) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "Malformed request, missing 'id' property");
    }

    if (methodNameElement == null) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "Malformed request, missing 'method' property");
    }

    if (paramsElement == null) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "Malformed request, missing 'params' property");
    }

    if (!methodNameElement.isJsonPrimitive()) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "Method name is not a JSON primitive");
    }

    JsonPrimitive methodName = methodNameElement.getAsJsonPrimitive();
    if (!methodName.isString()) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "Method name is not a string");
    }

    if (!paramsElement.isJsonArray()) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "'params' property is not an array");
    }

    JsonArray params = paramsElement.getAsJsonArray();
    if (params.size() != 1) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "'params' property is not an array");
    }

    JsonElement paramElement = params.get(0);
    if (!paramElement.isJsonObject()) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "Parameter is not an object");
    }

    JsonObject parameter = paramElement.getAsJsonObject();
    List<String> serviceAndMethod = Lists.newArrayList(DOT_SPLITTER.split(methodName.getAsString()));

    String methodNameString = methodName.getAsString();
    int dotIndex = methodNameString.lastIndexOf('.');

    if (dotIndex < 0) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "'method' property is not properly formatted");
    }

    if (dotIndex == methodNameString.length() - 1) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "'method' property is not properly formatted");
    }

    String service = methodNameString.substring(0, dotIndex);
    String method = methodNameString.substring(dotIndex + 1);

    if (service.isEmpty() || method.isEmpty()) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "'method' property is not properly formatted");
    }

    if (serviceAndMethod.size() < 2) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "'method' property is not properly formatted");
    }

    return new JsonRpcRequest(service, method, id, parameter);
}

From source file:io.thinger.thinger.views.Element.java

License:Open Source License

public static Element createPrimitiveElement(String name, JsonPrimitive primitive, LinearLayout layout,
        boolean output) {
    if (primitive.isBoolean()) {
        return new BoolValue(layout, name, primitive.getAsBoolean(), output);
    } else if (primitive.isNumber()) {
        return new NumberValue(layout, name, primitive.getAsNumber(), output);
    } else if (primitive.isString()) {
        return new StringValue(layout, name, primitive.getAsString(), output);
    }//  w  ww  . j a v a2  s.c om
    return null;
}

From source file:io.winterdev.server.SmsManager.java

public boolean sendSms(String num, String text) {

    try {/*ww  w .j  a  va  2 s.co  m*/
        JsonObject response = ApiGetter.get("https://rest.nexmo.com/sms/json?api_key=" + Private.NEXMO_KEY
                + "&api_secret=" + Private.NEXMO_SECRET + "&to=" + num + "&text=" + text + "&from="
                + Private.NEXMO_NUMBER);
        JsonObject messages = response.getAsJsonArray("messages").get(0).getAsJsonObject();
        JsonPrimitive status = messages.getAsJsonPrimitive("status");
        if (status.getAsString().equalsIgnoreCase("0"))
            return true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}