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.bchalk.GVCallback.callback.GVCommunicator.java

public JSONObject getSettings() {
    if (!isLoggedIn()) {
        if (!login()) {
            return null;
        }// w  w  w  . ja va  2s.co m
    }
    try {
        HttpGet get = new HttpGet(BASE + "/voice/settings/tab/phones");
        HttpResponse response = myClient.execute(get);
        String json = getJSON(response.getEntity());
        return (JSONObject) JSONValue.parse(json);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:be.cytomine.client.Cytomine.java

public void downloadFile(String url, String dest) throws CytomineException {

    try {//from   w  w w . jav  a2s .c om
        HttpClient client = new HttpClient(publicKey, privateKey, getHost());
        int code = client.get(getHost() + url, dest);
        analyzeCode(code, (JSONObject) JSONValue.parse("{}"));
    } catch (Exception e) {
        throw new CytomineException(0, e.toString());
    }
}

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

/**
 * Update a task.// ww w  .j a v a2  s.c o m
 * 
 * @param task
 * @return updated {@link Task}
 */
public Task updateTask(Task task) {
    Client client = prepareClient();
    String url = TASK.replace(PLACEHOLDER, task.getId().toString());
    WebResource webResource = client.resource(url);

    JSONObject object = createTaskRequestParameter(task);
    String response = webResource.entity(object.toJSONString(), MediaType.APPLICATION_JSON_TYPE)
            .put(String.class);

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

From source file:at.nonblocking.cliwix.cli.CliwixCliClient.java

private static JSONObject getJson(String serverUrl, String path) {
    if (debug)/* w w w . j  a  va2s .c o  m*/
        console.println("Sending GET request: " + path);
    Response response = getHandler.get(serverUrl, path, cookieManager);
    handleError(response);

    JSONObject obj = null;
    try {
        String infoResponseJson = response.getResponseAsString();
        if (debug)
            console.println("Received: " + infoResponseJson);
        return (JSONObject) JSONValue.parse(infoResponseJson);
    } catch (IOException e) {
        if (debug)
            console.printStacktrace(e);
        console.printlnError("Error: " + e.getMessage());
        console.exit(EXIT_STATUS_FAIL);
    } finally {
        response.disconnect();
    }

    return null;
}

From source file:com.treasure_data.client.DefaultClientAdaptorImpl.java

private CreateDatabaseResult doCreateDatabase(CreateDatabaseRequest request) throws ClientException {
    validator.validateDatabaseName(request.getDatabaseName());
    request.setCredentials(getConfig().getCredentials());
    validator.validateCredentials(this, request);

    String jsonData = null;/*from w ww  . j  ava 2 s  .c om*/
    int code = 0;
    String message = null;
    try {
        conn = createConnection();

        // send request
        String path = String.format(HttpURL.V3_DATABASE_CREATE,
                HttpConnectionImpl.e(request.getDatabaseName()));
        Map<String, String> header = new HashMap<String, String>();
        setUserAgentHeader(header);
        Map<String, String> params = null;
        conn.doPostRequest(request, path, header, params);

        // receive response code
        code = conn.getResponseCode();
        message = conn.getResponseMessage();
        if (code != HttpURLConnection.HTTP_OK) {
            String errMessage = conn.getErrorMessage();
            LOG.severe(HttpClientException.toMessage("Create database failed", message, code));
            LOG.severe(errMessage);
            throw new HttpClientException("Create database failed", message + ", detail = " + errMessage, code);
        }

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

    // parse JSON data
    @SuppressWarnings("unchecked")
    Map<String, String> dbMap = (Map<String, String>) JSONValue.parse(jsonData);
    validator.validateJavaObject(jsonData, dbMap);
    String dbName = dbMap.get("database");

    return new CreateDatabaseResult(new Database(dbName));
}

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

/**
 * Get current user./*from   w  ww .  j  a va  2 s . co m*/
 * 
 * @return current user {@link User}
 */
public User getCurrentUser() {
    Client client = prepareClient();
    WebResource webResource = client.resource(GET_CURRENT_USER);

    String response = webResource.get(String.class);
    JSONObject object = (JSONObject) JSONValue.parse(response);
    JSONObject data = (JSONObject) object.get(DATA);

    return new User(data.toJSONString());
}

From source file:at.nonblocking.cliwix.cli.CliwixCliClient.java

private static JSONObject postJson(String serverUrl, String path, JSONObject request) {
    String requestString = JSONValue.toJSONString(request);

    if (debug)//from   w  w w  .jav  a2 s.com
        console.println("Sending: " + requestString);
    Response response = postHandler.post(serverUrl, path, new ByteArrayInputStream(requestString.getBytes()),
            requestString.length(), CONTENT_TYPE.JSON, null, null, cookieManager);
    handleError(response);

    JSONObject obj = null;
    try {
        String exportResult = response.getResponseAsString();
        if (debug)
            console.println("Received: " + exportResult);
        return (JSONObject) JSONValue.parse(exportResult);
    } catch (IOException e) {
        if (debug)
            console.printStacktrace(e);
        console.printlnError("Error: " + e.getMessage());
        console.exit(EXIT_STATUS_FAIL);
    } finally {
        response.disconnect();
    }

    return null;
}

From source file:com.ge.research.semtk.sparqlX.SparqlEndpointInterface.java

/**
 * Execute an auth query using POST//from  w ww .  j av a 2  s  .co  m
 * @return a JSONObject wrapping the results. in the event the results were tabular, they can be obtained in the JsonArray "@Table". if the results were a graph, use "@Graph" for json-ld
 * @throws Exception
 */
private JSONObject executeQueryAuthPost(String query, SparqlResultTypes resultType) throws Exception {

    if (resultType == null) {
        resultType = getDefaultResultType();
    }

    DefaultHttpClient httpclient = new DefaultHttpClient();

    httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(this.userName, this.password));

    String[] serverNoProtocol = this.server.split("://");
    //System.err.println("the new server name is: " + serverNoProtocol[1]);

    HttpHost targetHost = new HttpHost(serverNoProtocol[1], Integer.valueOf(this.port), "http");

    DigestScheme digestAuth = new DigestScheme();
    AuthCache authCache = new BasicAuthCache();
    digestAuth.overrideParamter("realm", "SPARQL");
    // Suppose we already know the expected nonce value
    digestAuth.overrideParamter("nonce", "whatever");
    authCache.put(targetHost, digestAuth);
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    // add new stuff
    HttpPost httppost = new HttpPost(getPostURL());
    String resultsFormat = this.getContentType(resultType);
    httppost.addHeader("Accept", resultsFormat);
    httppost.addHeader("X-Sparql-default-graph", this.dataset);

    // add params
    List<NameValuePair> params = new ArrayList<NameValuePair>(3);
    params.add(new BasicNameValuePair("query", query));
    params.add(new BasicNameValuePair("format", resultsFormat));
    params.add(new BasicNameValuePair("default-graph-uri", this.dataset));

    httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

    // finish new stuff

    HttpResponse response_http = httpclient.execute(targetHost, httppost, localcontext);
    HttpEntity entity = response_http.getEntity();
    String responseTxt = EntityUtils.toString(entity, "UTF-8");

    // some diagnostic output
    if (responseTxt == null) {
        System.err.println("the response text was null!");
    }

    if (responseTxt.trim().isEmpty()) {
        handleEmptyResponse(); // implementation-specific behavior
    }

    JSONObject resp;
    try {
        resp = (JSONObject) JSONValue.parse(responseTxt);
    } catch (Exception e) {
        entity.getContent().close();
        throw new Exception("Cannot parse query result into JSON: " + responseTxt);
    }

    if (resp == null) {
        System.err.println("the response could not be transformed into json");

        if (responseTxt.contains("Error")) {
            entity.getContent().close();
            throw new Exception(responseTxt);
        }
        entity.getContent().close();
        return null;
    } else {
        JSONObject procResp = getResultsFromResponse(resp, resultType);
        entity.getContent().close();

        return procResp;
    }
}

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

/**
 * Returns a list of the most popular tags.
 * //from   w w w .jav a2s.c o  m
 * @param numberOfTags
 *            the number of popular tags to return.
 * @return the most popular tags or null if an error occurred.
 */
@Deprecated
@SuppressWarnings("unchecked")
public static JSONArray getMostPopularTagsOld(int numberOfTags) {

    // check the parameters
    if (numberOfTags <= 0) {
        return null;
    }

    // the json array to return
    JSONArray toreturn = new JSONArray();

    // the array to store rating values
    double[] ratingValues = new double[numberOfTags];
    // even tough Java does it automatically, we set the values to zero
    for (int i = 0; i < ratingValues.length; i++) {
        ratingValues[i] = 0.0;
    }

    // a help array for the package ratings
    HashMap<String, Double> packageRatings = new HashMap<String, Double>();

    // prepare the REST API call
    String RESTcall = "api/rest/tag";

    try {
        // run the REST call to obtain all tags
        String tagListString = connectorInstance.restCallWithAuthorization(RESTcall, null);
        if (tagListString == 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(tagListString);
        JSONArray array = (JSONArray) obj;

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

            // pick the tag name
            String tagName = (String) array.get(i);

            // run the REST call to obtain all packages for the tag in
            // question
            String tRESTcall = RESTcall + "/" + tagName;
            String pListString = connectorInstance.restCallWithAuthorization(tRESTcall, null);

            if (pListString == null) {
                log.log(Level.SEVERE, "Failed to realize api call \"" + url + RESTcall + "\" !!!");
                return null;
            }

            // parse the JSON string
            Object pObj = JSONValue.parse(pListString);
            JSONArray pArray = (JSONArray) pObj;

            // iterate over the JSON array
            double tagRating = 0.0;
            for (int j = 0; j < pArray.size(); j++) {
                // pick the name of the package
                String pName = (String) (pArray.get(j));

                // check whether the average rating value has already been
                // obtained
                Double aRatingValueD = packageRatings.get(pName);

                if (aRatingValueD == null) {
                    // in case it was not obtained until now --> get it and
                    // store it locally
                    double aRatingValue = CKANGatewayUtil.getDataSetRatingsAverage(pName);
                    aRatingValueD = new Double(aRatingValue);
                    packageRatings.put(pName, aRatingValueD);
                }

                // update the tag rating
                tagRating += aRatingValueD.doubleValue();
            }

            // update the toreturn array
            if (toreturn.size() < numberOfTags) {
                toreturn.add(tagName);
                ratingValues[toreturn.size() - 1] = tagRating;

            } else {
                // get the smallest value in the rating values
                int minIndex = minDoubleArray(ratingValues);
                if (ratingValues[minIndex] < tagRating) {
                    ratingValues[minIndex] = tagRating;
                    toreturn.set(minIndex, tagName);
                }
            }
        }
    }
    // catch potential exceptions
    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:net.emotivecloud.scheduler.drp4ost.DRP4OST.java

@GET
@Path("/resources")
@Produces("application/xml")
public ListStrings getNodes() {
    ListStrings list = new ListStrings();
    ArrayList<String> hostsNames = new ArrayList<String>();

    String hosts = oStackClient.getHosts();
    JSONObject jsonHosts = (JSONObject) JSONValue.parse(hosts);
    JSONArray jsonHostsArray = (JSONArray) jsonHosts.get("hosts");

    for (int i = 0; i < jsonHostsArray.size(); ++i) {
        JSONObject flavor = (JSONObject) jsonHostsArray.get(i);
        String hostName = flavor.get("host_name").toString();
        hostsNames.add(hostName);/*from  w  ww.  j  a v  a2s .co  m*/
    }

    list.addAll(hostsNames);

    //        list.addAll(super.getNodes());
    //GenericEntity<ListStrings> entity = new GenericEntity<ListStrings>(list) {};
    //Response response = Response.ok(entity).build();
    return list;
}