Example usage for org.json.simple JSONValue parse

List of usage examples for org.json.simple JSONValue parse

Introduction

In this page you can find the example usage for org.json.simple JSONValue parse.

Prototype

public static Object parse(String s) 

Source Link

Usage

From source file:com.turt2live.hurtle.uuid.UUIDServiceProvider.java

/**
 * Gets the UUID of a player name./*from w ww .  j  a  v  a2 s  .  c  om*/
 *
 * @param name the name, cannot be null
 *
 * @return the UUID for the player, or null if not found or for invalid input
 */
public static UUID getUUID(String name) {
    if (name == null)
        return null;
    try {
        URL url = new URL("http://uuid.turt2live.com/uuid/" + name);
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
        String parsed = "";
        String line;
        while ((line = reader.readLine()) != null)
            parsed += line;
        reader.close();

        Object o = JSONValue.parse(parsed);
        if (o instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) o;
            o = jsonObject.get("uuid");
            if (o instanceof String) {
                String s = (String) o;
                if (!s.equalsIgnoreCase("unknown")) {
                    return UUID.fromString(insertDashes(s));
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.turt2live.uuid.turt2live.v1.ApiV1Service.java

@Override
public String[] getNameHistory(UUID uuid) {
    String response = doUrlRequest(getConnectionUrl() + "/history/" + convertUuid(uuid));
    if (response != null) {
        JSONObject json = (JSONObject) JSONValue.parse(response);

        if (json.containsKey("names")) {
            JSONArray array = (JSONArray) json.get("names");
            String[] names = new String[array.size()];

            int i = 0;
            for (Object o : array) {
                names[i] = o.toString();
                i++;//from w w  w  .  j a v  a2s.  co  m
            }

            return names;
        }
    }

    return null;
}

From source file:com.precioustech.fxtrading.oanda.restapi.instrument.OandaInstrumentDataProviderService.java

@Override
public Collection<TradeableInstrument<String>> getInstruments() {
    Collection<TradeableInstrument<String>> instrumentsList = Lists.newArrayList();
    CloseableHttpClient httpClient = getHttpClient();
    try {/*  w ww  .j  a  va 2s . c om*/
        HttpUriRequest httpGet = new HttpGet(getInstrumentsUrl());
        httpGet.setHeader(authHeader);
        LOG.info(TradingUtils.executingRequestMsg(httpGet));
        HttpResponse resp = httpClient.execute(httpGet);
        String strResp = TradingUtils.responseToString(resp);
        if (strResp != StringUtils.EMPTY) {
            Object obj = JSONValue.parse(strResp);
            JSONObject jsonResp = (JSONObject) obj;
            JSONArray instrumentArray = (JSONArray) jsonResp.get(instruments);

            for (Object o : instrumentArray) {
                JSONObject instrumentJson = (JSONObject) o;
                String instrument = (String) instrumentJson.get(OandaJsonKeys.instrument);
                String[] currencies = OandaUtils.splitCcyPair(instrument);
                Double pip = Double.parseDouble(instrumentJson.get(OandaJsonKeys.pip).toString());
                JSONObject interestRates = (JSONObject) instrumentJson.get(interestRate);
                if (interestRates.size() != 2) {
                    throw new IllegalArgumentException();
                }

                JSONObject currency1Json = (JSONObject) interestRates.get(currencies[0]);
                JSONObject currency2Json = (JSONObject) interestRates.get(currencies[1]);

                final double baseCurrencyBidInterestRate = ((Number) currency1Json.get(bid)).doubleValue();
                final double baseCurrencyAskInterestRate = ((Number) currency1Json.get(ask)).doubleValue();
                final double quoteCurrencyBidInterestRate = ((Number) currency2Json.get(bid)).doubleValue();
                final double quoteCurrencyAskInterestRate = ((Number) currency2Json.get(ask)).doubleValue();

                InstrumentPairInterestRate instrumentPairInterestRate = new InstrumentPairInterestRate(
                        baseCurrencyBidInterestRate, baseCurrencyAskInterestRate, quoteCurrencyBidInterestRate,
                        quoteCurrencyAskInterestRate);
                TradeableInstrument<String> tradeableInstrument = new TradeableInstrument<String>(instrument,
                        pip, instrumentPairInterestRate, null);
                instrumentsList.add(tradeableInstrument);
            }
        } else {
            TradingUtils.printErrorMsg(resp);
        }
    } catch (Exception e) {
        LOG.error("exception encountered whilst retrieving all instruments info", e);
    } finally {
        TradingUtils.closeSilently(httpClient);
    }
    return instrumentsList;
}

From source file:net.maxgigapop.mrs.driver.openstack.OpenStackRESTClient.java

public static JSONArray pullNovaVM(String host, String tenantId, String token) throws IOException {

    String url = String.format("http://%s:8774/v2/%s/servers/detail", host, tenantId);
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    String responseStr = sendGET(obj, con, "", token);

    JSONObject responseJSON = (JSONObject) JSONValue.parse(responseStr);
    JSONArray servers = (JSONArray) responseJSON.get("servers");

    return servers;
}

From source file:com.github.pmerienne.trident.ml.preprocessing.StandardScalerIntegrationTest.java

@SuppressWarnings({ "unchecked", "rawtypes" })
protected static double extractDouble(String drpcResult) {
    List<List<Object>> values = (List) JSONValue.parse(drpcResult);
    Double value = (Double) values.get(0).get(0);
    return value;
}

From source file:app.WebSocketServerHandler.java

private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

    // Check for closing frame
    if (frame instanceof CloseWebSocketFrame) {
        channels.remove(ctx.channel());//from   w w w  . j  a v a 2s  .  co m
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
        return;
    }
    if (frame instanceof PingWebSocketFrame) {
        ctx.write(new PongWebSocketFrame(frame.content().retain()));
        return;
    }
    if (frame instanceof TextWebSocketFrame) {
        JSONObject msg = (JSONObject) JSONValue.parse(((TextWebSocketFrame) frame).text());

        if (msg == null) {
            System.out.println("Unknown message type");
            return;
        }

        switch (msg.get("type").toString()) {
        case "broadcast":
            final TextWebSocketFrame outbound = new TextWebSocketFrame(msg.toJSONString());
            channels.forEach(gc -> gc.writeAndFlush(outbound.duplicate().retain()));
            msg.replace("type", "broadcastResult");
            ctx.writeAndFlush(new TextWebSocketFrame(msg.toJSONString()));
            break;
        case "echo":
            ctx.writeAndFlush(new TextWebSocketFrame(msg.toJSONString()));
            break;
        default:
            System.out.println("Unknown message type");
        }

        return;
    }
}

From source file:com.n1t3slay3r.empirecraft.main.Update.java

/**
 * Query the API to find the latest approved file's details.
 *//*w  w  w  .java2  s  . com*/
public void query() {
    URL url;

    try {
        // Create the URL to query using the project's ID
        url = new URL(API_HOST + API_QUERY + projectID);
    } catch (MalformedURLException e) {
        return;
    }

    try {
        // Open a connection and query the project
        URLConnection conn = url.openConnection();

        if (apiKey != null) {
            // Add the API key to the request if present
            conn.addRequestProperty("X-API-Key", apiKey);
        }

        // Add the user-agent to identify the program
        conn.addRequestProperty("User-Agent", "ServerModsAPI-Example (by Gravity)");

        // Read the response of the query
        // The response will be in a JSON format, so only reading one line is necessary.
        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String response = reader.readLine();

        // Parse the array of files from the query's response
        JSONArray array = (JSONArray) JSONValue.parse(response);

        if (array.size() > 0) {
            // Get the newest file's details
            JSONObject latest = (JSONObject) array.get(array.size() - 1);

            // Get the version's title
            String versionName = (String) latest.get(API_NAME_VALUE);

            // Get the version's link
            String versionLink = (String) latest.get(API_LINK_VALUE);

            // Get the version's release type
            String versionType = (String) latest.get(API_RELEASE_TYPE_VALUE);

            // Get the version's file name
            String versionFileName = (String) latest.get(API_FILE_NAME_VALUE);

            // Get the version's game version
            String versionGameVersion = (String) latest.get(API_GAME_VERSION_VALUE);

            if (playername != null) {
                Bukkit.getPlayer(UUID.fromString(playername))
                        .sendMessage(ChatColor.YELLOW + "The latest version of " + ChatColor.GOLD
                                + versionFileName + ChatColor.YELLOW + " is " + ChatColor.GOLD + versionName
                                + ChatColor.YELLOW + ", a " + ChatColor.GOLD + versionType.toUpperCase()
                                + ChatColor.YELLOW + " for " + ChatColor.GOLD + versionGameVersion
                                + ChatColor.YELLOW + ", available at: " + ChatColor.GOLD + versionLink);
            } else {
                System.out.println("The latest version of " + versionFileName + " is " + versionName + ", a "
                        + versionType.toUpperCase() + " for " + versionGameVersion + ", available at: "
                        + versionLink);
            }
        }
    } catch (IOException e) {
    }
}

From source file:edu.rit.chrisbitler.ritcraft.slackintegration.rtm.RTMClient.java

/**
 * Method for when the websocket opens. We set up the message listener here too
 * @param session The websocket session that just opened for this method
 * @param endpointConfig The endpoint configuration - not used
 *///  w  w  w.  j a  v  a2  s.  co m
@Override
public void onOpen(Session session, EndpointConfig endpointConfig) {
    RTMClient.this.session = session;
    System.out.println("Websocket connection open");

    //Register the message handler - This has to be a MessageHandler.Partial. If it is a MessageHandler.Whole it won't work.
    session.addMessageHandler(new MessageHandler.Partial<String>() {
        @Override
        public void onMessage(String s, boolean b) {
            JSONObject obj = (JSONObject) JSONValue.parse(s);
            if (obj.get("type") != null) {
                String type = String.valueOf(obj.get("type"));

                //Give the message off to the handler based on the event type
                switch (type) {
                case "hello":
                    HelloMessage.handle();
                    break;
                case "message":
                    MsgMessage.handle(obj);
                    break;
                }
            } else {
                System.out.println("[Slack] Recieved malformed JSON message from slack - no type");
            }
        }
    });
}

From source file:com.mansoor.uncommon.configuration.JsonConfiguration.java

/**
 * {@inheritDoc}/*from w  ww . j  a v  a 2 s . co  m*/
 */
@SuppressWarnings("unchecked")
protected void loadConfig(final File propertyFile) throws IOException {
    final Map<String, Object> map = (Map<String, Object>) JSONValue.parse(new FileReader(propertyFile));
    Preconditions.checkNull(map, "Unable to load Json");
    properties.putAll(map);
}

From source file:com.p000ison.dev.simpleclans2.util.JSONUtil.java

public static <T> Set<T> JSONToSet(String json, Set<T> set) {
    if (json == null || json.isEmpty()) {
        return null;
    }//from w  w w. ja v a  2 s. c om

    JSONArray parser = (JSONArray) JSONValue.parse(json);

    if (parser == null) {
        return null;
    }

    for (Object obj : parser) {
        set.add((T) obj);
    }

    return set;
}