Example usage for com.google.gson JsonElement isJsonNull

List of usage examples for com.google.gson JsonElement isJsonNull

Introduction

In this page you can find the example usage for com.google.gson JsonElement isJsonNull.

Prototype

public boolean isJsonNull() 

Source Link

Document

provides check for verifying if this element represents a null value or not.

Usage

From source file:br.com.thiaguten.contrib.JsonContrib.java

License:Apache License

/**
 * Converts an object into a {@code JsonElement}, search values by their keys and returns first not null occurrence found
 *
 * @param object object you wish to obtain the value
 * @param keys   keys to search on {@code JsonElement}
 * @return first not null occurrence found
 */// ww w  . j a v  a 2  s.  c  o  m
public static String findFirstNotNullValueByKeys(Object object, String... keys) {
    List<Object> occurrencesFound = findValuesByKeys(object, keys);
    if (occurrencesFound != null && !occurrencesFound.isEmpty()) {
        for (Object obj : occurrencesFound) {
            JsonElement jsonElement = parseObject(obj);
            if (jsonElement != null && !jsonElement.isJsonNull()) {
                return getJsonElementAsString(jsonElement);
            }
        }
    }
    return null;
}

From source file:brooklyn.entity.mesos.MesosClusterImpl.java

License:Apache License

public List<String> scanFrameworks(JsonArray frameworks) {
    List<String> frameworkNames = MutableList.<String>of();
    for (int i = 0; i < frameworks.size(); i++) {
        JsonObject task = frameworks.get(i).getAsJsonObject();
        String id = task.get("id").getAsString();
        JsonElement pidObj = task.get("pid");
        String pid = null;/*  w ww.j  a va2 s  .  c  o m*/
        if (pidObj != null && !pidObj.isJsonNull()) {
            pid = pidObj.getAsString();
        }
        String name = task.get("name").getAsString();
        String url = task.get("webui_url").getAsString();
        frameworkNames.add(name);

        Optional<Entity> entity = Iterables.tryFind(sensors().get(MESOS_FRAMEWORKS).getMembers(), Predicates
                .compose(Predicates.equalTo(id), EntityFunctions.attribute(MesosFramework.FRAMEWORK_ID)));
        if (entity.isPresent())
            continue;

        EntitySpec<? extends MesosFramework> frameworkSpec = EntitySpec
                .create(FRAMEWORKS.containsKey(name) ? FRAMEWORKS.get(name)
                        : EntitySpec.create(MesosFramework.class))
                .configure(MesosFramework.FRAMEWORK_ID, id).configure(MesosFramework.FRAMEWORK_PID, pid)
                .configure(MesosFramework.FRAMEWORK_NAME, name).configure(MesosFramework.FRAMEWORK_URL, url)
                .configure(MesosFramework.MESOS_CLUSTER, this)
                .displayName(String.format("%s Framework", Strings.toInitialCapOnly(name)));
        MesosFramework added = sensors().get(MESOS_FRAMEWORKS).addMemberChild(frameworkSpec);
        added.start(ImmutableList.<Location>of());
    }
    return frameworkNames;
}

From source file:brooklyn.entity.mesos.task.marathon.MarathonTaskImpl.java

License:Apache License

