Example usage for com.google.gson JsonElement toString

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

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Returns a String representation of this element.

Usage

From source file:com.weibo.api.motan.protocol.grpc.http.NettyHttpRequestHandler.java

License:Apache License

protected Object[] parseArguments(String params, MethodInfo methodInfo) {
    if (params == null) {
        return null;
    }/*  www .  j a v  a 2 s.c o  m*/

    Class<?>[] paramsType = methodInfo.getMethod().getParameterTypes();
    JsonParser parser = new JsonParser();
    JsonArray jsonArray = (JsonArray) parser.parse(params);
    try {
        Object[] result = new Object[jsonArray.size()];
        for (int i = 0; i < jsonArray.size(); i++) {
            JsonElement element = jsonArray.get(i);
            Message pbMessage = null;
            try {
                Method method = paramsType[i].getMethod("getDefaultInstance", null);
                if (method != null) {
                    pbMessage = (Message) method.invoke(null, null);
                }
            } catch (Exception e) {
                LoggerUtil.warn("parse pb message fail. param type:" + paramsType[i]);
            }

            if (pbMessage != null) {
                result[i] = parsePB(element.toString(), pbMessage);
            } else {
                // TODO not pb
            }

        }
        return result;
    } catch (Exception e) {
        throw new MotanServiceException("parse arguments fail!" + e.getMessage());
    }
}

From source file:com.wialon.core.Session.java

License:Apache License

/**
 * Initialize Wialon session/*from  w  w  w . j a va 2s  . co  m*/
 * @param baseUrl
 */
public boolean initSession(String baseUrl) {
    this.baseUrl = baseUrl;
    this.renderer = new Renderer();
    this.messagesLoader = new MessagesLoader();
    if (httpClient == null)
        httpClient = RemoteHttpClient.getInstance();
    if (jsonParser == null)
        jsonParser = new JsonParser();
    if (gson == null)
        gson = new GsonBuilder().registerTypeAdapter(String.class, new JsonDeserializer<String>() {
            @Override
            public String deserialize(JsonElement jsonElement, Type type,
                    JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
                return jsonElement.isJsonPrimitive() ? jsonElement.getAsString() : jsonElement.toString();
            }
        }).create();
    return initialized = true;
}

From source file:com.wialon.item.UnitGroup.java

License:Apache License

@Override
public boolean updateItemData(String key, JsonElement data) {
    if (super.updateItemData(key, data))
        return true;
    else {/*  w  ww . j a  va  2 s .c  o m*/
        if (key.equals("u") && data.getAsJsonArray() != null) {
            setUnits(Session.getInstance().getGson().fromJson(data.toString(), Long[].class));
        } else
            return false;
        return true;
    }
}

From source file:com.wialon.remote.RemoteHttpClient.java

License:Apache License

/**
 * Handle batch call completed event//from   w  ww .  j av  a2  s.  c  o  m
 * @param callback       callback to call with result code
 * @param batchCallbacks collection of callbacks for each batched call
 * @param results        resulting data
 */
private void onBatchCallCompleted(ResponseHandler callback, List<ResponseHandler> batchCallbacks,
        String results) {
    JsonArray resultsArray = Session.getInstance().getJsonParser().parse(results).getAsJsonArray();
    if (results == null || batchCallbacks == null || resultsArray == null
            || batchCallbacks.size() != resultsArray.size()) {
        int errorCode = 3;
        // error doing request
        // pass result for all callbacks
        if (batchCallbacks != null)
            for (ResponseHandler batchCall : batchCallbacks)
                batchCall.onFailure(errorCode, null);
        callback.onFailure(errorCode, null);
        return;
    }
    // fire callback for each call with its data
    //int lastError=0;
    for (int i = 0; i < resultsArray.size(); i++) {
        JsonElement result = resultsArray.get(i);
        if (result.isJsonObject() && result.getAsJsonObject().has("error")) {
            int error = result.getAsJsonObject().get("error").getAsInt();
            if (error != 0) {
                //lastError=error;
                batchCallbacks.get(i).onFailure(error, null);
            } else
                batchCallbacks.get(i).onSuccess(result.toString());
        } else
            batchCallbacks.get(i).onSuccess(result.toString());
    }
    // finally fire our own callb0ack
    //if (lastError!=0)
    //callback.onFailure(lastError, null);
    //else
    callback.onSuccess(results);
}

