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.precioustech.fxtrading.oanda.restapi.trade.OandaTradeManagementProvider.java

@Override
public Collection<Trade<Long, String, Long>> getTradesForAccount(Long accountId) {
    Collection<Trade<Long, String, Long>> allTrades = Lists.newArrayList();
    CloseableHttpClient httpClient = getHttpClient();
    try {/*from www .j  a  va2 s.c om*/
        HttpUriRequest httpGet = new HttpGet(getTradesInfoUrl(accountId));
        httpGet.setHeader(this.authHeader);
        httpGet.setHeader(OandaConstants.UNIX_DATETIME_HEADER);
        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 accountTrades = (JSONArray) jsonResp.get(trades);
            for (Object accountTrade : accountTrades) {
                JSONObject trade = (JSONObject) accountTrade;
                Trade<Long, String, Long> tradeInfo = parseTrade(trade, accountId);
                allTrades.add(tradeInfo);
            }
        } else {
            TradingUtils.printErrorMsg(resp);
        }
    } catch (Exception ex) {
        LOG.error("error encountered whilst fetching trades for account:" + accountId, ex);
    } finally {
        TradingUtils.closeSilently(httpClient);
    }
    return allTrades;
}

From source file:de.mpg.imeji.presentation.servlet.autocompleter.java

/**
 * Parse a json input from Google Geo API
 * // w w w  . jav  a  2  s  . c  o  m
 * @param google
 * @return
 * @throws IOException
 */
@SuppressWarnings("unchecked")
private String parseGoogleGeoAPI(String google) throws IOException {
    JSONObject obj = (JSONObject) JSONValue.parse(google);
    JSONArray array = (JSONArray) obj.get("results");
    JSONArray result = new JSONArray();
    for (int i = 0; i < array.size(); ++i) {
        JSONObject parseObject = (JSONObject) array.get(i);
        JSONObject sendObject = new JSONObject();
        sendObject.put("label", parseObject.get("formatted_address"));
        sendObject.put("value", parseObject.get("formatted_address"));
        JSONObject location = (JSONObject) ((JSONObject) parseObject.get("geometry")).get("location");
        sendObject.put("latitude", location.get("lat"));
        sendObject.put("longitude", location.get("lng"));
        result.add(sendObject);
    }
    StringWriter out = new StringWriter();
    result.writeJSONString(out);
    return out.toString();
}

From source file:ca.inverse.sogo.engine.source.SOGoUtilities.java

/**
        //  w  w  w . j  a  va  2 s  . c  o m
Sample output of c_settings :
        
 Calendar = {
 DragHandleVertical = 122;
 FolderColors = {
     "flachapelle:Calendar/personal" = "#FF6666";
     "lmarcotte:Calendar/2633-49F5AB80-1-ECD55D0" = "#CC33FF";
     "lmarcotte:Calendar/personal" = "#99FF99";
 };
 FolderShowAlarms = {
     "lmarcotte:Calendar/personal" = YES;
 };
 FolderShowTasks = {
     "lmarcotte:Calendar/personal" = YES;
 };
 FolderSyncTags = {
     "lmarcotte:Calendar/2633-49F5AB80-1-ECD55D0" = "a bb oo";
     "lmarcotte:Calendar/personal" = toto;
 };
 InactiveFolders = (
 );
 SubscribedFolders = (
     "flachapelle:Calendar/personal"
 );
 View = weekview;
  };
          
  As an example, for :
          
  FolderSyncTags = {
     "lmarcotte:Calendar/2633-49F5AB80-1-ECD55D0" = "a bb oo";
  };
        
  we'll eventually check, in sogo_folder_info:
          
  c_folder_type = 'Appointment' AND
  c_path2 = 'lmarcotte' AND
  c_path ENDS WITH 'Calendar/2633-49F5AB80-1-ECD55D0'
          
 */