@Override
public void connectSensors() {
    // TODO If we are not "mesos.task.managed", then we are just guessing at the appId. We may get 
    // it wrong. If it's wrong then our uri will always give 404. We should not mark the task as
    // "serviceUp=false", and we should not clear the TASK_ID (which was correctly set in
    // MesosFramework.scanTasks, which is where this task came from in the first place).
    // The new behaviour of showing it as healthy (and not clearing the taskId, which caused 
    // another instance to be automatically added!) is better than it was, but it definitely  
    // needs more attention.

    final boolean managed = Boolean.TRUE.equals(sensors().get(MANAGED));

    String uri = Urls.mergePaths(getFramework().sensors().get(MarathonFramework.FRAMEWORK_URL), "/v2/apps",
            sensors().get(APPLICATION_ID), "tasks");
    HttpFeed.Builder httpFeedBuilder = HttpFeed.builder().entity(this).period(2000, TimeUnit.MILLISECONDS)
            .baseUri(uri)/*from  w w  w.  j  av a  2  s  .  c om*/
            .credentialsIfNotNull(
                    config().get(MesosCluster.MESOS_USERNAME), config().get(MesosCluster.MESOS_PASSWORD))
            .header("Accept", "application/json")
            .poll(new HttpPollConfig<Boolean>(SERVICE_UP).suppressDuplicates(true)
                    .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.walk("tasks"),
                            new Function<JsonElement, Boolean>() {
                                @Override
                                public Boolean apply(JsonElement input) {
                                    JsonArray tasks = input.getAsJsonArray();
                                    return tasks.size() == 1;
                                }
                            }))
                    .onFailureOrException(Functions.constant(managed ? Boolean.FALSE : true)))
            .poll(new HttpPollConfig<Long>(TASK_STARTED_AT).suppressDuplicates(true)
                    .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.walk("tasks"),
                            new Function<JsonElement, Long>() {
                                @Override
                                public Long apply(JsonElement input) {
                                    JsonArray tasks = input.getAsJsonArray();
                                    for (JsonElement each : tasks) {
                                        JsonElement startedAt = each.getAsJsonObject().get("startedAt");
                                        if (startedAt != null && !startedAt.isJsonNull()) {
                                            return Time.parseDate(startedAt.getAsString()).getTime();
                                        }
                                    }
                                    return null;
                                }
                            }))
                    .onFailureOrException(Functions.<Long>constant(-1L)))
            .poll(new HttpPollConfig<Long>(TASK_STAGED_AT).suppressDuplicates(true)
                    .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.walk("tasks"),
                            new Function<JsonElement, Long>() {
                                @Override
                                public Long apply(JsonElement input) {
                                    JsonArray tasks = input.getAsJsonArray();
                                    for (JsonElement each : tasks) {
                                        JsonElement stagedAt = each.getAsJsonObject().get("stagedAt");
                                        if (stagedAt != null && !stagedAt.isJsonNull()) {
                                            return Time.parseDate(stagedAt.getAsString()).getTime();
                                        }
                                    }
                                    return null;
                                }
                            }))
                    .onFailureOrException(Functions.<Long>constant(-1L)))
            .poll(new HttpPollConfig<String>(Attributes.HOSTNAME).suppressDuplicates(true)
                    .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.walk("tasks"),
                            new Function<JsonElement, String>() {
                                @Override
                                public String apply(JsonElement input) {
                                    JsonArray tasks = input.getAsJsonArray();
                                    for (JsonElement each : tasks) {
                                        JsonElement host = each.getAsJsonObject().get("host");
                                        if (host != null && !host.isJsonNull()) {
                                            return host.getAsString();
                                        }
                                    }
                                    return null;
                                }
                            }))
                    .onFailureOrException(Functions.<String>constant(null)))
            .poll(new HttpPollConfig<String>(TASK_ID).suppressDuplicates(true)
                    .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.walk("tasks"),
                            new Function<JsonElement, String>() {
                                @Override
                                public String apply(JsonElement input) {
                                    JsonArray tasks = input.getAsJsonArray();
                                    for (JsonElement each : tasks) {
                                        JsonElement id = each.getAsJsonObject().get("id");
                                        if (id != null && !id.isJsonNull()) {
                                            return id.getAsString();
                                        }
                                    }
                                    return null;
                                }
                            }))
                    .onFailureOrException(
                            (Function) Functions.<Object>constant(managed ? null : FeedConfig.UNCHANGED)))
            .poll(new HttpPollConfig<String>(Attributes.ADDRESS).suppressDuplicates(true)
                    .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.walk("tasks"),
                            new Function<JsonElement, String>() {
                                @Override
                                public String apply(JsonElement input) {
                                    JsonArray tasks = input.getAsJsonArray();
                                    for (JsonElement each : tasks) {
                                        JsonElement host = each.getAsJsonObject().get("host");
                                        if (host != null && !host.isJsonNull()) {
                                            try {
                                                return InetAddress.getByName(host.getAsString())
                                                        .getHostAddress();
                                            } catch (UnknownHostException uhe) {
                                                Exceptions.propagate(uhe);
                                            }
                                        }
                                    }
                                    return null;
                                }
                            }))
                    .onFailureOrException(Functions.<String>constant(null)));
    httpFeed = httpFeedBuilder.build();
}