From source file:com.xpbytes.gson.hal.HalTypeAdapterFactory.java

License:Apache License

@Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {

    final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
    final TypeAdapter<JsonElement> basicAdapter = gson.getAdapter(JsonElement.class);
    // If we convert to JSON, isn't the deserializer more appropriate...?

    // Is this a HalResource?
    if (!HalReflection.isResource(type.getRawType()))
        return delegate;

    return new TypeAdapter<T>() {
        @Override//from   w  w w.  java 2s.c o  m
        public void write(JsonWriter out, T value) throws IOException {
            delegate.write(out, value);
        }

        @Override
        public T read(JsonReader in) throws IOException {
            JsonElement fullJson = basicAdapter.read(in);
            Logger.getGlobal().log(Level.ALL, fullJson.toString());
            T deserialized = delegate.fromJsonTree(fullJson);

            if (fullJson.isJsonObject()) {
                JsonObject fullJsonObject = fullJson.getAsJsonObject();

                JsonObject linksObject = fullJsonObject.getAsJsonObject(HalConstants.RESERVED_LINKS_ROOT);
                JsonObject embeddedObject = fullJsonObject.getAsJsonObject(HalConstants.RESERVED_EMBEDDED_ROOT);

                List<Field> fieldsList = HalReflection.getHalFields(type.getRawType());
                for (Field field : fieldsList) {
                    if (HalReflection.isLink(field))
                        readLink(field, linksObject, deserialized);
                    else if (HalReflection.isEmbed(field))
                        readEmbed(field, embeddedObject, deserialized);
                }

            }

            return deserialized;
        }

        private <A> void readEmbed(Field field, JsonObject rootObject, A deserialized) {
            HalEmbed embed = field.getAnnotation(HalEmbed.class);
            boolean optional = embed.optional();
            if (rootObject == null && optional)
                return;

            String memberName = HalReflection.getJsonFieldName(embed, field);
            JsonParseException missingException = new JsonParseException(
                    String.format(Locale.US, "Expected embed `%s` in the embedded root `%s` to be present",
                            memberName, HalConstants.RESERVED_EMBEDDED_ROOT));

            if (rootObject == null)
                throw missingException;

            boolean exists = rootObject.has(memberName);
            if (!exists) {
                if (optional)
                    return;
                throw missingException;
            }

            Type innerType = HalReflection.getFieldItemizedType(field);
            //Class outerType = HalReflection.getFieldType( field );
            JsonElement element = rootObject.get(memberName);

            // This gson.fromJson call will actually call into the proper stack to recursively
            // deserialize embeds and set their links where necessary.
            HalReflection.setEmbed(field, gson.fromJson(element, innerType), deserialized);
        }

        private <A> void readLink(Field field, JsonObject rootObject, A deserialized) {

            HalLink link = field.getAnnotation(HalLink.class);
            boolean optional = link.optional();
            if (rootObject == null && optional)
                return;

            String memberName = HalReflection.getJsonFieldName(link, field);
            JsonParseException missingException = new JsonParseException(
                    String.format(Locale.US, "Expected link `%s` in the links root `%s` to be present",
                            memberName, HalConstants.RESERVED_LINKS_ROOT));

            if (rootObject == null)
                throw missingException;

            boolean exists = rootObject.has(memberName);
            if (!exists) {
                if (optional)
                    return;
                throw missingException;
            }

            // If this is not a descendant of a HalLinkObject, we better treat it as one.
            Class<?> innerType = HalReflection.getFieldItemizedType(field);
            if (!innerType.isAssignableFrom(HalLinkObject.class))
                innerType = HalLinkObject.class;

            //Class outerType = HalReflection.getFieldType( field );
            JsonElement element = rootObject.get(memberName);

            // TODO support collections

            /*if ( Collection.class.isAssignableFrom( outerType ) )
            {
            innerType.
            //noinspection unchecked
            Class<Collection> collectionClass = (Class<Collection>)outerType;
            Collection collection = gson.fromJson( element, collectionClass );
            }
                    
            field.getType()
                    
            if ( element.isJsonArray() ) {
            for ( JsonElement element1 : element.getAsJsonArray() )
                HalReflection.setLink( field, , deserialized );
            } else {
             */
            HalReflection.setLink(field, (HalLinkObject) gson.fromJson(element, (Type) innerType),
                    deserialized);
        }

    }.nullSafe();
}