public static HashMap getSyncTags(SOGoSyncSource source, int type, SyncContext context, String username,
        FunambolLogger log) {
    Vector<String> folders;
    HashMap h;

    h = new HashMap();

    // For now, we only support sync tags for calendars (events and tasks). So if we detect
    // a contact source, we return immediately.
    if (type == SOGoSyncSource.SOGO_CONTACT)
        return h;

    folders = new Vector<String>();

    try {
        ResultSet rs;
        Statement s;

        // We first fetch the user's time zone
        s = source.getDBConnection().createStatement();
        rs = s.executeQuery("SELECT c_settings FROM sogo_user_profile WHERE c_uid = '" + username + "'");

        if (rs.next()) {
            String data;

            data = rs.getString(1);

            // We've got no c_settings, return immediately
            if (data == null || data.length() == 0) {
                rs.close();
                s.close();
                return h;
            }

            try {
                JSONObject json, jsonCalendar;
                log.info("About to parse: " + data);
                json = (JSONObject) JSONValue.parse(data);

                if (json != null) {
                    jsonCalendar = (JSONObject) json.get("Calendar");

                    if (jsonCalendar != null) {
                        String key, value;
                        Iterator it;

                        json = (JSONObject) jsonCalendar.get("FolderSyncTags");
                        if (json != null) {
                            it = json.keySet().iterator();
                            while (it != null && it.hasNext()) {
                                key = it.next().toString();
                                value = (String) json.get(key);
                                h.put(value.toLowerCase(), key);
                            }
                        }

                        json = (JSONObject) jsonCalendar.get("FolderSynchronize");
                        if (json != null) {
                            it = json.keySet().iterator();
                            while (it != null && it.hasNext()) {
                                folders.add(it.next().toString());
                            }
                        }
                    }
                }
            } catch (Exception pe) {
                log.error("Exception occured in getSyncTags(): " + pe.toString(), pe);
            }
        }

        // We cleanup what we have to sync, if necessary. We only keep
        // the keys that are actually in "folders". 
        h.values().retainAll(folders);
        rs.close();
        s.close();

    } catch (Exception e) {
        log.error("Exception occured in getSyncTags(): " + e.toString(), e);
    }

    return h;
}

From source file:fr.bmartel.protocol.google.oauth.device.CalendarNotifManager.java

/**
 * Request usercode and verification url
 * /*from  w  w w  .ja va2  s  .c o  m*/
 */
public void requestDeviceAuth(final IOauthDeviceResponseListener responseListener) {

    String method = "POST";
    String uri = GoogleConst.GOOGLE_USERCODE_REQUEST_URI;
    String requestBody = "client_id=" + this.clientId + "&" + "scope=" + convertScopeToStr();

    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put("Content-Type", "application/x-www-form-urlencoded");
    headers.put("Host", GoogleConst.GOOGLE_ACCOUNT_HOST);

    HttpFrame frame = new HttpFrame(method, new HttpVersion(1, 1), headers, uri, new ListOfBytes(requestBody));

    ClientSocket clientSocket = new ClientSocket(GoogleConst.GOOGLE_ACCOUNT_HOST, 443);

    // set SSL encryption
    clientSocket.setSsl(true);

    clientSocket.checkCertificate(false);

    clientSocket.addClientSocketEventListener(new IHttpClientListener() {

        @Override
        public void onIncomingHttpFrame(HttpFrame frame, HttpStates httpStates, IClientSocket clientSocket) {

            if (httpStates == HttpStates.HTTP_FRAME_OK && frame.isHttpResponseFrame()) {

                Object obj = JSONValue.parse(new String(frame.getBody().getBytes()));

                JSONObject queryResponse = (JSONObject) obj;

                if (queryResponse != null) {

                    oauthRegistration = OauthForDeviceResponse.decodeOauthForDeviceResponse(queryResponse);

                    if (responseListener != null) {
                        responseListener.onResponseReceived(oauthRegistration);
                    }
                }

            }
            clientSocket.closeSocket();
        }
    });

    clientSocket.write(frame.toString().getBytes());
}

From source file:com.att.voice.AmazonEchoApi.java

public String getLatestTodo() throws IOException {
    String output = httpGet("/api/todos?type=TASK&size=1");

    // Parse JSON
    Object obj = JSONValue.parse(output);
    JSONObject jsonObject = (JSONObject) obj;
    JSONArray values = (JSONArray) jsonObject.get("values");
    JSONObject item = (JSONObject) values.get(0);

    // Get text and itemId
    String text = item.get("text").toString();
    String itemId = item.get("itemId").toString();

    if (!checkItemId(itemId)) {
        addItemId(itemId);// www .  j  a v  a  2  s  .  c  o  m
        return text;
    } else {
        return null;
    }
}

From source file:ch.uzh.ddis.thesis.lambda_architecture.speed.spout.kafka.DynamicBrokersReader.java

/**
 * [zk: localhost:2181(CONNECTED) 56] get /brokers/ids/0
 * { "host":"localhost", "jmx_port":9999, "port":9092, "version":1 }
 *
 * @param contents/*w  ww .j a v  a  2 s  .  co  m*/
 * @return
 */