From source file:brooklyn.entity.mesos.task.marathon.MarathonTaskImpl.java

License:Apache License

public Optional<JsonElement> getApplicationJson() {
    MesosFramework framework = getFramework();
    String uri = Urls.mergePaths(framework.sensors().get(MarathonFramework.FRAMEWORK_URL), "/v2/apps",
            sensors().get(APPLICATION_ID));
    HttpToolResponse response = HttpTool.httpGet(MesosUtils.buildClient(framework), URI.create(uri),
            MutableMap.of(HttpHeaders.ACCEPT, "application/json"));
    if (!HttpTool.isStatusCodeHealthy(response.getResponseCode())) {
        return Optional.absent();
    } else {//from   w  w w. j  av a2  s  .co m
        JsonElement app = HttpValueFunctions.jsonContents().apply(response);
        if (app.isJsonNull()) {
            return Optional.absent();
        } else {
            LOG.debug("Application JSON: {}", response.getContentAsString());
            return Optional.of(app);
        }
    }
}

From source file:brooklyn.entity.mesos.task.marathon.MarathonTaskImpl.java

License:Apache License

@Override
public MarathonTaskLocation createLocation(Map<String, ?> flags) {
    Entity entity = getRunningEntity();
    MesosSlave slave = getMesosCluster().getMesosSlave(getHostname());
    SubnetTier subnet = slave.getSubnetTier();
    Boolean sdn = config().get(MesosCluster.SDN_ENABLE);

    // Configure the entity subnet
    LOG.info("Configuring entity {} via subnet {}", entity, subnet);
    entity.config().set(SubnetTier.PORT_FORWARDING_MANAGER, subnet.getPortForwardManager());
    entity.config().set(SubnetTier.PORT_FORWARDER, subnet.getPortForwarder());
    entity.config().set(SubnetTier.SUBNET_CIDR, Cidr.UNIVERSAL);
    DockerUtils.configureEnrichers(subnet, entity);

    // Lookup mapped ports
    List<Map.Entry<Integer, Integer>> portBindings = (List) flags.get("portBindings");
    Map<Integer, String> tcpMappings = MutableMap.of();
    Optional<JsonElement> application = getApplicationJson();
    if (application.isPresent()) {
        JsonArray tasks = application.get().getAsJsonObject().get("app").getAsJsonObject().get("tasks")
                .getAsJsonArray();/*ww  w  .  j a v a 2 s .  co m*/
        for (JsonElement each : tasks) {
            JsonElement ports = each.getAsJsonObject().get("ports");
            if (ports != null && !ports.isJsonNull()) {
                JsonArray array = ports.getAsJsonArray();
                if (array.size() > 0) {
                    for (int i = 0; i < array.size(); i++) {
                        int hostPort = array.get(i).getAsInt();
                        int containerPort = portBindings.get(i).getKey();
                        String address = sdn ? sensors().get(Attributes.SUBNET_ADDRESS) : getId();
                        String target = address + ":" + containerPort;
                        tcpMappings.put(hostPort, target);
                        if (containerPort == 22) { // XXX should be a better way?
                            sensors().set(DockerAttributes.DOCKER_MAPPED_SSH_PORT,
                                    HostAndPort.fromParts(getHostname(), hostPort).toString());
                        }
                    }
                }
            }
        }
    } else {
        throw new IllegalStateException(
                "Cannot retrieve application details for " + sensors().get(APPLICATION_ID));
    }

    // Create our wrapper location around the task
    Boolean useSsh = config().get(DockerAttributes.DOCKER_USE_SSH);
    LocationSpec<MarathonTaskLocation> spec = LocationSpec.create(MarathonTaskLocation.class)
            .parent(getMarathonFramework().getDynamicLocation()).configure(flags)
            .configure(DynamicLocation.OWNER, this).configure("entity", getRunningEntity())
            .configure(CloudLocationConfig.WAIT_FOR_SSHABLE, "false")
            .configure(SshMachineLocation.DETECT_MACHINE_DETAILS, useSsh)
            .configure(SshMachineLocation.TCP_PORT_MAPPINGS, tcpMappings).displayName(getShortName());
    if (useSsh) {
        spec.configure(SshMachineLocation.SSH_HOST, getHostname())
                .configure(SshMachineLocation.SSH_PORT, getSshPort()).configure("address", getAddress())
                .configure(LocationConfigKeys.USER, "root") // TODO from slave
                .configure(LocationConfigKeys.PASSWORD, "p4ssw0rd").configure(SshTool.PROP_PASSWORD, "p4ssw0rd")
                .configure(SshTool.PROP_HOST, getHostname()).configure(SshTool.PROP_PORT, getSshPort())
                .configure(LocationConfigKeys.PRIVATE_KEY_DATA, (String) null) // TODO used to generate authorized_keys
                .configure(LocationConfigKeys.PRIVATE_KEY_FILE, (String) null);
    }
    MarathonTaskLocation location = getManagementContext().getLocationManager().createLocation(spec);
    sensors().set(DYNAMIC_LOCATION, location);
    sensors().set(LOCATION_NAME, location.getId());

    // Record port mappings
    LOG.debug("Recording port mappings for {} at {}: {}", new Object[] { entity, location, tcpMappings });
    for (Integer hostPort : tcpMappings.keySet()) {
        HostAndPort target = HostAndPort.fromString(tcpMappings.get(hostPort));
        subnet.getPortForwarder().openPortForwarding(location, target.getPort(), Optional.of(hostPort),
                Protocol.TCP, Cidr.UNIVERSAL);
        subnet.getPortForwarder().openFirewallPort(entity, hostPort, Protocol.TCP, Cidr.UNIVERSAL);
        LOG.debug("Forwarded port: {} => {}", hostPort, target.getPort());
    }

    LOG.info("New task location {} created", location);
    if (useSsh) {
        DockerUtils.addExtraPublicKeys(entity, location);
    }
    return location;
}