From source file:com.yahoo.yqlplus.example.apis.WeatherSource.java

@Query
public List<Forecast> getForecast(@Key("woeid") String woeid)
        throws InterruptedException, ExecutionException, TimeoutException, UnsupportedEncodingException {
    JsonObject jsonObject = HttpUtil.getJsonResponse(BASE_URL, "q",
            "select * from weather.forecast where u = 'f' and woeid = " + woeid);
    JsonArray jsonArray = (JsonArray) jsonObject.getAsJsonObject("query").getAsJsonObject("results")
            .getAsJsonObject("channel").getAsJsonObject("item").get("forecast");
    Iterator<JsonElement> it = jsonArray.iterator();
    List<Forecast> forecasts = Lists.newArrayList();
    while (it.hasNext()) {
        JsonElement ele = it.next();
        ForecastBase tmp = HttpUtil.getGson().fromJson(ele.toString(), ForecastBase.class);
        forecasts.add(new Forecast(tmp.getCode(), tmp.getDate(), tmp.getDay(), tmp.getHigh(), tmp.getLow(),
                tmp.getText(), woeid, "f"));
    }//from   ww w.  ja  v a  2s .c om
    return forecasts;
}

From source file:com.yahoo.yqlplus.example.apis.WeatherSource.java

@Query
public List<Forecast> getForecast(@Key("woeid") String woeid, @Key("u") String u)
        throws InterruptedException, ExecutionException, TimeoutException, UnsupportedEncodingException {
    JsonObject jsonObject = HttpUtil.getJsonResponse(BASE_URL.replace("{woeid}", woeid).replace("{u}", u));
    JsonArray jsonArray = (JsonArray) jsonObject.getAsJsonObject("query").getAsJsonObject("results")
            .getAsJsonObject("channel").getAsJsonObject("item").get("forecast");
    Iterator<JsonElement> it = jsonArray.iterator();
    List<Forecast> forecasts = Lists.newArrayList();
    while (it.hasNext()) {
        JsonElement ele = it.next();
        ForecastBase tmp = HttpUtil.getGson().fromJson(ele.toString(), ForecastBase.class);
        forecasts.add(new Forecast(tmp.getCode(), tmp.getDate(), tmp.getDay(), tmp.getHigh(), tmp.getLow(),
                tmp.getText(), woeid, u));
    }/*from   w w w . ja v  a 2s . c o m*/
    return forecasts;
}

From source file:controllers.ListData.java

License:Open Source License

private static String addRangeToJson(String jsonString, int startIndex, long totalSize) {
    JsonParser parser = new JsonParser();
    JsonElement element = parser.parse(jsonString);

    if (element.isJsonObject()) {
        JsonObject object = element.getAsJsonObject();
        object.addProperty("startIndex", startIndex);
        object.addProperty("totalSize", totalSize);
    }//from  ww  w  .ja  va  2s  .  co m
    return element.toString();
}

From source file:controllers.Rdio.java

License:Open Source License

