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:io.jawg.osmcontributor.rest.mappers.JodaTimeDateTimeDeserializer.java

License:Open Source License

@Override
public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    DateTime dateTime = null;//  w  ww . j a v a2 s  . c o  m
    if (!json.isJsonNull()) {
        try {
            dateTime = DateTime.parse(json.getAsString(), ISODateTimeFormat.dateTime());
        } catch (Exception e) {
            Timber.e(e, "Joda-Time DateTime Transform failed.");
            throw new JsonParseException(e);
        }
    }
    return dateTime;
}

From source file:io.openvidu.server.core.SessionEventsHandler.java

License:Apache License

public void onSendMessage(Participant participant, JsonObject message, Set<Participant> participants,
        Integer transactionId, OpenViduException error) {
    if (error != null) {
        rpcNotificationService.sendErrorResponse(participant.getParticipantPrivateId(), transactionId, null,
                error);//from w  w w .  j ava  2s.c o m
        return;
    }

    JsonObject params = new JsonObject();
    params.addProperty(ProtocolElements.PARTICIPANTSENDMESSAGE_DATA_PARAM, message.get("data").getAsString());
    params.addProperty(ProtocolElements.PARTICIPANTSENDMESSAGE_FROM_PARAM,
            participant.getParticipantPublicId());
    params.addProperty(ProtocolElements.PARTICIPANTSENDMESSAGE_TYPE_PARAM, message.get("type").getAsString());

    Set<String> toSet = new HashSet<String>();

    if (message.has("to")) {
        JsonArray toJson = message.get("to").getAsJsonArray();
        for (int i = 0; i < toJson.size(); i++) {
            JsonElement el = toJson.get(i);
            if (el.isJsonNull()) {
                throw new OpenViduException(Code.SIGNAL_TO_INVALID_ERROR_CODE,
                        "Signal \"to\" field invalid format: null");
            }
            toSet.add(el.getAsString());
        }
    }

    if (toSet.isEmpty()) {
        for (Participant p : participants) {
            rpcNotificationService.sendNotification(p.getParticipantPrivateId(),
                    ProtocolElements.PARTICIPANTSENDMESSAGE_METHOD, params);
        }
    } else {
        Set<String> participantPublicIds = participants.stream().map(Participant::getParticipantPublicId)
                .collect(Collectors.toSet());
        for (String to : toSet) {
            if (participantPublicIds.contains(to)) {
                Optional<Participant> p = participants.stream()
                        .filter(x -> to.equals(x.getParticipantPublicId())).findFirst();
                rpcNotificationService.sendNotification(p.get().getParticipantPrivateId(),
                        ProtocolElements.PARTICIPANTSENDMESSAGE_METHOD, params);
            } else {
                throw new OpenViduException(Code.SIGNAL_TO_INVALID_ERROR_CODE,
                        "Signal \"to\" field invalid format: Connection [" + to + "] does not exist");
            }
        }
    }

    rpcNotificationService.sendResponse(participant.getParticipantPrivateId(), transactionId, new JsonObject());
}

From source file:io.robusta.rra.representation.implementation.GsonRepresentation.java

License:Apache License

/**
 * check if document is not null/*w  ww.j  a va  2 s  . com*/
 * 
 * @param key
 * @return
 */
protected boolean hasNotEmpty(String key) {
    throwIfNotObject();
    JsonObject object = this.document.getAsJsonObject();
    JsonElement elt = object.get(key);
    if (elt == null || elt.isJsonNull() || (isString(elt) && elt.getAsString().isEmpty())) {
        // elt is null or empty string
        return false;
    } else {
        return true;
    }

}

From source file:io.thekraken.json2hive.HiveUtils.java

License:Apache License

