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:ci6226.buildindex.java

/**
 * Indexes the given file using the given writer, or if a directory is
 * given, recurses over files and directories found under the given
 * directory.//w  w  w  .  ja v  a2 s. co m
 *
 * NOTE: This method indexes one document per input file. This is slow. For
 * good throughput, put multiple documents into your input file(s). An
 * example of this is in the benchmark module, which can create "line doc"
 * files, one document per line, using the
 * <a
 * href="../../../../../contrib-benchmark/org/apache/lucene/benchmark/byTask/tasks/WriteLineDocTask.html"
 * >WriteLineDocTask</a>.
 *
 * @param writer Writer to the index where the given file/dir info will be
 * stored
 * @param file The file to index, or the directory to recurse into to find
 * files to index
 * @throws IOException If there is a low-level I/O error
 */
static void indexDocs(IndexWriter writer, String s) throws IOException {
    Object obj = JSONValue.parse(s);
    JSONObject person = (JSONObject) obj;

    String text = (String) person.get("text");
    //  System.out.println(text);

    String user_id = (String) person.get("user_id");
    //  System.out.println(user_id);

    String business_id = (String) person.get("business_id");
    //  System.out.println(business_id);
    String review_id = (String) person.get("review_id");
    //   System.out.println(review_id);

    JSONObject votes = (JSONObject) person.get("votes");

    long funny = (Long) votes.get("funny");
    // System.out.println(funny);

    long cool = (Long) votes.get("cool");
    //   System.out.println(cool);

    long useful = (Long) votes.get("useful");
    // System.out.println(useful);
    // do not try to index files that cannot be read

    // make a new, empty document
    Document doc = new Document();

    // Add the path of the file as a field named "path".  Use a
    // field that is indexed (i.e. searchable), but don't tokenize 
    // the field into separate words and don't index term frequency
    // or positional information:
    Field review_idf = new StringField("review_id", review_id, Field.Store.YES);
    doc.add(review_idf);
    Field business_idf = new StringField("business_id", business_id, Field.Store.YES);
    doc.add(business_idf);
    Field textf = new TextField("text", text, Field.Store.YES);
    doc.add(textf);
    Field user_idf = new StringField("user_id", user_id, Field.Store.YES);
    doc.add(user_idf);

    // Add the last modified date of the file a field named "modified".
    // Use a LongField that is indexed (i.e. efficiently filterable with
    // NumericRangeFilter).  This indexes to milli-second resolution, which
    // is often too fine.  You could instead create a number based on
    // year/month/day/hour/minutes/seconds, down the resolution you require.
    // For example the long value 2011021714 would mean
    // February 17, 2011, 2-3 PM.
    doc.add(new LongField("cool", cool, Field.Store.YES));
    doc.add(new LongField("funny", funny, Field.Store.YES));
    doc.add(new LongField("useful", useful, Field.Store.YES));

    // Add the contents of the file to a field named "contents".  Specify a Reader,
    // so that the text of the file is tokenized and indexed, but not stored.
    // Note that FileReader expects the file to be in UTF-8 encoding.
    // If that's not the case searching for special characters will fail.
    //  if (writer.getConfig().getOpenMode() == OpenMode.CREATE) {
    // New index, so we just add the document (no old document can be there):
    //   System.out.println("adding " + review_id);
    writer.addDocument(doc);
    //       } else {
    // Existing index (an old copy of this document may have been indexed) so 
    // we use updateDocument instead to replace the old one matching the exact 
    // path, if present:
    //         System.out.println("updating " + file);
    ///          writer.updateDocument(new Term("review_id", review_id), doc);
    //     }

}

From source file:com.noelportugal.amazonecho.AmazonEchoApi.java

public String getLatestCards() throws IOException {

    String output = httpGet("/api/cards");
    System.out.println(output);/*from ww  w  .  j  a v  a2  s  .c  o  m*/
    // Parse JSON
    Object obj = JSONValue.parse(output);
    JSONObject jsonObject = (JSONObject) obj;
    JSONArray values = (JSONArray) jsonObject.get("cards");
    //System.out.println(values.size());

    JSONObject item = (JSONObject) values.get(0);

    //System.out.println(item.toString());
    // Get text and itemId
    String text = item.get("title").toString();
    String itemId = item.get("title").toString();
    //System.out.println(text);

    if (!checkItemId(itemId)) {

        return text;
    } else {
        return null;
    }
}