@NoBinding
public static ArrayList<Track> searchTrack(User user, String trackName, AuthCredentials backupCredentials) {

    if (user.rdioCreds == null) {
        Logger.info("Attempting to searchTrack without Catalog API credentials rejected.");
        return null;
    }/*from w  ww.  j  ava2 s  .c  o  m*/
    //Logger.info("Rdio.searchTrack:" + trackName);

    ArrayList trackResults = null;
    // try {

    String url = endpoint + "search";
    WSRequest sign;
    try {
        sign = getConnector(user).sign(user.rdioCreds == null ? backupCredentials : user.rdioCreds, WS.url(url),
                "GET");
    } catch (Exception ex) {
        Logger.error(ex.toString());
        ex.printStackTrace();
        return null;
    }

    sign.setParameter("method", "search");
    sign.setParameter("apikey", Play.configuration.getProperty("rdio.secret"));
    sign.setParameter("type", "track");
    sign.setParameter("q", trackName);
    sign.setParameter("limit", 35);
    sign.setParameter("preference", "editorial");

    JsonElement searchResult = sign.get().getJson();

    if (searchResult.toString().contains("{\"code\":\"UnauthorizedError\",\"message\":\"Unauthorized\"}")) {
        Logger.error(searchResult.toString());
        Logger.error(user.firstName + " is unauthorized.. @TODO add logic to setup token");
        if (setupTokens(user, user.rdioCreds.code, 0)) {
            searchResult = sign.get().getJson();
        } else {
            Logger.error("Severe error searching track for user " + user.firstName);
            return null;
        }

    } else if (searchResult.toString().toLowerCase().contains("unauthorized")) {
        Logger.error("Picking up unauthorized with wrong message: " + searchResult.toString());
    }

    trackResults = new ArrayList();
    JsonObject rdioTrack;

    if (searchResult == null) {
        Logger.info("Null search object getting " + trackName);
    }
    JsonObject dataObj = searchResult.getAsJsonObject();
    JsonArray jArray = dataObj.get("data").getAsJsonArray();
    for (JsonElement rdioTrackElement : jArray) {
        rdioTrack = rdioTrackElement.getAsJsonObject();

        //Logger.info("type:" + rdioTrack.get("type").getAsString());
        Track track = Track.retrieveTrackByRadioId(rdioTrack.get("id").getAsString());

        if (track != null
                && track.coverArt.equals("http://www.zmusiccafe.com/public/images/missing-album-art.png")) {
            //Logger.warn("Reparsing missing album image art for existing track");
            track.coverArt = "http://direct.rhapsody.com/imageserver/v2/albums/" + track.albumKey
                    + "/images/200x200.jpg";
            track.save();
        }
        ;
        if (track == null) {
            Logger.info("Finding Similar track with network");
            track = Track.find("byTitleAndAlbum_NameAndArtistAndNetwork", rdioTrack.get("name").getAsString(),
                    rdioTrack.get("albumName").getAsString(), rdioTrack.get("artistName").getAsString(), "rdio")
                    .first();
            if (track != null
                    && track.coverArt.equals("http://www.zmusiccafe.com/public/images/missing-album-art.png")) {
                //Logger.warn("Reparsing missing album iamage art");
                track.coverArt = "http://direct.rhapsody.com/imageserver/v2/albums/" + track.albumKey
                        + "/images/200x200.jpg";
                track.save();
            }
            if (track == null) {
                Logger.info("Finding similar track with no network");
                track = Track.find("byTitleIlikeAndAlbum_NameIlikeAndArtistIlikeAndNetworkIsNull",
                        rdioTrack.get("name").getAsString(), rdioTrack.get("albumName").getAsString(),
                        rdioTrack.get("artistName").getAsString()).first();
                if (track != null && track.coverArt
                        .equals("http://www.zmusiccafe.com/public/images/missing-album-art.png")) {
                    //Logger.warn("Reparsing missing album iamage art");
                    track.coverArt = "http://direct.rhapsody.com/imageserver/v2/albums/" + track.albumKey
                            + "/images/200x200.jpg";
                    track.save();
                }
            }
            if (track == null) {
                //Logger.info("Creating new track:" + rdioTrack.toString());
                track = new Track();
                track = RdioHelper.parseNewTrack(user, track, rdioTrack, false);
                track.save();

                //                        YoutubeJob ty = new YoutubeJob(track);
                //                       ty.loadYoutubes();

                //                        if (track.bestYoutubeMatch() == null || track.bestYoutubeMatch().getId() == null){
                //                            Logger.info("No you tube match for :" + track.artist + ":" + track.title);
                //                        } else {
                //                            track.youtube_id = ty.bestYouTubeMatch().getId().getVideoId().toString();
                //                            track.youtube_duration = getDuration(track.youtube_id);
                //                        }
            } else {

                // @TODO I don't think we need to do this, we have the track
                Logger.error("Why reparsing track " + track.title); // @TODO what does this have to do with anything?
                //RdioHelper.parseNewTrack(user, track, rdioTrack);
            }
        }

        // track.save();

        if (track.canStream) {
            trackResults.add(track);
        }

    }

    return trackResults;
}

From source file:controllers.Rdio.java

