Example usage for com.google.gson JsonParser JsonParser

List of usage examples for com.google.gson JsonParser JsonParser

Introduction

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

Prototype

@Deprecated
public JsonParser() 

Source Link

Usage

From source file:com.ericsson.eiffel.remrem.publish.service.MessageServiceRMQImpl.java

License:Apache License

@Override
public SendResult send(String jsonContent, MsgService msgService, String userDomainSuffix, String tag,
        String routingKey) {//from w ww  . j a  va2 s. c  o  m

    JsonParser parser = new JsonParser();
    try {
        JsonElement json = parser.parse(jsonContent);
        if (json.isJsonArray()) {
            return send(json, msgService, userDomainSuffix, tag, routingKey);
        } else {
            Map<String, String> map = new HashMap<>();
            Map<String, String> routingKeyMap = new HashMap<>();
            String eventId = msgService.getEventId(json.getAsJsonObject());
            if (StringUtils.isNotBlank(eventId)) {
                String routing_key = PublishUtils.getRoutingKey(msgService, json.getAsJsonObject(), rmqHelper,
                        userDomainSuffix, tag, routingKey);
                if (StringUtils.isNotBlank(routing_key)) {
                    map.put(eventId, json.toString());
                    routingKeyMap.put(eventId, routing_key);
                } else if (routing_key == null) {
                    List<PublishResultItem> resultItemList = new ArrayList<>();
                    routingKeyGenerationFailure(resultItemList);
                    return new SendResult(resultItemList);
                } else {
                    List<PublishResultItem> resultItemList = new ArrayList<>();
                    PublishResultItem resultItem = rabbitmqConfigurationNotFound(msgService);
                    resultItemList.add(resultItem);
                    return new SendResult(resultItemList);
                }
            } else {
                List<PublishResultItem> resultItemList = new ArrayList<>();
                createFailureResult(resultItemList);
                return new SendResult(resultItemList);
            }
            return send(routingKeyMap, map, msgService);
        }
    } catch (final JsonSyntaxException e) {
        String resultMsg = "Could not parse JSON.";
        if (e.getCause() != null) {
            resultMsg = resultMsg + " Cause: " + e.getCause().getMessage();
        }
        log.error(resultMsg, e.getMessage());
        List<PublishResultItem> resultItemList = new ArrayList<>();
        createFailureResult(resultItemList);
        return new SendResult(resultItemList);
    }
}

From source file:com.ericsson.eiffel.remrem.semantics.schemas.SchemaFile.java

License:Apache License

/**
 * @param jsonFileName/*ww  w. jav  a2s . c om*/
 *            -name of the input json file is to be created is an input
 *            parameter to this method
 * @param jsonObject
 *            -josnObject having required properties to generate events is
 *            an input parameter to this method
 */