private Broker getBrokerHost(byte[] contents) {
    try {
        Map<Object, Object> value = (Map<Object, Object>) JSONValue.parse(new String(contents, "UTF-8"));
        String host = (String) value.get("host");
        Integer port = ((Long) value.get("port")).intValue();
        return new Broker(host, port);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.gmail.bleedobsidian.itemcase.Updater.java

/**
 * Query ServerMods API for project variables.
 *
 * @return If successful or not.//  ww  w  .  j  ava 2s .  c om
 */
private boolean query() {
    try {
        final URLConnection con = this.url.openConnection();
        con.setConnectTimeout(5000);
        con.setReadTimeout(5000);

        if (this.apiKey != null) {
            con.addRequestProperty("X-API-Key", this.apiKey);
        }

        con.addRequestProperty("User-Agent", this.plugin.getName() + " Updater");

        con.setDoOutput(true);

        final BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
        final String response = reader.readLine();

        final JSONArray array = (JSONArray) JSONValue.parse(response);

        if (array.size() == 0) {
            this.result = UpdateResult.ERROR_ID;
            return false;
        }

        this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get("name");
        this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get("downloadUrl");
        this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get("releaseType");
        this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)).get("gameVersion");

        return true;
    } catch (IOException e) {
        if (e.getMessage().contains("HTTP response code: 403")) {
            this.result = UpdateResult.ERROR_APIKEY;
        } else {
            this.result = UpdateResult.ERROR_SERVER;
        }

        return false;
    }

}

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

/**
 * Gets the known username history of a UUID. All dates are in UTC.
 * This returns a map of player names and when they were last seen (the
 * approximate date they stopped using that name).
 *
 * @param uuid the uuid to lookup, cannot be null
 *
 * @return a map of names and dates (UTC), or an empty map for invalid input or unknown/non-existent history
 *///from  ww  w  .j a  va2 s  .  c  o m
public static Map<String, Date> getHistory(UUID uuid) {
    if (uuid == null)
        return new HashMap<>();
    try {
        URL url = new URL("http://uuid.turt2live.com/history/" + uuid.toString().replaceAll("-", ""));
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
        String parsed = "";
        String line;
        while ((line = reader.readLine()) != null)
            parsed += line;
        reader.close();

        Map<String, Date> map = new HashMap<>();
        Object o = JSONValue.parse(parsed);
        if (o instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) o;
            Object namesObj = jsonObject.get("names");
            if (namesObj instanceof JSONArray) {
                JSONArray names = (JSONArray) namesObj;
                for (Object name : names) {
                    o = name;
                    if (o instanceof JSONObject) {
                        JSONObject json = (JSONObject) o;

                        Object nameObj = json.get("name");
                        Object dateObj = json.get("last-seen");
                        if (nameObj instanceof String && dateObj instanceof String) {
                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                            format.setTimeZone(TimeZone.getTimeZone("UTC"));
                            try {
                                Date date = format.parse((String) dateObj);
                                map.put((String) nameObj, date);
                            } catch (ParseException e) {
                                System.out.println("Could not parse " + dateObj + ": " + e.getMessage());
                            }
                        }
                    }
                }
            }
        }
        return map;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return new HashMap<>();
}

From source file:de.fhg.fokus.odp.middleware.ckan.CKANGatewayUtil.java

/**
 * The function returns all meta data sets filtered according to the
 * maintainer email. The function returns a HashMap with key=metadataSetId
 * and value=HashMap(with Key = MetaDataEntryKey and value =
 * MetaDataEntryValue).// w w w .  j av a 2  s  .  co m
 * 
 * @param maintainerEmail
 *            the maintainer email.
 * @param fileFormat
 *            the file format to filter for.
 * 
 * @return the the hash map as described in the general comments of the
 *         method or null if anything has gone wrong.
 */