License:Open Source License

public static Album retrieveAlbumByRdioId(User user, String album_key) {

    //Logger.info("Retrieving album by ID:" + album_key);
    Album album = Album.find("byRdio_Key", album_key).first();

    if (album != null && album.tracksLoaded == true && album.albumTracks != null
            && album.albumTracks.size() > 1) {
        return album;
    }//from www. j av a2s .  c  o  m

    // Logger.info("Album not (fully) loaded, loading...");
    WSRequest sign = null;

    String url = endpoint + "/albums/" + album_key + "?include=tracks,images";

    boolean rerequest = false;

    try {
        sign = getConnector(user).sign(user.rdioCreds, WS.url(url), "GET");
    } catch (Exception ex) {

        Logger.error("User " + user.firstName + " had error with credentials");
        Logger.error(ex.toString());
        ex.printStackTrace();
        rerequest = true;
    }

    if (rerequest) {
        setupTokens(user, null, 0);
        try {
            sign = getConnector(user).sign(user.rdioCreds, WS.url(url), "GET");
        } catch (Exception ex) {
            Logger.error(ex.toString());
            ex.printStackTrace();
            return null;
        }
    }

    JsonElement json = sign.get().getJson();

    if (json.toString().equalsIgnoreCase("{\"code\":\"UnauthorizedError\",\"message\":\"Unauthorized\"}")) {
        json = reasssignCatalogAPIAccessToken(user, url, null);
    }

    if (json == null) {
        Logger.error("XZK:001 Null search result for " + user.firstName + " for album key" + album_key);
        return null;
    }

    JsonArray searchArray = json.getAsJsonObject().getAsJsonArray("albums");

    JsonObject searchResult;

    if (searchArray == null) {
        Logger.error("Null searchArray in Rdio.java");
        Logger.info(json.toString());
        return null;
    }
    // Logger.info(searchArray.toString());
    if (searchArray.size() < 1) {
        // @TODO Add flag to album to ignore in future
        Logger.error("Album " + album_key + " is missing from Napster catalog");
        return null;
    }
    searchResult = searchArray.get(0).getAsJsonObject();

    if (album == null) {
        Logger.info("No album at all, creating..0");
        album = new Album();
    }
    if (searchResult.get("name") == null) {
        Logger.error("Strange error:" + searchResult.toString());
        return null;
    }
    album.rdio_key = album_key;
    album.name = searchResult.get("name").getAsString();
    album.artist = searchResult.getAsJsonPrimitive("artistName").getAsString();
    String dateString = searchResult.getAsJsonPrimitive("released").getAsString();
    album.releaseDate = new DateTime(dateString).toDate();
    JsonObject linked = searchResult.getAsJsonObject("linked");
    JsonArray imagesArray = linked.getAsJsonArray("images");
    JsonElement imageElement = imagesArray.get(0);
    album.icon = imageElement.getAsJsonObject().get("url").getAsString();
    album.baseIcon = album.icon;
    album.bigIcon = album.icon;
    JsonArray tracks = linked.getAsJsonArray("tracks");
    Iterator<JsonElement> iterator = tracks.iterator();
    int trackNum = 1;
    album.albumTracks = new ArrayList<Track>();

    int tracksAdded = 0;
    while (iterator.hasNext()) {
        JsonObject trackObj = iterator.next().getAsJsonObject();
        Track track = Track.find("byRdio_Id", trackObj.get("id").getAsString()).first();

        if (track == null) {
            track = new Track();
            RdioHelper.parseNewTrack(user, track, trackObj, true);

        }

        // Make sure track is not already present
        boolean trackPresent = false;

        Iterator iter = album.albumTracks.iterator();
        while (iter.hasNext()) {
            Track albumTrack = (Track) iter.next();
            if (albumTrack.rdio_id == track.rdio_id) {
                trackPresent = true;
                break;
            }
        }

        if (trackPresent) {
            Logger.error("Trying to add a track to an album but it already exists in album!");
        } else {
            tracksAdded++;
            track.album = album;
            album.albumTracks.add(track);
        }
    }

    album.tracksLoaded = true;
    album.save();
    //Logger.info("Saved album " + album.rdio_key + " and added " + tracksAdded + " tracks.");
    return album;

}