From source file:brooklyn.event.feed.http.JsonFunctions.java

License:Apache License

@SuppressWarnings("unchecked")
public static <T> Function<JsonElement, T> cast(final Class<T> expected) {
    return new Function<JsonElement, T>() {
        @Override// w ww.j  a  v  a  2s  .  co  m
        public T apply(JsonElement input) {
            if (input == null) {
                return (T) null;
            } else if (input.isJsonNull()) {
                return (T) null;
            } else if (expected == boolean.class || expected == Boolean.class) {
                return (T) (Boolean) input.getAsBoolean();
            } else if (expected == char.class || expected == Character.class) {
                return (T) (Character) input.getAsCharacter();
            } else if (expected == byte.class || expected == Byte.class) {
                return (T) (Byte) input.getAsByte();
            } else if (expected == short.class || expected == Short.class) {
                return (T) (Short) input.getAsShort();
            } else if (expected == int.class || expected == Integer.class) {
                return (T) (Integer) input.getAsInt();
            } else if (expected == long.class || expected == Long.class) {
                return (T) (Long) input.getAsLong();
            } else if (expected == float.class || expected == Float.class) {
                return (T) (Float) input.getAsFloat();
            } else if (expected == double.class || expected == Double.class) {
                return (T) (Double) input.getAsDouble();
            } else if (expected == BigDecimal.class) {
                return (T) input.getAsBigDecimal();
            } else if (expected == BigInteger.class) {
                return (T) input.getAsBigInteger();
            } else if (Number.class.isAssignableFrom(expected)) {
                // TODO Will result in a class-cast if it's an unexpected sub-type of Number not handled above
                return (T) input.getAsNumber();
            } else if (expected == String.class) {
                return (T) input.getAsString();
            } else if (expected.isArray()) {
                JsonArray array = input.getAsJsonArray();
                Class<?> componentType = expected.getComponentType();
                if (JsonElement.class.isAssignableFrom(componentType)) {
                    JsonElement[] result = new JsonElement[array.size()];
                    for (int i = 0; i < array.size(); i++) {
                        result[i] = array.get(i);
                    }
                    return (T) result;
                } else {
                    Object[] result = (Object[]) Array.newInstance(componentType, array.size());
                    for (int i = 0; i < array.size(); i++) {
                        result[i] = cast(componentType).apply(array.get(i));
                    }
                    return (T) result;
                }
            } else {
                throw new IllegalArgumentException("Cannot cast json element to type " + expected);
            }
        }
    };
}

