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:br.com.davimonteiro.lotus_runtime.config.ConfigurationUtil.java

License:Open Source License

public static Configuration save(Path configPath, Configuration config) {
    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.setPrettyPrinting().create();

    JsonParser parser = new JsonParser();
    JsonElement jsonElement = parser.parse(gson.toJson(config));

    String json = gson.toJson(jsonElement);

    try {//from   ww  w  .  ja v  a 2  s .c om
        Files.write(configPath, json.getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    }

    return config;
}

From source file:br.com.rednetsolucoes.merendaescolar.serviceimpl.MerendaEscolaServiceImpl.java

@Override
public List<MerendaEscola> listarEscolas() {
    String uri = "http://localhost:8080/webresources/escolaservice";

    WebTarget webTarget = ClientBuilder.newClient().target(uri);
    String entity = webTarget.request().get().readEntity(String.class);

    List<MerendaEscola> escolas = new ArrayList<>();

    JsonParser parser = new JsonParser();
    JsonArray jsonArray = parser.parse(entity).getAsJsonArray();
    for (JsonElement j : jsonArray) {
        String nomeEscola = j.getAsJsonObject().get("nome").toString();
        long idEscola = j.getAsJsonObject().get("id").getAsLong();

        escolas.add(new MerendaEscola(new MerendaEstoque(), nomeEscola, idEscola));
    }//from  ww w  .  j  a  v a 2 s  . com

    return escolas;
}

From source file:br.com.rednetsolucoes.merendaescolar2.serviceimpl.EscolaEstoqueServiceImpl.java

@Override
public List<EscolaEstoque> listarEscolas() {
    String uri = "http://localhost:8080/webresources/escolaservice";

    WebTarget webTarget = ClientBuilder.newClient().target(uri);
    String entity = webTarget.request().get().readEntity(String.class);

    List<EscolaEstoque> escolas = new ArrayList<>();

    JsonParser parser = new JsonParser();
    JsonArray jsonArray = parser.parse(entity).getAsJsonArray();
    for (JsonElement j : jsonArray) {
        String nomeEscola = j.getAsJsonObject().get("nome").toString();
        long idEscola = j.getAsJsonObject().get("id").getAsLong();

        escolas.add(new EscolaEstoque(nomeEscola, idEscola, new ArrayList()));
    }/*from   ww  w .  j  a  v a2  s.c om*/

    return escolas;
}

From source file:br.com.saude.api.social.gcm.GcmServer.java

License:Open Source License

public GcmServer(String apiKey, String senderId, String serviceName) {
    jsonParser = new JsonParser();
    gson = new GsonBuilder().create();
    String username = senderId + "@" + Constants.GCM_HOST;
    smackCcsClient = new SmackCcsClient(apiKey, username, serviceName, Constants.GCM_HOST,
            Constants.GCM_CCS_PORT);/*from w ww .j av  a 2  s  . co m*/
    System.out.println("smackCcsClient(" + apiKey + ", " + username + ", " + serviceName + ", "
            + Constants.GCM_HOST + ", " + Constants.GCM_CCS_PORT + ")\n");

    // Add the GcmPacketExtension as an extension provider.
    ProviderManager.addExtensionProvider(Constants.GCM_ELEMENT_NAME, Constants.GCM_NAMESPACE,
            new ExtensionElementProvider<GcmPacketExtension>() {
                @Override
                public GcmPacketExtension parse(XmlPullParser parser, int initialDepth)
                        throws XmlPullParserException, IOException, SmackException {
                    String json = parser.nextText();
                    return new GcmPacketExtension(json);
                }
            });

    stanzaFilter = new StanzaFilter() {
        @Override
        public boolean accept(Stanza stanza) {
            // Accept messages from GCM CCS.
            if (stanza.hasExtension(Constants.GCM_ELEMENT_NAME, Constants.GCM_NAMESPACE)) {
                return true;
            }
            // Reject messages that are not from GCM CCS.
            return false;
        }
    };

    stanzaListener = new StanzaListener() {
        @Override
        public synchronized void processPacket(Stanza packet) throws SmackException.NotConnectedException {
            // Extract the GCM message from the packet.
            GcmPacketExtension packetExtension = (GcmPacketExtension) packet
                    .getExtension(Constants.GCM_NAMESPACE);

            JsonObject jGcmMessage = jsonParser.parse(packetExtension.getJson()).getAsJsonObject();
            String from = jGcmMessage.get("from").getAsString();

            // If there is no message_type normal GCM message is assumed.
            if (!jGcmMessage.has("message_type")) {
                if (StringUtils.isNotEmpty(from)) {
                    JsonObject jData = jGcmMessage.get("data").getAsJsonObject();
                    onMessage(from, jData);

                    // Send Ack to CCS to confirm receipt of upstream message.
                    String messageId = jGcmMessage.get("message_id").getAsString();
                    if (StringUtils.isNotEmpty(messageId)) {
                        sendAck(from, messageId);
                    } else {
                        logger.log(Level.SEVERE, "Message ID is null or empty.");
                    }
                } else {
                    logger.log(Level.SEVERE, "From is null or empty.");
                }
            } else {
                // Handle message_type here.
                String messageType = jGcmMessage.get("message_type").getAsString();
                if (messageType.equals("ack")) {
                    // Handle ACK. Here the ack is logged, you may want to further process the ACK at this
                    // point.
                    String messageId = jGcmMessage.get("message_id").getAsString();
                    logger.info("ACK received for message " + messageId + " from " + from);
                } else if (messageType.equals("nack")) {
                    // Handle NACK. Here the nack is logged, you may want to further process the NACK at
                    // this point.
                    String messageId = jGcmMessage.get("message_id").getAsString();
                    logger.info("NACK received for message " + messageId + " from " + from);
                } else if (messageType.equals("control")) {
                    logger.info("Control message received.");
                    String controlType = jGcmMessage.get("control_type").getAsString();
                    if (controlType.equals("CONNECTION_DRAINING")) {
                        // Handle connection draining
                        // SmackCcsClient only maintains one connection the CCS to reduce complexity. A real
                        // world application should be capable of maintaining multiple connections to GCM,
                        // allowing the application to continue to onMessage for incoming messages on the
                        // draining connection and sending all new out going messages on a newly created
                        // connection.
                        logger.info("Current connection will be closed soon.");
                    } else {
                        // Currently the only control_type is CONNECTION_DRAINING, if new control messages
                        // are added they should be handled here.
                        logger.info("New control message has been received.");
                    }
                }
            }
        }
    };
    smackCcsClient.listen(stanzaListener, stanzaFilter);

}

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

License:Apache License

/**
 * Parses the object into its equivalent JsonElement representation.
 * <p/>//from   www . ja  v  a  2s  .  co m
 * Will be thrown {@code JsonSyntaxException} if the specified object is an instance of String and
 *
 * @param object the specified object to be parsed
 * @return JsonElement representation of specified object
 * //@throws JsonSyntaxException
 */
public static JsonElement parseObject(Object object) /*throws JsonSyntaxException*/ {
    if (object != null && object instanceof String) {
        try {
            return new JsonParser().parse((String) object);
        } catch (JsonSyntaxException e) {
            return null;
        }
    } else {
        return objectToJsonElementTree(object);
    }
}

From source file:br.com.uft.scicumulus.utils.Utils.java

public static JsonObject openFileJson(String file) throws FileNotFoundException {
    FileReader reader = new FileReader(file);
    JsonParser jsonParser = new JsonParser();
    JsonObject jsonObject = (JsonObject) jsonParser.parse(reader);
    return jsonObject;
}

From source file:br.mack.api.Marvel.java

public static void main(String[] args) {
    //Criao de um timestamp
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyyhhmmss");
    String ts = sdf.format(date);

    //Criao do HASH
    String hashStr = MD5(ts + privatekey + apikey);
    String uri;/*ww  w . ja va 2s.  c  o m*/
    String name = "Captain%20America";
    //url de consulta
    uri = urlbase + "?nameStartsWith=" + name + "&ts=" + ts + "&apikey=" + apikey + "&hash=" + hashStr;

    try {
        CloseableHttpClient cliente = HttpClients.createDefault();

        //HttpHost proxy = new HttpHost("172.16.0.10", 3128, "http");
        //RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
        HttpGet httpget = new HttpGet(uri);
        //httpget.setConfig(config);
        HttpResponse response = cliente.execute(httpget);
        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        //Header[] h = (Header[]) response.getAllHeaders();

        /*for (Header head : h) {
        System.out.println(head.getValue());
        }*/
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            InputStream instream = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
            StringBuilder out = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                out.append(line);
            }
            //System.out.println(out.toString());
            reader.close();
            instream.close();
            JsonParser parser = new JsonParser();

            // find character's comics
            JsonElement comicResultElement = parser.parse(out.toString());
            JsonObject comicDataWrapper = comicResultElement.getAsJsonObject();
            JsonObject data = (JsonObject) comicDataWrapper.get("data");
            JsonArray results = data.get("results").getAsJsonArray();

            System.out.println(((JsonObject) results.get(0)).get("thumbnail"));

        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:br.net.fabiozumbi12.redprotect.MojangUUIDs.java

License:Open Source License

public static String getName(String UUID) {
    try {/*from w  ww. j  a  va  2  s .c om*/
        URL url = new URL("https://api.mojang.com/user/profiles/" + UUID.replaceAll("-", "") + "/names");
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String line = in.readLine();
        if (line == null) {
            return null;
        }
        JsonArray array = (JsonArray) new JsonParser().parse(line);
        HashMap<Long, String> names = new HashMap<Long, String>();
        String name = "";
        for (Object profile : array) {
            JsonObject jsonProfile = (JsonObject) profile;
            if (jsonProfile.has("changedToAt")) {
                names.put(jsonProfile.get("changedToAt").getAsLong(), jsonProfile.get("name").getAsString());
                continue;
            }
            name = jsonProfile.get("name").getAsString();
        }
        if (!names.isEmpty()) {
            Long key = Collections.max(names.keySet());
            return names.get(key);
        } else {
            return name;
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;
}

From source file:br.net.fabiozumbi12.redprotect.MojangUUIDs.java

License:Open Source License

public static String getUUID(String player) {
    try {//  w w w.ja  v  a 2 s. c o m
        URL url = new URL("https://api.mojang.com/users/profiles/minecraft/" + player);
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String line = in.readLine();
        if (line == null) {
            return null;
        }
        JsonObject jsonProfile = (JsonObject) new JsonParser().parse(line);
        String name = jsonProfile.get("id").getAsString();
        return toUUID(name);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;
}

From source file:br.org.cesar.knot.lib.connection.KnotSocketIo.java

License:Open Source License

/**
 * Turns the device belongs to someone. When a device is created in
 * Meshblu, it is an orphan device. In other words, everyone can made any
 * changes on this device. After claim a device, only the
 * owner can delete or update it./*w w  w.  j a  v  a  2 s  .  c  o m*/
 * Note: In Meshblu, the owner for one device IS another device.
 *
 * @param device         the identifier of device (uuid)
 * @param callbackResult Callback for this method
 * @throws KnotException
 * @throws SocketNotConnected <p>
 *                            Check the reference on @see <a https://meshblu-socketio.readme.io/docs/unregister</a>
 */
public <T extends AbstractThingDevice> void deleteDevice(final T device, final Event<T> callbackResult)
        throws SocketNotConnected {

    if (isSocketRegistered() && isSocketConnected() && device != null) {
        JSONObject deviceToDelete = getNecessaryDeviceInformation(device);

        if (deviceToDelete != null) {
            mSocket.emit(EVENT_UNREGISTER_DEVICE, deviceToDelete, new Ack() {
                @Override
                public void call(Object... args) {
                    //Get First element of the array
                    if (args.length > 0 && args[FIRST_EVENT_RECEIVED] != null) {
                        JsonElement jsonElement = new JsonParser().parse(args[FIRST_EVENT_RECEIVED].toString());
                        JsonObject jsonObject = jsonElement.getAsJsonObject();
                        if (jsonObject.get(ERROR) != null) {
                            callbackResult.onEventError(new KnotException(jsonObject.get(ERROR).toString()));
                        } else if (jsonObject.get(FROMUUID) != null) {
                            callbackResult.onEventFinish(device);
                        } else {
                            callbackResult.onEventError(new KnotException("Unknown error"));
                        }

                    } else {
                        callbackResult.onEventError(new KnotException("Failed to delete file"));
                    }

                }
            });
        }
    } else {
        throw new SocketNotConnected("Socket not ready or connected");
    }
}