public void createNewInputJsonSchema(String jsonFileName, JsonObject jsonObject) {
    String currentWorkingDir = EiffelConstants.USER_DIR;
    FileWriter writer = null;
    String copyFilePath = currentWorkingDir + File.separator + EiffelConstants.INPUT_EIFFEL_SCHEMAS;
    String newFileName = copyFilePath + File.separator + jsonFileName + EiffelConstants.JSON_MIME_TYPE;
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    JsonParser jp = new JsonParser();
    JsonElement je = jp.parse(jsonObject.toString());
    String prettyJsonString = gson.toJson(je);
    try {
        writer = new FileWriter(newFileName);
        writer.write(prettyJsonString);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            writer.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

From source file:com.ericsson.eiffel.remrem.semantics.SemanticsService.java

License:Apache License

private void outputValidate(EiffelEventType eiffelType, String jsonStringInput)
        throws EiffelValidationException {
    EiffelValidator validator = EiffelOutputValidatorFactory.getEiffelValidator(eiffelType);
    JsonObject jsonObject = new JsonParser().parse(jsonStringInput).getAsJsonObject();
    validator.validate(jsonObject);/*from  w w  w  . j av a 2  s  . co m*/
    // custom validations on an event which is not covered in schema.
    validator.customValidation(jsonObject);
}

From source file:com.ericsson.eiffel.remrem.semantics.SemanticsService.java

License:Apache License

/**
 * Gets the path to an event template file that must be in lowercase
 * and read through a resource stream. Stream is parsed into a
 * JsonElement.//from w ww. j a  va2s .c om
 * 
 * @param String eventType
 * 
 * @return json element containing an event template
 */
@Override
public JsonElement getEventTemplate(String eventType) {
    String path = "templates/" + eventType.toLowerCase() + ".json";
    InputStream fileStream = getClass().getClassLoader().getResourceAsStream(path);
    JsonElement json = null;
    JsonParser parser = new JsonParser();
    try {
        json = parser.parse(new InputStreamReader(fileStream));
    } catch (Exception e) {
        log.error(e.getMessage());
        return json;
    }
    return json;
}

From source file:com.ericsson.eiffel.remrem.semantics.validator.EiffelValidator.java

License:Apache License

/**
 *
 * @param report json validation report/*from  w ww.  j  av a 2  s.  c o  m*/
 * @return error message
 */
private String getErrorsList(ProcessingReport report) {
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    JsonParser parser = new JsonParser();
    String message = "";
    for (ProcessingMessage processingMessage : report) {
        if (LogLevel.ERROR.equals(processingMessage.getLogLevel())) {
            JsonElement element = parser.parse(processingMessage.asJson().toString());
            element.getAsJsonObject().remove("schema");
            element.getAsJsonObject().remove("level");
            message = gson.toJson(element);
            log.debug(message);
        }
    }
    return message;
}

From source file:com.esotericsoftware.spine.SkeletonJson.java

License:Open Source License

public SkeletonData readSkeletonData(String folder, String file) {
    float scale = this.scale;

    SkeletonData skeletonData = new SkeletonData();
    //skeletonData.name = file.nameWithoutExtension();
    skeletonData.name = file;/*from   w w w.j  ava 2  s . c om*/

    //JsonValue root = new JsonReader().parse(file);
    try (InputStreamReader isReader = new InputStreamReader(
            ResourceLoader.getResourceAsStream(folder + "/" + file + ".json"))) {
        JsonReader reader = new JsonReader(isReader);
        JsonParser parser = new JsonParser();

        JsonObject root = (JsonObject) parser.parse(reader);

        // Skeleton.
        JsonObject skeletonMap = root.get("skeleton").getAsJsonObject();
        if (skeletonMap != null) {
            skeletonData.hash = skeletonMap.has("hash") ? skeletonMap.get("hash").getAsString() : null;
            skeletonData.version = skeletonMap.has("spine") ? skeletonMap.get("spine").getAsString() : null;
            skeletonData.width = skeletonMap.has("width") ? skeletonMap.get("width").getAsFloat() : 0;
            skeletonData.height = skeletonMap.has("height") ? skeletonMap.get("height").getAsFloat() : 0;
            skeletonData.imagesPath = skeletonMap.has("images") ? skeletonMap.get("images").getAsString()
                    : null;
        }

        // Bones.
        //for (JsonValue boneMap = root.getChild("bones"); boneMap != null; boneMap = boneMap.next) {
        for (JsonElement boneMap : root.get("bones").getAsJsonArray()) {
            JsonObject currentBone = boneMap.getAsJsonObject();
            BoneData parent = null;
            String parentName = currentBone.has("parent") ? currentBone.get("parent").getAsString() : null;
            if (parentName != null) {
                parent = skeletonData.findBone(parentName);
                if (parent == null)
                    throw new SerializationException("Parent bone not found: " + parentName);
            }
            BoneData boneData = new BoneData(currentBone.get("name").getAsString(), parent);
            boneData.length = (currentBone.has("length") ? currentBone.get("length").getAsFloat() : 0) * scale;//boneMap.getFloat("length", 0) * scale;
            boneData.x = (currentBone.has("x") ? currentBone.get("x").getAsFloat() : 0) * scale;//boneMap.getFloat("x", 0) * scale;
            boneData.y = (currentBone.has("y") ? currentBone.get("y").getAsFloat() : 0) * scale;//boneMap.getFloat("y", 0) * scale;
            boneData.rotation = currentBone.has("rotation") ? currentBone.get("rotation").getAsFloat() : 0;//boneMap.getFloat("rotation", 0);
            boneData.scaleX = currentBone.has("scaleX") ? currentBone.get("scaleX").getAsFloat() : 1;//boneMap.getFloat("scaleX", 1);
            boneData.scaleY = currentBone.has("scaleY") ? currentBone.get("scaleY").getAsFloat() : 1;//boneMap.getFloat("scaleY", 1);
            boneData.flipX = currentBone.has("flipX") ? currentBone.get("flipX").getAsBoolean() : false;//boneMap.getBoolean("flipX", false);
            boneData.flipY = currentBone.has("flipY") ? currentBone.get("flipY").getAsBoolean() : false;//boneMap.getBoolean("flipY", false);
            boneData.inheritScale = currentBone.has("inheritScale")
                    ? currentBone.get("inheritScale").getAsBoolean()
                    : true;//boneMap.getBoolean("inheritScale", true);
            boneData.inheritRotation = currentBone.has("inheritRotation")
                    ? currentBone.get("inheritRotation").getAsBoolean()
                    : true;//boneMap.getBoolean("inheritRotation", true);

            String color = currentBone.has("color") ? currentBone.get("color").getAsString() : null;//boneMap.getString("color", null);
            if (color != null)
                boneData.getColor().set(Color.valueOf(color));

            skeletonData.bones.add(boneData);
        }

        // IK constraints.
        // TODO May return a JsonObject not Array
        //for (JsonValue ikMap = root.getChild("ik"); ikMap != null; ikMap = ikMap.next) {
        if (root.has("ik")) {
            for (JsonElement ikMap : root.get("ik").getAsJsonArray()) {
                JsonObject currentIk = ikMap.getAsJsonObject();
                IkConstraintData ikConstraintData = new IkConstraintData(currentIk.get("name").getAsString());

                //for (JsonValue boneMap = ikMap.getChild("bones"); boneMap != null; boneMap = boneMap.next) {
                for (JsonElement boneMap : currentIk.get("bones").getAsJsonArray()) {
                    String boneName = boneMap.getAsString();
                    BoneData bone = skeletonData.findBone(boneName);
                    if (bone == null)
                        throw new SerializationException("IK bone not found: " + boneName);
                    ikConstraintData.bones.add(bone);
                }

                String targetName = currentIk.get("target").getAsString();
                ikConstraintData.target = skeletonData.findBone(targetName);
                if (ikConstraintData.target == null)
                    throw new SerializationException("Target bone not found: " + targetName);

                ikConstraintData.bendDirection = (currentIk.has("bendPositive")
                        ? currentIk.get("bendPositive").getAsBoolean()
                        : true) ? 1 : -1;//ikMap.getBoolean("bendPositive", true) ? 1 : -1;
                ikConstraintData.mix = currentIk.has("mix") ? currentIk.get("mix").getAsFloat() : 1;//ikMap.getFloat("mix", 1);

                skeletonData.ikConstraints.add(ikConstraintData);
            }
        }

        // Slots.
        //for (JsonValue slotMap = root.getChild("slots"); slotMap != null; slotMap = slotMap.next) {
        for (JsonElement slotMap : root.get("slots").getAsJsonArray()) {
            JsonObject currentSlot = slotMap.getAsJsonObject();
            String slotName = currentSlot.get("name").getAsString();
            String boneName = currentSlot.get("bone").getAsString();
            BoneData boneData = skeletonData.findBone(boneName);
            if (boneData == null)
                throw new SerializationException("Slot bone not found: " + boneName);
            SlotData slotData = new SlotData(slotName, boneData);

            String color = currentSlot.has("color") ? currentSlot.get("color").getAsString() : null;//slotMap.getString("color", null);
            if (color != null)
                slotData.getColor().set(Color.valueOf(color));

            slotData.attachmentName = currentSlot.has("attachment")
                    ? currentSlot.get("attachment").getAsString()
                    : null;//slotMap.getString("attachment", null);

            slotData.additiveBlending = currentSlot.has("additive") ? currentSlot.get("additive").getAsBoolean()
                    : false;//slotMap.getBoolean("additive", false);

            skeletonData.slots.add(slotData);
        }

        // Skins.
        //for (JsonValue skinMap = root.getChild("skins"); skinMap != null; skinMap = skinMap.next) {
        for (Entry<String, JsonElement> skinMap : root.get("skins").getAsJsonObject().entrySet()) {
            Skin skin = new Skin(skinMap.getKey());
            //for (JsonValue slotEntry = skinMap.child; slotEntry != null; slotEntry = slotEntry.next) {
            for (Entry<String, JsonElement> slotEntry : skinMap.getValue().getAsJsonObject().entrySet()) {
                int slotIndex = skeletonData.findSlotIndex(slotEntry.getKey());
                if (slotIndex == -1)
                    throw new SerializationException("Slot not found: " + slotEntry.getKey());
                //for (JsonValue entry = slotEntry.child; entry != null; entry = entry.next) {
                for (Entry<String, JsonElement> entry : slotEntry.getValue().getAsJsonObject().entrySet()) {
                    Attachment attachment = readAttachment(skin, entry.getKey(),
                            entry.getValue().getAsJsonObject());
                    if (attachment != null) {
                        skin.addAttachment(slotIndex, entry.getKey(), attachment);
                    }
                }
            }
            skeletonData.skins.add(skin);
            if (skin.name.equals("default"))
                skeletonData.defaultSkin = skin;
        }

        // Events.
        //for (JsonValue eventMap = root.getChild("events"); eventMap != null; eventMap = eventMap.next) {
        if (root.has("events")) {
            for (Entry<String, JsonElement> eventMap : root.get("events").getAsJsonObject().entrySet()) {
                JsonObject currentEvent = eventMap.getValue().getAsJsonObject();
                EventData eventData = new EventData(eventMap.getKey());
                eventData.intValue = currentEvent.has("int") ? currentEvent.get("int").getAsInt() : 0;//eventMap.getInt("int", 0);
                eventData.floatValue = currentEvent.has("float") ? currentEvent.get("float").getAsFloat() : 0f;//eventMap.getFloat("float", 0f);
                eventData.stringValue = currentEvent.has("string") ? currentEvent.get("string").getAsString()
                        : null;//eventMap.getString("string", null);
                skeletonData.events.add(eventData);
            }
        }

        // Animations.
        //for (JsonValue animationMap = root.getChild("animations"); animationMap != null; animationMap = animationMap.next)
        for (Entry<String, JsonElement> animationMap : root.get("animations").getAsJsonObject().entrySet()) {
            readAnimation(animationMap.getKey(), animationMap.getValue().getAsJsonObject(), skeletonData);
        }

    } catch (JsonIOException | IOException e) {
        e.printStackTrace();
    }

    /*skeletonData.bones.shrink();
    skeletonData.slots.shrink();
    skeletonData.skins.shrink();
    skeletonData.animations.shrink();*/
    return skeletonData;
}

From source file:com.ethos.business.general.FuncionesGenerales.java

/**
 * ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 *
 * @description Metodo utilizado para leer los datos desde un objeto tipo
 * JSON//w w w .j a  v a2s  . co m
 * @param jsonRq
 * @return JsonObject
 * ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 */
public JsonObject recibirDatos(BufferedReader jsonRq) {

    StringBuilder sb = new StringBuilder();
    JsonObject jObjData = new JsonObject();
    String line;
    JsonElement jelement;
    try {

        while ((line = jsonRq.readLine()) != null) {
            sb.append(line);
            jelement = new JsonParser().parse(sb.toString());
            jObjData = (JsonObject) jelement.getAsJsonObject();
        }
    } catch (IOException | JsonSyntaxException e) {
        e.printStackTrace();
    }
    return jObjData;
}

From source file:com.evandroid.musica.lyrics.Bollywood.java

License:Open Source License

public static ArrayList<Lyrics> search(String query) {
    ArrayList<Lyrics> results = new ArrayList<>();
    String searchUrl = "http://quicklyric.azurewebsites.net/bollywood/search.php?q=%s";
    try {//from   www  . j a  v a2s.  c  o  m
        String jsonText;
        jsonText = Net.getUrlAsString(String.format(searchUrl, URLEncoder.encode(query, "utf-8")));
        JsonObject jsonResponse = new JsonParser().parse(jsonText).getAsJsonObject();
        JsonArray lyricsResults = jsonResponse.getAsJsonArray("lyrics");
        for (int i = 0; i < lyricsResults.size(); ++i) {
            JsonObject lyricsResult = lyricsResults.get(i).getAsJsonObject();
            JsonArray tags = lyricsResult.get("tags").getAsJsonArray();
            Lyrics lyrics = new Lyrics(Lyrics.SEARCH_ITEM);
            lyrics.setTitle(lyricsResult.get("name").getAsString());
            for (int j = 0; i < tags.size(); ++j) {
                JsonObject tag = tags.get(j).getAsJsonObject();
                if (tag.get("tag_type").getAsString().equals("Singer")) {
                    lyrics.setArtist(tag.get("name").getAsString().trim());
                    break;
                }
            }
            lyrics.setURL("http://quicklyric.azurewebsites.net/bollywood/get.php?id="
                    + lyricsResult.get("id").getAsInt());
            results.add(lyrics);
        }
    } catch (IOException | JsonParseException e) {
        e.printStackTrace();
    }
    return results;
}

From source file:com.evandroid.musica.lyrics.Bollywood.java

License:Open Source License

public static Lyrics fromAPI(String url, String artist, String title) {
    Lyrics lyrics = new Lyrics(Lyrics.POSITIVE_RESULT);
    lyrics.setArtist(artist);// w w  w  .  j a  v a  2 s  . c om
    lyrics.setTitle(title);
    // fixme no public url
    try {
        String jsonText = Net.getUrlAsString(url);
        JsonObject lyricsJSON = new JsonParser().parse(jsonText).getAsJsonObject();
        lyrics.setText(lyricsJSON.get("body").getAsString().trim());
    } catch (IOException | JsonParseException e) {
        e.printStackTrace();
        return new Lyrics(Lyrics.ERROR);
    }
    lyrics.setSource(domain);
    return lyrics;
}

From source file:com.evandroid.musica.lyrics.LyricWiki.java

License:Open Source License

@Reflection
public static Lyrics fromMetaData(String artist, String title) {
    if ((artist == null) || (title == null))
        return new Lyrics(Lyrics.ERROR);
    String originalArtist = artist;
    String originalTitle = title;
    String url = null;/* ww  w. j  a  v  a 2 s.  c  o m*/
    try {
        String encodedArtist = URLEncoder.encode(artist, "UTF-8");
        String encodedSong = URLEncoder.encode(title, "UTF-8");
        JsonObject json = new JsonParser()
                .parse(Net.getUrlAsString(new URL(String.format(baseUrl, encodedArtist, encodedSong)))
                        .replace("song = ", ""))
                .getAsJsonObject();
        url = URLDecoder.decode(json.get("url").getAsString(), "UTF-8");
        artist = json.get("artist").getAsString();
        title = json.get("song").getAsString();
        encodedArtist = URLEncoder.encode(artist, "UTF-8");
        encodedSong = URLEncoder.encode(title, "UTF-8");
        json = new JsonParser()
                .parse(Net.getUrlAsString(new URL(String.format(baseAPIUrl, encodedArtist, encodedSong))))
                .getAsJsonObject().get("result").getAsJsonObject();
        Lyrics lyrics = new Lyrics(Lyrics.POSITIVE_RESULT);
        lyrics.setArtist(artist);
        lyrics.setTitle(title);
        lyrics.setText(json.get("lyrics").getAsString().replaceAll("\n", "<br />"));
        lyrics.setURL(url);
        lyrics.setOriginalArtist(originalArtist);
        lyrics.setOriginalTitle(originalTitle);
        return lyrics;
    } catch (JsonParseException e) {
        return new Lyrics(Lyrics.NO_RESULT);
    } catch (IOException e) {
        return url == null ? new Lyrics(Lyrics.ERROR) : fromURL(url, originalArtist, originalTitle);
    }
}