From source file:ccm.pay2spawn.util.JsonNBTHelper.java

License:Open Source License

public static JsonElement fixNulls(JsonElement element) {
    if (element.isJsonNull())
        return new JsonPrimitive("");
    if (element.isJsonObject())
        return fixNulls(element.getAsJsonObject());
    if (element.isJsonArray())
        return fixNulls(element.getAsJsonArray());
    if (element.isJsonPrimitive())
        return fixNulls(element.getAsJsonPrimitive());
    return null;/*from   w w w .  j a va  2  s .  c  o  m*/
}

From source file:cf.adriantodt.David.modules.db.GuildModule.java

License:LGPL

private static Data getOrGen(Optional<Guild> guildOptional, Optional<String> optionalId,
        Optional<String> optionalName) {
    RuntimeException ex = new IllegalStateException("Id and/or Name can't be Optional if Guild isn't returned");
    String id = optionalId.orElseGet(() -> guildOptional.orElseThrow(() -> ex).getId());
    String name = optionalName.orElseGet(() -> guildOptional.orElseThrow(() -> ex).getName());

    Data data;//from   w w  w .ja  va 2 s  .c  om

    JsonElement object = DBModule.onDB(r -> r.db("bot").table("guilds").get(id)).run().simpleExpected();
    if (object.isJsonNull()) {
        data = new Data();

        data.id = id;
        data.name = toGuildName(name);

        MapObject m = new MapObject().with("id", data.id).with("name", data.name)
                .with("cmdPrefixes", data.cmdPrefixes).with("lang", data.lang).with("userPerms", data.userPerms)
                .with("flags", data.flags);

        DBModule.onDB(r -> r.table("guilds").insert(m)).noReply();
    } else {
        data = unpack(object);
    }
    Data finalData = data;
    guildOptional.ifPresent(guild -> guildMap.put(guild, finalData));
    UserCommandsModule.loadAllFrom(data);
    return data;
}

From source file:ch.cern.db.flume.sink.kite.parser.JSONtoAvroParser.java

License:GNU General Public License

private Object getElementAsType(Schema schema, JsonElement element) {
    if (element == null || element.isJsonNull())
        return null;

    switch (schema.getType()) {
    case BOOLEAN:
        return element.getAsBoolean();
    case DOUBLE://ww w. j  ava2 s  .c  o  m
        return element.getAsDouble();
    case FLOAT:
        return element.getAsFloat();
    case INT:
        return element.getAsInt();
    case LONG:
        return element.getAsLong();
    case NULL:
        return null;
    case UNION:
        return getElementAsType(schema.getTypes().get(0), element);
    //      case FIXED:
    //      case ARRAY:
    //      case BYTES:
    //      case ENUM:
    //      case MAP:
    //      case RECORD:
    //      case STRING:
    default:
        return element.getAsString();
    }
}

From source file:club.jmint.mifty.service.MiftyService.java

License:Apache License