From source file:gribbit.util.RequestBuilder.java

/**
 * Send a POST request to a given URL with the given key-value POST parameters (with keys in the even indices
 * and values in the following odd indices). Result is a json-simple object, see
 * https://code.google.com/p/json-simple/wiki/DecodingExamples
 * /*from w  ww .  ja  va  2  s .c  om*/
 * @throws IllegalArgumentException
 *             if request could not be completed or JSON could not be parsed.
 */
public static Object postToURLWithJSONResponse(String url, String... keyValuePairs)
        throws IllegalArgumentException {
    String jsonStr = (String) makeRequest(url, keyValuePairs, /* isGET = */false, /* isBinaryResponse = */
            false);
    try {
        return JSONValue.parse(jsonStr);
    } catch (Exception e) {
        throw new IllegalArgumentException("Could not parse JSON response: " + e.getMessage(), e);
    }
}

From source file:mediasearch.twitter.TwitterService.java

public long getRateLimitStatus() {
    HttpsURLConnection connection = bearerAuthConnectionGet(TwitterData.RATE_LIMIT_STATUS_URL);

    JSONObject obj = (JSONObject) JSONValue.parse(readResponse(connection));
    if (obj != null) {
        JSONObject o = (JSONObject) obj.get("resources");
        o = (JSONObject) o.get("search");
        o = (JSONObject) o.get("/search/tweets");
        return (long) o.get("remaining");
    }//from  w ww  . ja  v  a 2 s . c o m

    return 0xdeadbeef;
}

From source file:cs.rsa.ts14dist.appserver.RabbitMQRPCConnector.java

@Override
public JSONObject sendLowPriorityRequestAndBlockUntilReply(JSONObject payload) throws IOException {
    String response = null;//from  w  w  w  . j a v a 2 s  .  com
    String corrId = UUID.randomUUID().toString();

    BasicProperties props = new BasicProperties.Builder().correlationId(corrId)
            .replyTo(replyLowPriorityQueueName).build();

    String message = payload.toJSONString();

    logger.trace("Send request: " + message);
    channelLowPriority.basicPublish("", requestLowPriorityQueueName, props, message.getBytes());

    while (true) {
        QueueingConsumer.Delivery delivery = null;
        try {
            delivery = consumerLowPriority.nextDelivery();
        } catch (ShutdownSignalException e) {
            logger.error("ShutdownException: " + e.getMessage());
            e.printStackTrace();
        } catch (ConsumerCancelledException e) {
            logger.error("ConsumerCancelledException: " + e.getMessage());
            e.printStackTrace();
        } catch (InterruptedException e) {
            logger.error("InterruptedException: " + e.getMessage());
            e.printStackTrace();
        }
        if (delivery.getProperties().getCorrelationId().equals(corrId)) {
            response = new String(delivery.getBody(), "UTF-8");
            logger.trace("Retrieved reply: " + response);
            break;
        }
    }

    JSONObject reply = (JSONObject) JSONValue.parse(response);
    return reply;
}

From source file:eu.hansolo.accs.RestClient.java

public JSONObject getAddress(final double LATITUDE, final double LONGITUDE) {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        HttpGet get = new HttpGet("http://maps.google.com/maps/api/geocode/json?latlng=" + LATITUDE + ","
                + LONGITUDE + "&sensor=false");
        get.addHeader("accept", "application/json");

        CloseableHttpResponse response = httpClient.execute(get);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            //throw new RuntimeException("Failed: HTTP error code: " + statusCode);
            return new JSONObject();
        }//from w w w . j a  va  2  s  . c  o  m

        String output = getFromResponse(response);
        JSONObject jsonObject = (JSONObject) JSONValue.parse(output);
        return jsonObject;
    } catch (IOException e) {
        return new JSONObject();
    }
}

From source file:com.rogue.simpleclient.SimpleClient.java

/**
 * Connects to and authenticates with the Mojang auth server
 *
 * @since 1.0.0//w  w w  .  j a  v  a  2s  .co  m
 * @version 1.0.0
 *
 * @param username The username/email to use
 * @param password The password to use
 * @throws IOException Incorrect credentials or some other connection error
 */