@SuppressWarnings("rawtypes")
public static HashMap<String, HashMap> viewDataSets(String maintainerEmail, String fileFormat) {

    // check the input parameters
    if (maintainerEmail == null || maintainerEmail.equals("") || fileFormat == null
            || fileFormat.trim().equals("")) {
        return null;
    }

    // prepare the REST API call
    String RESTcall = API_URI + "?maintainer_email=";
    maintainerEmail = maintainerEmail.replaceAll("@", "%40;");
    RESTcall += maintainerEmail;

    // the variable to return
    HashMap<String, HashMap> toreturn = new HashMap<String, HashMap>();

    try {
        // run the REST call to obtain all packages
        String packageListString = connectorInstance.restCall(RESTcall);
        if (packageListString == null) {
            log.log(Level.SEVERE, "Failed to realize api call \"" + url + RESTcall + "\" !!!");
            return null;
        }

        // parse the JSON string and obtain an array of JSON objects
        Object obj = JSONValue.parse(packageListString);
        Map m = (Map) obj;
        JSONArray array = (JSONArray) (m.get("results"));
        if (array == null) {
            return null;
        }

        // move over the JSON array
        for (int i = 0; i < array.size(); i++) {

            // get details for each single package
            String RESTcallPackage = API_URI + "/" + array.get(i);
            String packageStr = connectorInstance.restCall(RESTcallPackage);

            if (packageStr == null) {
                log.log(Level.SEVERE, "Failed to obtain details for package \"" + packageStr + "\"");
                continue;
            }

            // parse the string for the package
            Object packageObj = JSONValue.parse(packageStr);
            HashMap helpMap = (HashMap) packageObj;

            // check whether at least one of the given resources matches the
            // required file format
            boolean matchesFormat = false;
            JSONArray arr = (JSONArray) (helpMap.get("resources"));
            for (int j = 0; j < arr.size(); j++) {
                HashMap rMap = (HashMap) arr.get(j);
                String format = (String) rMap.get("format");
                if (format == null) {
                    format = "";
                }
                format = format.trim();
                if (format.equals(fileFormat)) {
                    matchesFormat = true;
                }
            }

            if (matchesFormat == false) {
                continue;
            }

            // if all filters passed --> add to the hashmap to return
            toreturn.put((String) array.get(i), helpMap);
        }
    } catch (MalformedURLException e) {
        log.log(Level.SEVERE, "Failed to realize api call \"" + url + RESTcall + "\" !!!");
        return null;
    } catch (IOException e) {
        return null;
    }

    return toreturn;
}

From source file:com.jgoetsch.eventtrader.test.ProfidingMsgParserTest.java

@SuppressWarnings("rawtypes")
public void testPartialEntry() throws Exception {
    msgParser.parseData("alert", (Map) JSONValue.parse(
            "{\"partial_entry\":{\"exitPrice\":null,\"dateAdded\":1344264185000,\"newsletterIds\":[3,26,2,24],\"type\":\"Long Stock\",\"dateClosed\":null,\"amount\":null,\"username\":\"timothysykes\",\"compareDate\":1344264185000,\"ticker\":\"NTE\",\"action\":\"Bought\",\"entryPrice\":7.0453,\"shortSell\":false,\"shortUrl\":\"1Mn22v\",\"optionType\":\"CALL\",\"callOption\":true,\"entryComments\":\"Bought small position on GIANT earnings win, this was a runner from a decade ago, now manufacturing tablets/smartphones, can't trust numbers 100% since they're a shady Chinese company, but it's the right sector and the #s look amazing, might sell into any big spike as I dig further into these blowout numbers\",\"percentage\":null,\"optionExpiration\":null,\"entryDate\":1344264185000,\"futuresMonth\":0,\"futuresYear\":0,\"shares\":6000,\"entryType\":\"STOCK\",\"exitDate\":null,\"optionStrike\":null,\"comments\":null,\"openTrade\":true},\"msgId\":27895,\"image\":\"http://a1.twimg.com/profile_images/1166026278/TimCover1_normal.jpg\",\"partial\":{\"shares\":4240,\"short\":false,\"tradeDate\":1344266235912,\"transactionType\":\"Bought\",\"price\":7.06,\"adding\":true}}"),
            new MsgHandler() {
                public boolean newMsg(Msg msg) {
                    Assert.assertEquals(TradeSignal.class, msg.getClass());
                    TradeSignal trade = (TradeSignal) msg;
                    Assert.assertEquals("timothysykes", trade.getSourceName());
                    Assert.assertEquals("http://a1.twimg.com/profile_images/1166026278/TimCover1_normal.jpg",
                            trade.getImageUrl());
                    Assert.assertEquals(1344266235912L, trade.getDate().toDate().getTime());
                    Assert.assertEquals(TradeSignal.TYPE_BUY, trade.getType());
                    Assert.assertEquals(Contract.stock("NTE"), trade.getContract());
                    Assert.assertEquals(4240, trade.getNumShares());
                    Assert.assertEquals(7.06, trade.getPrice());
                    return false;
                }//from  w  w w. j  a va  2s  .  c o m
            });
}