public static String struct(String value, int nasted) {

    if (value == null)
        return " ";
    if (value.isEmpty())
        return " ";
    if (nasted < 0)
        nasted = 0;//from  w w w .  j a  v  a2  s  .  c o m
    JsonParser parser = new JsonParser();
    JsonElement jsonElement = parser.parse(value);
    JsonObject jsonObject = jsonElement.getAsJsonObject();
    String struct = "";
    COMMA = 0;
    for (Entry<String, JsonElement> entry : jsonObject.entrySet()) {
        String key = entry.getKey();
        JsonElement val = entry.getValue();
        // 3 Possibilities
        // 1. structures
        // 2. array
        // 3. primitive

        if (val.isJsonObject() && nasted >= 1) {
            if (COMMA > 0) {
                struct += ",";
            }
            COMMA = 0;
            struct += fieldWrapper(key) + ":" + STRUCT + "<" + struct(val.toString(), 1) + ">";
        }
        // Array
        else if (val.isJsonArray()) {
            if (COMMA > 0) {
                struct += ",";
            }
            COMMA++;

            struct += fieldWrapper(key) + ":" + ARRAY + "<" + array(val.toString()) + ">";
        } else { // normal field
            if (COMMA > 0) {
                struct += ",";
            }
            COMMA++;

            if (val.isJsonNull()) {
                struct += fieldWrapper(key) + ":" + STRING;
            } else {
                struct += fieldWrapper(key) + ":" + findType(val.toString());
            }
        }
    }
    return struct;
}

From source file:io.thekraken.json2hive.Json.java

License:Apache License

private static HiveTable createHiveTable(String hiveTableName, String jsonObject) {
    HiveTable hive = new HiveTable(hiveTableName);

    JsonParser parser = new JsonParser();
    JsonElement jsonElement = parser.parse(jsonObject);
    JsonObject jsonObj = jsonElement.getAsJsonObject();

    for (Entry<String, JsonElement> entry : jsonObj.entrySet()) {
        String key = entry.getKey();
        JsonElement value = entry.getValue();

        /** Structure */
        if (value.isJsonObject()) {
            hive.addStructure(key, value.toString());
        }/*from   w  w  w . j  av  a2s . c o m*/
        /** Array */
        else if (value.isJsonArray()) {
            hive.addArray(key, value.toString());
        } else {
            /** primitive */
            if (value.isJsonNull()) {
                hive.AddUnknow(value.toString());
            } else {
                hive.addPrimitive(key, value.toString());
            }
        }
    }
    hive.close();
    return hive;
}

From source file:it.cnr.istc.ratio.gui.MainJFrame.java

License:Open Source License

/**
 * Creates new form MainJFrame/*from   w  w w.  j  ava 2  s  .  c o  m*/
 */
