Example usage for com.google.gson JsonObject get

List of usage examples for com.google.gson JsonObject get

Introduction

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

Prototype

public JsonElement get(String memberName) 

Source Link

Document

Returns the member with the specified name.

Usage

From source file:br.com.caelum.vraptor.serialization.gson.GsonDeserialization.java

License:Open Source License

private boolean isWithoutRoot(Parameter[] parameters, JsonObject root) {
    for (Parameter parameter : parameters) {
        if (root.get(parameter.getName()) != null)
            return false;
    }/*from w  w  w  .ja  v a2s . com*/
    return true;
}

From source file:br.com.eventick.api.Event.java

License:Open Source License

/**
 * Retorna a lista de participantes {@link Attendee} do evento
 * @return uma {@link List} de {@link Attendee}
 * @throws IOException/*ww w  .  j  a v  a2s .  c  o m*/
 * @throws InterruptedException
 * @throws ExecutionException
 */
public void setAttendees() throws IOException, InterruptedException, ExecutionException {
    String fetchURL = String.format("%s/%d/attendees", URL, this.id);
    String json = api.getRequests().get(fetchURL, this.getApi().getToken());
    JsonObject jsonObject = api.getGson().fromJson(json, JsonElement.class).getAsJsonObject();
    JsonArray jsonArray = jsonObject.get("attendees").getAsJsonArray();

    Attendee att;
    int i = 0;

    for (; i < jsonArray.size(); i++) {
        att = this.api.getGson().fromJson(jsonArray.get(i), Attendee.class);
        this.attendees.add(att);
    }
}

From source file:br.com.eventick.api.Event.java

License:Open Source License

public void setTickets() throws IOException, InterruptedException, ExecutionException {
    String fetchURL = String.format("%s/%d", URL, this.id);
    String json = api.getRequests().get(fetchURL, this.getApi().getToken());
    JsonObject jsonObject = api.getGson().fromJson(json, JsonElement.class).getAsJsonObject();
    JsonArray jsonArray = jsonObject.get("tickets").getAsJsonArray();

    Ticket tick;//from w ww.ja va  2  s .  c  om
    int i = 0;

    for (; i < jsonArray.size(); i++) {
        tick = this.api.getGson().fromJson(jsonArray.get(i), Ticket.class);
        this.tickets.add(tick);
    }
}

From source file:br.com.eventick.api.EventickAPI.java

License:Open Source License

/**
 * Retorna a colecao de eventos do usuario
 * @return//from  w  ww . java  2 s  . c  o  m
 * @throws IOException
 * @throws InterruptedException
 * @throws ExecutionException
 */
public List<Event> getMyEvents() throws IOException, InterruptedException, ExecutionException {
    List<Event> collection = new ArrayList<Event>();

    String fetchURL = String.format("%s/events", URL);
    String json = requests.get(fetchURL, this.getToken());
    JsonObject jsonObject = gson.fromJson(json, JsonElement.class).getAsJsonObject();
    JsonArray jsonArray = jsonObject.get("events").getAsJsonArray();

    Event eve;
    int i = 0;

    for (; i < jsonArray.size(); i++) {
        eve = gson.fromJson(jsonArray.get(i), Event.class);
        collection.add(eve);
    }

    return collection;
}

From source file:br.com.eventick.api.EventickAPI.java

License:Open Source License

/**
 * Otenha qualquer um de seus eventos a partir do ID
 * @param id, ID do evento//from  w w w .ja v a 2 s. c o  m
 * @return
 * @return um objeto {@link Event} daquele evento
 * @throws IOException
 * @throws ExecutionException
 * @throws InterruptedException
 */
public Event getEventById(int id) throws IOException, InterruptedException, ExecutionException {
    String fetchURL = String.format("%s/events/%d", URL, id);
    String json = requests.get(fetchURL, this.getToken());

    JsonObject jsonObject = gson.fromJson(json, JsonElement.class).getAsJsonObject();
    JsonArray jsonArray = jsonObject.get("events").getAsJsonArray();

    Event eve = gson.fromJson(jsonArray.get(0), Event.class);
    return eve;
}

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 a v a2s.  c  o 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.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;/*from  w ww  . ja  va2s  . co 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  w  w . j av  a 2 s.c o m
        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 {//from   w  w  w .  j a  v  a2s.  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./*ww  w.  j  av  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");
    }
}