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:be.cytomine.client.Cytomine.java

private JSONObject createJSONResponse(int code, String response) throws CytomineException {
    try {//  w ww  .  j  ava 2s.  c o  m
        Object obj = JSONValue.parse(response);
        return (JSONObject) obj;
    } catch (Exception e) {
        log.error(e);
        throw new CytomineException(code, response);
    } catch (Error e) {
        log.error(e);
        throw new CytomineException(code, response);
    }
}

From source file:com.turt2live.uuid.turt2live.v2.ApiV2Service.java

@Override
public List<PlayerRecord> getRandomSample(int amount) {
    if (amount <= 0)
        throw new IllegalArgumentException();

    String response = doUrlRequest(getConnectionUrl() + "/random/" + amount);
    if (response == null || response.length() <= 2)
        return null;

    JSONArray array = (JSONArray) ((JSONObject) JSONValue.parse(response)).get("results");
    List<PlayerRecord> records = new ArrayList<>();

    for (Object o : array) {
        PlayerRecord record = parsePlayerRecord(o.toString());

        if (record != null)
            records.add(record);// w w  w  . j a v a2s.  co m
    }

    return records;
}

From source file:com.precioustech.fxtrading.oanda.restapi.order.OandaOrderManagementProvider.java

@Override
public Long placeOrder(Order<String, Long> order, Long accountId) {
    CloseableHttpClient httpClient = getHttpClient();
    try {//from  ww  w .  j a va2 s . c  om
        HttpPost httpPost = createPostCommand(order, accountId);
        LOG.info(TradingUtils.executingRequestMsg(httpPost));
        HttpResponse resp = httpClient.execute(httpPost);
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK
                || resp.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            if (resp.getEntity() != null) {
                String strResp = TradingUtils.responseToString(resp);
                Object o = JSONValue.parse(strResp);
                JSONObject orderResponse;
                if (order.getType() == OrderType.MARKET) {
                    orderResponse = (JSONObject) ((JSONObject) o).get(tradeOpened);
                } else {
                    orderResponse = (JSONObject) ((JSONObject) o).get(orderOpened);
                }
                Long orderId = (Long) orderResponse.get(OandaJsonKeys.id);
                LOG.info("Order executed->" + strResp);
                return orderId;
            } else {
                return null;
            }

        } else {
            LOG.info(String.format("Order not executed. http code=%d. Order pojo->%s",
                    resp.getStatusLine().getStatusCode(), order.toString()));
            return null;
        }
    } catch (Exception e) {
        LOG.warn(e);
        return null;
    } finally {
        TradingUtils.closeSilently(httpClient);
    }
}

From source file:eu.hansolo.fx.weatherfx.darksky.DarkSky.java

public boolean update(final double LATITUDE, final double LONGITUDE) {
    // Update only if lastUpdate is older than 10 min
    if (Instant.now().minusSeconds(600).isBefore(lastUpdate))
        return true;

    StringBuilder response = new StringBuilder();
    try {/*from   w w  w.  ja  va2s .c o  m*/
        forecast.clear();
        alerts.clear();

        final String URL_STRING = createUrl(LATITUDE, LONGITUDE, unit, language, Exclude.HOURLY,
                Exclude.MINUTELY, Exclude.FLAGS);
        final HttpsURLConnection CONNECTION = (HttpsURLConnection) new URL(URL_STRING).openConnection();
        final BufferedReader IN = new BufferedReader(new InputStreamReader(CONNECTION.getInputStream()));
        String inputLine;
        while ((inputLine = IN.readLine()) != null) {
            response.append(inputLine).append("\n");
        }
        IN.close();

        Object obj = JSONValue.parse(response.toString());
        JSONObject jsonObj = (JSONObject) obj;

        latitude = Double.parseDouble(jsonObj.getOrDefault("latitude", 0).toString());
        longitude = Double.parseDouble(jsonObj.getOrDefault("longitude", 0).toString());
        timeZone = TimeZone.getTimeZone(jsonObj.getOrDefault("timezone", "").toString());

        // Update today data
        JSONObject currently = (JSONObject) jsonObj.get("currently");
        setDataPoint(today, currently);

        // Update forecast data
        JSONObject daily = (JSONObject) jsonObj.get("daily");
        JSONArray days = (JSONArray) daily.get("data");

        // Update today with more data
        JSONObject day0 = (JSONObject) days.get(0);
        today.setSunriseTime(epochStringToLocalDateTime(day0.getOrDefault("sunriseTime", 0).toString()));
        today.setSunsetTime(epochStringToLocalDateTime(day0.getOrDefault("sunsetTime", 0).toString()));
        today.setPrecipProbability(Double.parseDouble(day0.getOrDefault("precipProbability", 0).toString()));
        today.setPrecipType(PrecipType
                .valueOf(day0.getOrDefault("precipType", "none").toString().toUpperCase().replace("-", "_")));

        for (int i = 1; i < days.size(); i++) {
            JSONObject day = (JSONObject) days.get(i);
            DataPoint dataPoint = new DataPoint();
            setDataPoint(dataPoint, day);
            forecast.add(dataPoint);
        }

        // Update alert data
        if (jsonObj.containsKey("alerts")) {
            JSONArray alerts = (JSONArray) jsonObj.get("alerts");
            for (Object alertObj : alerts) {
                JSONObject alertJson = (JSONObject) alertObj;
                Alert alert = new Alert();
                alert.setTitle(alertJson.get("title").toString());
                alert.setDescription(alertJson.get("description").toString());
                alert.setTime(epochStringToLocalDateTime(alertJson.getOrDefault("time", 0).toString()));
                alert.setExpires(epochStringToLocalDateTime(alertJson.getOrDefault("expires", 0).toString()));
                alerts.add(alert);
            }
        }

        lastUpdate = Instant.now();

        return true;
    } catch (IOException ex) {
        System.out.println(ex);
        return false;
    }
}

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