public MainJFrame(String first) {
    initComponents();

    setIconImages(Arrays.asList(new ImageIcon(getClass().getResource("resources/ratio16.png")).getImage(),
            new ImageIcon(getClass().getResource("resources/ratio32.png")).getImage()));

    path = FileSystems.getDefault().getPath(first);

    load_state();
    load_graph();

    new Thread(() -> {
        WatchService watcher;
        try {
            watcher = FileSystems.getDefault().newWatchService();
        } catch (IOException ex) {
            return;
        }
        try {
            path.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        } catch (IOException ex) {
            Logger.getLogger(MainJFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        for (;;) {
            try {
                boolean overflow = false;
                WatchKey key = watcher.take();
                for (WatchEvent<?> event : key.pollEvents()) {
                    WatchEvent.Kind<?> kind = event.kind();
                    if (kind == OVERFLOW) {
                        overflow = true;
                        continue;
                    }
                    @SuppressWarnings("unchecked")
                    WatchEvent<Path> ev = (WatchEvent<Path>) event;
                    Path filename = ev.context();
                    if (kind == ENTRY_DELETE) {
                        switch (filename.getFileName().toString()) {
                        case "state.json":
                            clear_state();
                            break;
                        case "graph.json":
                            clear_graph();
                            break;
                        }
                        continue;
                    }
                    switch (filename.getFileName().toString()) {
                    case "state.json":
                        try {
                            JsonElement s_element = new JsonParser()
                                    .parse(new FileReader(path.resolve(filename).toFile()));
                            if (s_element.isJsonNull()) {
                                clear_state();
                            } else {
                                update_state(s_element.getAsJsonObject());
                            }
                        } catch (Exception ex) {
                            clear_state();
                        }
                        break;
                    case "graph.json":
                        try {
                            JsonElement g_element = new JsonParser()
                                    .parse(new FileReader(path.resolve(filename).toFile()));
                            if (g_element.isJsonNull()) {
                                clear_graph();
                            } else {
                                update_graph(g_element.getAsJsonObject());
                            }
                        } catch (Exception e) {
                            clear_graph();
                        }
                        break;
                    }
                }

                if (!key.reset()) {
                    break;
                }

                if (overflow) {
                    clear_state();
                    load_state();
                    clear_graph();
                    load_graph();
                }
            } catch (InterruptedException ex) {
                Logger.getLogger(MainJFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }).start();

    stateJTree.addTreeWillExpandListener(new TreeWillExpandListener() {
        @Override
        public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException {
            stateTreeModel.createChilds((DefaultMutableTreeNode) event.getPath().getLastPathComponent());
        }

        @Override
        public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException {
        }
    });

    ToolTipManager.sharedInstance().registerComponent(stateJTree);
}

From source file:it.cnr.istc.ratio.gui.MainJFrame.java

License:Open Source License

private void load_state() {
    File file = path.resolve("state.json").toFile();
    if (file.exists()) {
        try {//w ww . ja v a2  s. com
            FileReader reader = new FileReader(file);
            JsonElement element = new JsonParser().parse(reader);
            reader.close();
            if (!element.isJsonNull()) {
                update_state(element.getAsJsonObject());
            }
        } catch (Exception ex) {
            clear_state();
        }
    }
}

From source file:it.cnr.istc.ratio.gui.MainJFrame.java

License:Open Source License

private void load_graph() {
    File file = path.resolve("graph.json").toFile();
    if (file.exists()) {
        try {/*from w  w w .  j  a v  a 2 s. co m*/
            FileReader reader = new FileReader(file);
            JsonElement element = new JsonParser().parse(reader);
            reader.close();
            if (!element.isJsonNull()) {
                update_graph(element.getAsJsonObject());
            }
        } catch (Exception ex) {
            clear_graph();
        }
    }
}

From source file:it.noovle.dataflow.TwitterProcessor.java

License:Open Source License

/**
 * Does some processing on the JSON message describing the tweet
 *///from   w  ww .  j  a  v  a2  s  .  c o  m
private static JsonElement cleanup(JsonElement el) {

    SimpleDateFormat dateReader = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");
    SimpleDateFormat dateWriter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    if (el.isJsonNull()) {
        return el;
    } else if (el.isJsonObject()) {
        Set<String> toBeRemoved = Sets.newHashSet();
        JsonObject objEl = el.getAsJsonObject();
        for (Entry<String, JsonElement> child : objEl.entrySet()) {
            if (child.getValue().isJsonNull()) {
                toBeRemoved.add(child.getKey());
            } else if (child.getKey().equalsIgnoreCase("created_at")) {
                // Parse dates like 'Tue Oct 18 07:01:50 +0000 2016' and write them out as "2016-10-18 07:01:50"
                try {
                    Date date = dateReader.parse(child.getValue().getAsString());
                    objEl.addProperty(child.getKey(), dateWriter.format(date));
                } catch (ParseException e) {
                    LOG.warn("Error while parsing date", e);
                }
            } else if (child.getKey().equalsIgnoreCase("coordinates") && child.getValue().isJsonArray()) {
                objEl.add(child.getKey(), flatten(child.getValue()));
            } else if (child.getKey().equalsIgnoreCase("attributes")) {
                objEl.addProperty(child.getKey(), child.getValue().toString());
            } else if (child.getValue().isJsonObject()) {
                objEl.add(child.getKey(), cleanup(child.getValue()));
            } else if (child.getValue().isJsonArray()) {
                JsonArray newArray = new JsonArray();
                for (JsonElement arrayEl : child.getValue().getAsJsonArray()) {
                    newArray.add(cleanup(arrayEl));
                }
                objEl.add(child.getKey(), newArray);
            }
        }

        // Remove ignored fields
        // TODO: modify schema to include also these fields
        for (String key : IGNORED_FIELDS) {
            if (objEl.has(key)) {
                objEl.remove(key);
            }
        }
        // Remove fields marked for removal
        // TODO: modify schema to include also these fields
        for (String key : toBeRemoved) {
            objEl.remove(key);
        }

        return objEl;
    } else {
        return el;
    }

}

From source file:jmm.api.tmdb.TMDBMovieWrapper.java

License:Open Source License

/**
 * Get the basic movie information for a specific movie id. <br/>
 * <b>Bold</b> parameters are <b>required</b>.
 * //from  ww  w  . jav a2 s. c  om
 * @param id <b>the movie id</b>
 * @param language ISO 639-1 code.
 * @param append_to_response Comma separated, any movie method
 * @return the movie wth the given id <br/>null, if no movie was found with the given id
 */
public TMDBVideoFile findMovie(String id, String language, String append_to_response) {
    paramsMap.clear();
    //requiered parameters
    if (id == null) {
        throw new NullPointerException("Param: " + "id" + "must not be null");
    }
    //optional parameters
    if (language != null) {
        paramsMap.put(PARAM_LANGUAGE, language);
    }
    if (append_to_response != null) {
        paramsMap.put(PARAM_APPEND, append_to_response);
    }

    String url = buildUrl(API_MOVIE + "/" + id);
    JsonElement element = callAPI(url);
    //handle response
    TMDBVideoFile searchResult = null;
    if (!element.isJsonNull()) {
        String title = element.getAsJsonObject().get("title").getAsString();
        searchResult = new TMDBVideoFile(title);
        JsonElement value;
        value = element.getAsJsonObject().get("adult");
        if (!value.isJsonNull()) {
            searchResult.setAdult(value.getAsBoolean());
            if (searchResult.isAdult()) {
                searchResult.setFsk(VideoFile.FSK.FSK_18);
            }
        }
        value = element.getAsJsonObject().get("backdrop_path");
        if (!value.isJsonNull()) {
            searchResult.setBackdropPath(API_BASE_IMAGEURL + Backdrop_Sizes.w780 + value.getAsString());
        }
        //genres
        value = element.getAsJsonObject().get("genres");
        if (!value.isJsonNull()) {
            JsonArray genres = value.getAsJsonArray();
            if (genres.isJsonArray()) {
                Iterator<JsonElement> genresIterator = genres.iterator();
                while (genresIterator.hasNext()) {
                    JsonElement genreElement = genresIterator.next();
                    value = genreElement.getAsJsonObject().get("id");
                    if (!value.isJsonNull()) {
                        int genreID = value.getAsInt();
                        Genre genre = Genre.getGenreByTMDBID(genreID);
                        if (genre != null) {
                            searchResult.addGenreKey(genre.getGenreKey());
                        } else {
                            value = genreElement.getAsJsonObject().get("name");
                            String exceptionString;
                            if (!value.isJsonNull()) {
                                exceptionString = "Missing genre in resource bundle: " + value.getAsString()
                                        + " " + genreID;
                            } else {
                                exceptionString = "Missing genre in resource bundle: " + genreID;
                            }
                            LOG.warn(exceptionString);
                        }
                    }
                    //                            value = genreElement.getAsJsonObject().get("name");
                    //                            if(!value.isJsonNull()){                    
                    //                                String localizedGenre = value.getAsString();
                    //                                String genreKey = LocaleManager.getInstance().determineGenreKeyByLocale(localizedGenre);
                    //                                if(genreKey == null){
                    //                                    MyExceptionHandler.uncaughtExceptionLogger.warning("Missing genre in resource bundle: " + localizedGenre);
                    //                                }else{
                    //                                    searchResult.addGenre(genreKey);
                    //                                }
                    //                            }
                }
            }
        }
        value = element.getAsJsonObject().get("id");
        if (!value.isJsonNull()) {
            searchResult.setTmdbID(value.getAsString());
        }
        value = element.getAsJsonObject().get("imdb_id");
        if (!value.isJsonNull()) {
            searchResult.setImdbID(value.getAsString());
        }
        value = element.getAsJsonObject().get("original_title");
        if (!value.isJsonNull()) {
            searchResult.setOriginalTitle(value.getAsString());
        }
        value = element.getAsJsonObject().get("overview");
        if (!value.isJsonNull()) {
            searchResult.setDescription(value.getAsString());
        }
        value = element.getAsJsonObject().get("poster_path");
        if (!value.isJsonNull()) {
            searchResult.setImagePath(API_BASE_IMAGEURL + Poster_Sizes.w342 + value.getAsString());
        }
        //Publisher
        value = element.getAsJsonObject().get("production_companies");
        if (!value.isJsonNull()) {
            JsonArray publishers = value.getAsJsonArray();
            if (publishers.isJsonArray()) {
                Iterator<JsonElement> publishersIterator = publishers.iterator();
                while (publishersIterator.hasNext()) {
                    //Set only the first publisher
                    JsonElement publisherElement = publishersIterator.next();
                    value = publisherElement.getAsJsonObject().get("name");
                    if (!value.isJsonNull()) {
                        String publisher = value.getAsString();
                        searchResult.setPublisher(publisher);
                        break;
                    }
                }
            }
        }
        value = element.getAsJsonObject().get("runtime");
        if (!value.isJsonNull()) {
            searchResult.setPlaytime(value.getAsInt());
        }
        value = element.getAsJsonObject().get("vote_average");
        if (!value.isJsonNull()) {
            searchResult.setTmdbRating(value.getAsDouble());
            searchResult.setOnlineRating(value.getAsDouble());
        }
        //release date
        value = element.getAsJsonObject().get("release_date");
        if (!value.isJsonNull()) {
            String rlsDateString = value.getAsString();
            try {
                Date date = new SimpleDateFormat("yyyy-mm-dd").parse(rlsDateString);
                searchResult.setReleaseDate(date);
                String releaseYear = new SimpleDateFormat("yyyy").format(date);
                if (!releaseYear.isEmpty()) {
                    searchResult.setReleaseYear(Integer.valueOf(releaseYear));
                }
            } catch (ParseException | NumberFormatException ex) {
                LOG.warn("Release Year " + rlsDateString + "cannot be parsed into a valid format for title: "
                        + title + ".", ex);
                searchResult.setReleaseYear(0);
            }
        }

        //{"adult":false,"backdrop_path":"/eZxahf9ATsv3oQPtvZPqSZkAO7V.jpg","belongs_to_collection":{"id":1241,"name":"Harry Potter Collection",
        //"poster_path":"/fuWOg0iLKPRGTlg7lq4tWDBt5tu.jpg","backdrop_path":"/tpDcuXZGqEoU6CxuJ7e4S2NTIoS.jpg"},"budget":250000000,
        //"genres":[{"id":12,"name":"Abenteuer"},{"id":18,"name":"Drama"},{"id":14,"name":"Fantasy"},{"id":10751,"name":"Familie"}],
        //"homepage":"http://harrypotter.warnerbros.de/hp7a/","id":12444,"imdb_id":"tt0926084","original_title":"Harry Potter and the Deathly Hallows: Part 1",
        //"overview":"Harry sieht sich einer vollkommen vernderten Welt gegenber. Die Todesesser haben das Zauberministerium unter ihre Kontrolle gebracht und es tobt ein offener Kampf zwischen den Mchten des Guten und Bsen. Harry hat sich mit Hermine (Emma Watson) und Ron (Rupert Grint) auf die Suche nach den Horkuxen, magischen Objekten, die die Unsterblichkeit von Lord Voldemort (Ralph Fiennes) garantieren und zerstrt werden mssen. Der dunkle Lord hat seinerseits ein Kopfgeld auf Harry ausgesetzt, dener will sich das Vergngen den Jungen der lebte mit den eigenen Hnden zu tten, nicht nehmen lassen. Unterdessen stt Harry auf die Legende von den Heiligtmern des Todes, die ihm im Kampf gegen seinen Erzfeind das Leben retten knnte. Und so strebt alles unaufhaltsam der finalen Konfrontation zwischen den beiden Magiern entegegen, auf die Harry sich seit Beginn seiner Schullaufbahn vorbereitet hat.",
        //"popularity":305437.691,"poster_path":"/3ssNt5cCFYGne7OrBFkFFUVq8Cx.jpg","production_companies":[{"name":"Warner Bros. Pictures","id":174}],
        //"production_countries":[{"iso_3166_1":"US","name":"United States of America"},{"iso_3166_1":"GB","name":"United Kingdom"}],
        //"release_date":"2010-11-19","revenue":954305868,"runtime":146,
        //"spoken_languages":[{"iso_639_1":"en","name":"English"},{"iso_639_1":"fr","name":"Franais"},{"iso_639_1":"ja","name":"???"}],
        //"status":"Released","tagline":"","title":"Harry Potter und die Heiligtmer des Todes - Teil 1","vote_average":8.3,"vote_count":74}
        if (append_to_response != null && append_to_response.equalsIgnoreCase("casts")) {
            addActorsAndDirector(element, searchResult);
        }
    }
    return searchResult;
}