public String callProxy(String method, String params, boolean isEncrypt) throws TException {
    //parse parameters and verify signature
    CrossLog.logger.debug("callProxy: " + method + "(in: " + params + ")");
    JsonObject ip;/*from  ww w  .j  a  v a2  s . c om*/
    try {
        ip = parseInputParams(params, isEncrypt);
    } catch (CrossException ce) {
        return buildOutputByCrossException(ce);
    }

    //extract all parameters
    HashMap<String, String> inputMap = new HashMap<String, String>();
    Iterator<Entry<String, JsonElement>> it = ip.entrySet().iterator();
    Entry<String, JsonElement> en = null;
    String key;
    JsonElement je;
    while (it.hasNext()) {
        en = it.next();
        key = en.getKey();
        je = en.getValue();
        if (je.isJsonArray()) {
            inputMap.put(key, je.getAsJsonArray().toString());
            //System.out.println(je.getAsJsonArray().toString());
        } else if (je.isJsonNull()) {
            inputMap.put(key, je.getAsJsonNull().toString());
            //System.out.println(je.getAsJsonNull().toString());
        } else if (je.isJsonObject()) {
            inputMap.put(key, je.getAsJsonObject().toString());
            //System.out.println(je.getAsJsonObject().toString());
        } else if (je.isJsonPrimitive()) {
            inputMap.put(key, je.getAsJsonPrimitive().getAsString());
            //System.out.println(je.getAsJsonPrimitive().toString());
        } else {
            //unkown type;
        }
    }

    //execute specific method
    Method[] ma = this.getClass().getMethods();
    int idx = 0;
    for (int i = 0; i < ma.length; i++) {
        if (ma[i].getName().equals(method)) {
            idx = i;
            break;
        }
    }
    HashMap<String, String> outputMap = null;
    try {
        Method m = this.getClass().getDeclaredMethod(method, ma[idx].getParameterTypes());
        outputMap = (HashMap<String, String>) m.invoke(this, inputMap);
        CrossLog.logger.debug("callProxy: " + method + "() executed.");
    } catch (NoSuchMethodException nsm) {
        CrossLog.logger.error("callProxy: " + method + "() not found.");
        CrossLog.printStackTrace(nsm);
        return buildOutputError(ErrorCode.CROSSING_ERR_INTERFACE_NOT_FOUND.getCode(),
                ErrorCode.CROSSING_ERR_INTERFACE_NOT_FOUND.getInfo());
    } catch (Exception e) {
        CrossLog.logger.error("callProxy: " + method + "() executed with exception.");
        CrossLog.printStackTrace(e);
        if (e instanceof CrossException) {
            return buildOutputByCrossException((CrossException) e);
        } else {
            return buildOutputError(ErrorCode.COMMON_ERR_UNKOWN.getCode(),
                    ErrorCode.COMMON_ERR_UNKOWN.getInfo());
        }
    }
    //if got error then return immediately
    String ec = outputMap.get("errorCode");
    String ecInfo = outputMap.get("errorInfo");
    if ((ec != null) && (!ec.isEmpty())) {
        return buildOutputError(Integer.parseInt(ec), ecInfo);
    }

    //build response parameters
    JsonObject op = new JsonObject();
    Iterator<Entry<String, String>> ito = outputMap.entrySet().iterator();
    Entry<String, String> eno = null;
    JsonParser jpo = new JsonParser();
    JsonElement jeo = null;
    while (ito.hasNext()) {
        eno = ito.next();
        try {
            jeo = jpo.parse(eno.getValue());
        } catch (JsonSyntaxException e) {
            //            MyLog.logger.error("callProxy: Malformed output parameters["+eno.getKey()+"].");
            //            return buildOutputError(ErrorCode.COMMON_ERR_PARAM_MALFORMED.getCode(), 
            //                  ErrorCode.COMMON_ERR_PARAM_MALFORMED.getInfo());
            //we do assume that it should be a common string
            jeo = new JsonPrimitive(eno.getValue());
        }
        op.add(eno.getKey(), jeo);
    }

    String output = null;
    try {
        output = buildOutputParams(op, isEncrypt);
    } catch (CrossException ce) {
        return buildOutputByCrossException(ce);
    }
    CrossLog.logger.debug("callProxy: " + method + "(out: " + output + ")");
    return output;
}