private void connect(String username, String password) throws IOException {
    HttpURLConnection http = (HttpURLConnection) this.url.openConnection();
    http.setRequestMethod("POST");
    http.setRequestProperty("Content-Type", "application/json");
    http.setUseCaches(false);
    http.setDoOutput(true);
    try (DataOutputStream wr = new DataOutputStream(http.getOutputStream())) {
        wr.writeBytes(this.getPayload(username, password).toJSONString());
        wr.flush();
    }
    StringBuilder sb = new StringBuilder();
    try (InputStreamReader is = new InputStreamReader(http.getInputStream());
            BufferedReader br = new BufferedReader(is)) {
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
    }
    this.response = (JSONObject) JSONValue.parse(sb.toString());
}

From source file:ch.simas.jtoggl.JToggl.java

/**
 * Get time entries started in a specific time range. 
 * By default, the number of days from the field "How long are time entries 
 * visible in the timer" under "My settings" in Toggl is used to determine 
 * which time entries to return but you can specify another date range using 
 * start_date and end_date parameters./*ww  w. j  ava2s.c  o m*/
 * 
 * @param startDate
 * @param endDate
 * @return list of {@link TimeEntry}
 */
public List<TimeEntry> getTimeEntries(Date startDate, Date endDate) {
    Client client = prepareClient();
    WebResource webResource = client.resource(TIME_ENTRIES);

    if (startDate != null && endDate != null) {
        MultivaluedMap queryParams = new MultivaluedMapImpl();
        queryParams.add("start_date", DateUtil.convertDateToString(startDate));
        queryParams.add("end_date", DateUtil.convertDateToString(endDate));
        webResource = webResource.queryParams(queryParams);
    }
    String response = webResource.get(String.class);
    JSONArray data = (JSONArray) JSONValue.parse(response);

    List<TimeEntry> entries = new ArrayList<TimeEntry>();
    if (data != null) {
        for (Object obj : data) {
            JSONObject entryObject = (JSONObject) obj;
            entries.add(new TimeEntry(entryObject.toJSONString()));
        }
    }
    return entries;
}

From source file:formatter.handler.get.FormatterGetHandler.java

/**
 * Use this method to retrieve the doc just to see its format
 * @param db the database to fetch from/*from w  w  w .j a  v  a 2  s  . co m*/
 * @param docID the doc's ID
 * @return a JSON doc as returned by Mongo
 * @throws FormatterException 
 */
JSONObject loadJSONDocument(String db, String docID) throws FormatterException {
    try {
        String data = Connector.getConnection().getFromDb(db, docID);
        if (data.length() > 0) {
            JSONObject doc = (JSONObject) JSONValue.parse(data);
            if (doc != null)
                return doc;
        }
        throw new FormatterException("Doc not found " + docID);
    } catch (Exception e) {
        throw new FormatterException(e);
    }
}

From source file:com.grouptuity.venmo.VenmoSDK.java

public static VenmoResponse validateVenmoPaymentResponse(String signed_payload) {
    String encoded_signature, payload;
    if (signed_payload == null) {
        return new VenmoResponse(null, null, null, "0");
    }//from w ww .ja v  a2s . c o m
    try {
        String[] encodedsig_payload_array = signed_payload.split("\\.");
        encoded_signature = encodedsig_payload_array[0];
        payload = encodedsig_payload_array[1];
    } catch (ArrayIndexOutOfBoundsException e) {
        return new VenmoResponse(null, null, null, "0");
    }

    String decoded_signature = base64_url_decode(encoded_signature);
    String data;
    // check signature 
    String expected_sig = hash_hmac(payload, Grouptuity.VENMO_SECRET, "HmacSHA256");

    Log.d("VenmoSDK", "expected_sig using HmacSHA256:" + expected_sig);

    VenmoResponse myVenmoResponse;

    if (decoded_signature.equals(expected_sig)) {
        data = base64_url_decode(payload);

        try {
            JSONArray response = (JSONArray) JSONValue.parse(data);
            JSONObject obj = (JSONObject) response.get(0);
            String payment_id = obj.get("payment_id").toString();
            String note = obj.get("note").toString();
            String amount = obj.get("amount").toString();
            String success = obj.get("success").toString();
            myVenmoResponse = new VenmoResponse(payment_id, note, amount, success);
        } catch (Exception e) {
            Log.d("VenmoSDK", "Exception caught: " + e.getMessage());
            myVenmoResponse = new VenmoResponse(null, null, null, "0");
        }
    } else {
        Log.d("VenmoSDK", "Signature does NOT match");
        myVenmoResponse = new VenmoResponse(null, null, null, "0");
    }
    return myVenmoResponse;
}