private JSONObject getSpecificObject(final URIBuilder BUILDER) {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        HttpGet get = new HttpGet(BUILDER.build());

        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 v  a 2s.co  m*/

        String output = getFromResponse(response);
        JSONArray jsonArray = (JSONArray) JSONValue.parse(output);
        JSONObject jsonObject = jsonArray.size() > 0 ? (JSONObject) jsonArray.get(0) : new JSONObject();
        return jsonObject;
    } catch (URISyntaxException | IOException e) {
        return new JSONObject();
    }
}

From source file:com.treasure_data.client.bulkimport.BulkImportClientAdaptorImpl.java

private ShowSessionResult doShowSession(ShowSessionRequest request) throws ClientException {
    request.setCredentials(client.getTreasureDataCredentials());
    validator.validateCredentials(client, request);

    String jsonData = null;//w  w  w  . j ava2 s.  c  o  m
    String message = null;
    int code = 0;
    try {
        conn = createConnection();
        // send request
        String path = String.format(HttpURL.V3_SHOW, request.getSessionName());
        Map<String, String> header = new HashMap<String, String>();
        setUserAgentHeader(header);
        Map<String, String> params = null;
        conn.doGetRequest(request, path, header, params);
        // receive response code and body
        code = conn.getResponseCode();
        message = conn.getResponseMessage();
        if (code != HttpURLConnection.HTTP_OK) {
            String errMessage = conn.getErrorMessage();
            LOG.severe(HttpClientException.toMessage("Show session failed", message, code));
            LOG.severe(errMessage);
            throw new HttpClientException("Show session failed", message + ", detail = " + errMessage, code);
        }

        // receive response body
        jsonData = conn.getResponseBody();
        validator.validateJSONData(jsonData);
    } catch (IOException e) {
        LOG.throwing(getClass().getName(), "showSession", e);
        LOG.severe(HttpClientException.toMessage(e.getMessage(), message, code));
        throw new HttpClientException("Show session failed", message, code, e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    //json data: {
    //  "name":"session_17418",
    //  "status":"committed",
    //  "job_id":17432,
    //  "valid_records":10000000,
    //  "error_records":0,
    //  "valid_parts":39,
    //  "error_parts":0,
    //  "upload_frozen":true,
    //  "database":null,
    //  "table":null}

    @SuppressWarnings("rawtypes")
    Map sess = (Map) JSONValue.parse(jsonData);
    validator.validateJavaObject(jsonData, sess);
    String name = (String) sess.get("name");
    String database = (String) sess.get("database");
    String table = (String) sess.get("table");
    String status = (String) sess.get("status");
    Boolean uf = (Boolean) sess.get("upload_frozen");
    boolean upload_frozen = uf != null ? uf : false;
    String job_id = getJobID(sess);
    Long vr = (Long) sess.get("valid_records");
    long valid_records = vr != null ? vr : 0;
    Long er = (Long) sess.get("error_records");
    long error_records = er != null ? er : 0;
    Long vp = (Long) sess.get("valid_parts");
    long valid_parts = vp != null ? vp : 0;
    Long ep = (Long) sess.get("error_parts");
    long error_parts = ep != null ? ep : 0;

    SessionSummary summary = new SessionSummary(name, database, table, SessionSummary.Status.fromString(status),
            upload_frozen, job_id, valid_records, error_records, valid_parts, error_parts);
    return new ShowSessionResult(summary);
}

From source file:de.thejeterlp.bukkit.updater.Updater.java

/**
 * Index:/*  w  w  w .ja va  2 s .  c  o m*/
 * 0: downloadUrl
 * 1: name
 * 2: releaseType
 *
 * @return
 */
protected String[] read() {
    debug("Method: read()");
    try {
        URLConnection conn = url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setDoOutput(true);
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String response = reader.readLine();
        JSONArray array = (JSONArray) JSONValue.parse(response);
        if (array.size() == 0)
            return null;
        Map<?, ?> map = (Map) array.get(array.size() - 1);
        String downloadUrl = (String) map.get("downloadUrl");
        String name = (String) map.get("name");
        String releaseType = (String) map.get("releaseType");
        return new String[] { downloadUrl, name, releaseType };
    } catch (Exception e) {
        main.getLogger().severe("Error on trying to check remote versions. Error: " + e);
        return null;
    }
}

From source file:com.hortonworks.amstore.view.TaskManagerService.java

/**
 * Handles: DELETE /taskmanager/postupdatetasks Removes a task from the
 * list of tasks This is done because of BUG: a call to
 * viewContext.putInstanceData inside the servlet returns ERROR 500 after a
 * while./*  ww  w  . java  2 s .  c o  m*/
 * 
 * @param headers
 *            http headers
 * @param ui
 *            uri info
 *
 * @return the response
 */
@DELETE
@Path("/postupdatetasks/{uri}")
@Produces({ "text/html" })
public Response delPostUpdateTasks(@PathParam("uri") String uri, @Context HttpHeaders headers,
        @Context UriInfo ui) throws IOException {

    String response = "";
    try {

        String current = viewContext.getInstanceData("post-update-tasks");
        if (current == null)
            current = "[]";

        JSONArray array = (JSONArray) JSONValue.parse(current);
        array.remove(URLDecoder.decode(uri));

        viewContext.putInstanceData("post-update-tasks", array.toString());

        /*
         * } catch( ParseException pe){ System.out.println("position: " +
         * pe.getPosition()); System.out.println(pe); }
         */
    } catch (Exception e) {
        response += "Failed to remove: current=" + uri + "<br>";
        response += "Error in service: " + e.toString();
        return Response.ok(response).type("text/html").build();
    }

    String entity = "{ \"status\": \"ok\" }";
    return Response.ok(entity).type("text/html").build();
}

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

/**
 * Create a new time entry./*from w  ww .  ja v  a  2  s .c  om*/
 * 
 * @param timeEntry
 * @return created {@link TimeEntry}
 */
public TimeEntry createTimeEntry(TimeEntry timeEntry) {
    Client client = prepareClient();
    WebResource webResource = client.resource(TIME_ENTRIES);

    JSONObject object = createTimeEntryRequestParameter(timeEntry);
    String response = webResource.entity(object.toJSONString(), MediaType.APPLICATION_JSON_TYPE)
            .post(String.class);

    object = (JSONObject) JSONValue.parse(response);
    JSONObject data = (JSONObject) object.get(DATA);
    return new TimeEntry(data.toJSONString());
}

From source file:fromgate.weatherman.FGUtilCore.java

private void updateLastVersion() {
    if (!this.project_check_version)
        return;//from  w w w .j  a v  a  2  s  .c o  m
    URL url = null;
    try {
        url = new URL(this.project_curse_url);
    } catch (Exception e) {
        this.log("Failed to create URL: " + this.project_curse_url);
        return;
    }

    try {
        URLConnection conn = url.openConnection();
        conn.addRequestProperty("X-API-Key", null);
        conn.addRequestProperty("User-Agent", this.project_name + " using FGUtilCore (by fromgate)");
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String response = reader.readLine();
        JSONArray array = (JSONArray) JSONValue.parse(response);
        if (array.size() > 0) {
            JSONObject latest = (JSONObject) array.get(array.size() - 1);
            String plugin_name = (String) latest.get("name");
            this.project_last_version = plugin_name.replace(this.project_name + " v", "").trim();
            //String plugin_jar_url = (String) latest.get("downloadUrl");
            //this.project_file_url = plugin_jar_url.replace("http://servermods.cursecdn.com/", "http://dev.bukkit.org/media/");
        }
    } catch (Exception e) {
        this.log("Failed to check last version");
    }
}