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:ch.simas.jtoggl.JToggl.java

/**
 * All projects in the workspace with the given id.
 * /*from w  w  w  . j  a va 2  s .com*/
 * @param workspaceId
 *            id of the workspace
 * @return all projects
 */
public List<Project> getWorkspaceProjects(long workspaceId) {
    Client client = prepareClient();
    String url = WORKSPACE_PROJECTS.replace(PLACEHOLDER, String.valueOf(workspaceId));
    WebResource webResource = client.resource(url);

    String response = webResource.get(String.class);
    JSONArray data = (JSONArray) JSONValue.parse(response);

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

From source file:importer.handler.post.stages.StageThreeXML.java

boolean verifyCorCode(String stil, String text) {
    JSONObject jObj = (JSONObject) JSONValue.parse(stil);
    JSONArray ranges = (JSONArray) jObj.get(JSONKeys.RANGES);
    int offset = 0;
    for (int i = 0; i < ranges.size(); i++) {
        JSONObject range = (JSONObject) ranges.get(i);
        offset += ((Number) range.get("reloff")).intValue();
        int len = ((Number) range.get("len")).intValue();
        if (offset + len > text.length())
            return false;
    }/*from   ww w  .j  a va 2 s. c  om*/
    return true;
}

From source file:com.bchalk.GVCallback.callback.GVCommunicator.java

public boolean saveSettings(Map<String, String> map) {
    if (!isLoggedIn()) {
        if (!login()) {
            return false;
        }//from   w w w.j  a v a 2 s . c o m
    }
    try {
        HttpPost post = new HttpPost(BASE + "/voice/settings/editGeneralSettings");
        List<BasicNameValuePair> data = new ArrayList<BasicNameValuePair>();

        data.add(new BasicNameValuePair("_rnr_se", myToken));
        for (String key : map.keySet()) {
            data.add(new BasicNameValuePair(key, map.get(key)));
        }

        post.setEntity(new UrlEncodedFormEntity(data));

        HttpResponse response = myClient.execute(post);
        String rsp = getContent(response.getEntity());
        JSONObject val = (JSONObject) JSONValue.parse(rsp);
        return (Boolean) val.get("ok");
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return true;
}

From source file:fr.bmartel.bboxapi.BboxApi.java

/**
 * //from w  w w  . ja v  a2 s  .c  om
 * Retrieve full call log
 * 
 * @param listener
 *            listener for request result / failure
 * 
 * @return true if request has been successfully initiated
 */
@Override
public boolean getFullCallLog(final IFullCallLogListener listener) {

    ClientSocket clientSocket = new ClientSocket("gestionbbox.lan", 80);

    clientSocket.addClientSocketEventListener(new IHttpClientListener() {

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

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

                // this is data coming from the server
                if (frame.getStatusCode() == 200) {

                    String data = new String(frame.getBody().getBytes());

                    JSONArray obj = (JSONArray) JSONValue.parse(data);

                    if (obj.size() > 0) {

                        JSONObject item = (JSONObject) obj.get(0);
                        if (item.containsKey("calllog")) {

                            JSONArray sub_item = (JSONArray) item.get("calllog");

                            List<CallLog> logList = new ArrayList<CallLog>();

                            for (int i = 0; i < sub_item.size(); i++) {

                                JSONObject callItem = (JSONObject) sub_item.get(i);

                                if (callItem.containsKey("id") && callItem.containsKey("number")
                                        && callItem.containsKey("date") && callItem.containsKey("type")
                                        && callItem.containsKey("answered") && callItem.containsKey("duree")) {

                                    int id = Integer.parseInt(callItem.get("id").toString());
                                    String number = callItem.get("number").toString();
                                    long date = Long.parseLong(callItem.get("date").toString());
                                    String type = callItem.get("type").toString();
                                    int answered = Integer.parseInt(callItem.get("answered").toString());
                                    int duree = Integer.parseInt(callItem.get("duree").toString());
                                    boolean isAnswered = false;

                                    if (answered == 1)
                                        isAnswered = true;

                                    logList.add(new CallLog(id, number, date, CallType.getValue(type),
                                            isAnswered, duree));
                                }
                            }

                            listener.onFullCallLogReceived(logList);
                            clientSocket.closeSocket();

                            return;
                        }
                    }

                }
                listener.onFullCallLogFailure();
                clientSocket.closeSocket();
            }
        }

        @Override
        public void onSocketError() {

            listener.onFullCallLogFailure();

        }
    });

    HashMap<String, String> headers = new HashMap<String, String>();

    headers.put("Accept", "*/*");
    headers.put("Host", "gestionbbox.lan");
    headers.put("Cookie", token_header);
    HttpFrame frameRequest = new HttpFrame(HttpMethod.GET_REQUEST, new HttpVersion(1, 1), headers,
            "/api/v1/voip/fullcalllog/1", new ListOfBytes(""));

    clientSocket.write(frameRequest.toString().getBytes());

    return false;
}

From source file:mml.handler.get.MMLGetMMLHandler.java

/**
 * Handle the request/*  w ww .j  av  a  2 s .  com*/
 * @param request the request
 * @param response the response
 * @param urn the remaining urn of the request
 * @throws MMLException 
 */
public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws MMLException {
    try {
        docid = request.getParameter(Params.DOCID);
        if (docid == null)
            throw new Exception("You must specify a docid parameter");
        version1 = request.getParameter(Params.VERSION1);
        ScratchVersion cortex, corcodeDefault, corcodePages;
        cortex = Scratch.getVersion(docid, version1, Database.CORTEX);
        corcodeDefault = Scratch.getVersion(docid + "/default", version1, Database.CORCODE);
        corcodePages = Scratch.getVersion(docid + "/pages", version1, Database.CORCODE);
        String shortID = shortenDocID(docid);
        String dialectStr = getDialect(shortID, version1);
        this.dialect = (JSONObject) JSONValue.parse(dialectStr);
        globals = new HashMap<Character, String>();
        buildLineFormats();
        invertDialect();
        //printInvertIndex();
        int[] layers = cortex.getLayerNumbers();
        Arrays.sort(layers);
        JSONObject jObj = new JSONObject();
        jObj.put(JSONKeys.VERSION1, version1);
        JSONArray jArr = new JSONArray();
        jObj.put(JSONKeys.LAYERS, jArr);
        for (int i = 0; i < layers.length; i++) {
            createMML(cortex, corcodeDefault, corcodePages, layers[i]);
            ScratchLayer sl = new ScratchLayer(mml.toString(), ScratchVersion.simpleLayerName(layers[i]));
            jArr.add(sl.toJSONObject());
        }
        response.setContentType("application/json");
        response.setCharacterEncoding(encoding);
        String jStr = jObj.toJSONString();
        response.getWriter().println(jStr);
        //System.out.println(jObj.toJSONString());
    } catch (Exception e) {
        throw new MMLException(e);
    }
}

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

private DeleteDatabaseResult doDeleteDatabase(DeleteDatabaseRequest request) throws ClientException {
    request.setCredentials(getConfig().getCredentials());
    validator.validateCredentials(this, request);

    String jsonData = null;/*from  w w  w  . j  av  a2s  .  c o m*/
    int code = 0;
    String message = null;
    try {
        conn = createConnection();

        // send request
        String path = String.format(HttpURL.V3_DATABASE_DELETE,
                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("Delete database failed", message, code));
            LOG.severe(errMessage);
            throw new HttpClientException("Delete database failed", message + ", detail = " + errMessage, code);
        }

        // receive response body
        jsonData = conn.getResponseBody();
        validator.validateJSONData(jsonData);
    } catch (IOException e) {
        LOG.throwing(getClass().getName(), "deleteDatabase", e);
        LOG.severe(HttpClientException.toMessage(e.getMessage(), message, code));
        throw new HttpClientException("Delete 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);

    return new DeleteDatabaseResult(request.getDatabase());
}

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

/**
 * All clients in the workspace with the given id.
 * //from w  ww.ja v a  2  s.  c o  m
 * @param workspaceId
 *            id of the workspace
 * @return all clients
 */
public List<ch.simas.jtoggl.Client> getWorkspaceClients(long workspaceId) {
    Client client = prepareClient();
    String url = WORKSPACE_CLIENTS.replace(PLACEHOLDER, String.valueOf(workspaceId));
    WebResource webResource = client.resource(url);

    String response = webResource.get(String.class);
    JSONArray data = (JSONArray) JSONValue.parse(response);

    List<ch.simas.jtoggl.Client> clients = new ArrayList<ch.simas.jtoggl.Client>();
    if (data != null) {
        for (Object obj : data) {
            JSONObject entryObject = (JSONObject) obj;
            clients.add(new ch.simas.jtoggl.Client(entryObject.toJSONString()));
        }
    }
    return clients;
}

From source file:mml.handler.get.MMLGetMMLHandler.java

/**
 * Is this piece of text JSON?/*  w  ww .ja  v a2  s  . c  o m*/
 * @param text the text to test
 * @return true if it was else false
 */
private static boolean isJSON(String text) {
    try {
        Object res = JSONValue.parse(text);
        if (res == null)
            return false;
    } catch (Exception e) {
        return false;
    }
    return true;
}

From source file:net.emotivecloud.scheduler.drp4ost.DRP4OST.java

/**
 * Returns the private IPs associated to the server ID
 *
 * @param vmID//  ww w . j a v  a 2 s . c o  m
 * @return
 */
public String[] getIPs(String serverID) {

    ArrayList<String> ips = new ArrayList<String>();
    String serverDetails = null;
    String status = "UNKNOWN";

    // Until VM has ACTIVE status, no IP is assigned
    while (!status.equals("ACTIVE")) {
        serverDetails = oStackClient.getServer(serverID);
        status = oStackClient.getVMStatus(serverID);
        System.out.println("DRP4OST>DRP4OST.getIPs(), VM has status=" + status);
        try {
            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Parsing the JSON response to get all the images
    JSONObject allFlavors = (JSONObject) JSONValue.parse(serverDetails);
    JSONObject jsonServer = (JSONObject) allFlavors.get("server");
    JSONObject jsonAddresses = (JSONObject) jsonServer.get("addresses");
    JSONArray jsonPrivate = (JSONArray) jsonAddresses.get("private");

    for (int i = 0; i < jsonPrivate.size(); ++i) {
        JSONObject addr = (JSONObject) jsonPrivate.get(i);
        String tmpAddr = addr.get("addr").toString();
        ips.add(tmpAddr);
        System.out.println("DRP4OST>DRP4OST.getIPs(), VM has ip=" + tmpAddr);
    }

    String[] ipsArray = ips.toArray(new String[ips.size()]);
    return ipsArray;

}

From source file:bbdn.lti2.LTI2Servlet.java

@SuppressWarnings("unused")
public void handleSettingsRequest(HttpServletRequest request, HttpServletResponse response, String[] parts)
        throws java.io.IOException {

    String URL = request.getRequestURL().toString();
    System.out.println("URL=" + URL);
    String scope = parts[4];/*from   ww w  . j  a v a2s .  co m*/
    System.out.println("scope=" + scope);

    String acceptHdr = request.getHeader("Accept");
    String contentHdr = request.getContentType();
    boolean acceptComplex = acceptHdr == null || acceptHdr.indexOf(StandardServices.TOOLSETTINGS_FORMAT) >= 0;

    System.out.println("accept=" + acceptHdr + " ac=" + acceptComplex);

    // Check the JSON on PUT and check the oauth_body_hash
    IMSJSONRequest jsonRequest = null;
    JSONObject requestData = null;
    if ("PUT".equals(request.getMethod())) {
        try {
            jsonRequest = new IMSJSONRequest(request);
            requestData = (JSONObject) JSONValue.parse(jsonRequest.getPostBody());
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            doErrorJSON(request, response, jsonRequest, "Could not parse JSON", e);
            return;
        }
    }

    String consumer_key = "42";
    String profile = (String) PERSIST.get("profile");
    JSONObject providerProfile = (JSONObject) JSONValue.parse(profile);
    JSONObject security_contract = (JSONObject) providerProfile.get(LTI2Constants.SECURITY_CONTRACT);
    String oauth_secret = (String) security_contract.get(LTI2Constants.SHARED_SECRET);

    // Validate the incoming message
    Object retval = BasicLTIUtil.validateMessage(request, URL, oauth_secret, consumer_key);
    if (retval instanceof String) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        doErrorJSON(request, response, jsonRequest, (String) retval, null);
        return;
    }

    // The URLs for the various settings resources
    String settingsUrl = getServiceURL(request) + SVC_Settings;
    String proxy_url = settingsUrl + "/" + LTI2Util.SCOPE_ToolProxy + "/" + consumer_key;
    String binding_url = settingsUrl + "/" + LTI2Util.SCOPE_ToolProxyBinding + "/" + "TBD";
    String link_url = settingsUrl + "/" + LTI2Util.SCOPE_LtiLink + "/" + "TBD";

    // Load and parse the old settings...
    JSONObject link_settings = LTI2Util.parseSettings((String) PERSIST.get(LTI2Util.SCOPE_LtiLink));
    JSONObject binding_settings = LTI2Util.parseSettings((String) PERSIST.get(LTI2Util.SCOPE_ToolProxyBinding));
    JSONObject proxy_settings = LTI2Util.parseSettings((String) PERSIST.get(LTI2Util.SCOPE_ToolProxy));

    // For a GET request we depend on LTI2Util to do the GET logic
    if ("GET".equals(request.getMethod())) {
        Object obj = LTI2Util.getSettings(request, scope, link_settings, binding_settings, proxy_settings,
                link_url, binding_url, proxy_url);

        if (obj instanceof String) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            doErrorJSON(request, response, jsonRequest, (String) obj, null);
            return;
        }

        if (acceptComplex) {
            response.setContentType(StandardServices.TOOLSETTINGS_FORMAT);
        } else {
            response.setContentType(StandardServices.TOOLSETTINGS_SIMPLE_FORMAT);
        }

        JSONObject jsonResponse = (JSONObject) obj;
        response.setStatus(HttpServletResponse.SC_OK);
        PrintWriter out = response.getWriter();
        System.out.println("jsonResponse=" + jsonResponse);
        out.println(jsonResponse.toString());
        return;
    } else if ("PUT".equals(request.getMethod())) {
        // This is assuming the rule that a PUT of the complex settings
        // format that there is only one entry in the graph and it is
        // the same as our current URL.  We parse without much checking.
        String settings = null;
        try {
            JSONArray graph = (JSONArray) requestData.get(LTI2Constants.GRAPH);
            if (graph.size() != 1) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                doErrorJSON(request, response, jsonRequest, "Only one graph entry allowed", null);
                return;
            }
            JSONObject firstChild = (JSONObject) graph.get(0);
            JSONObject custom = (JSONObject) firstChild.get(LTI2Constants.CUSTOM);
            settings = custom.toString();
        } catch (Exception e) {
            settings = jsonRequest.getPostBody();
        }
        PERSIST.put(scope, settings);
        System.out.println("Stored settings scope=" + scope);
        System.out.println("settings=" + settings);
        response.setStatus(HttpServletResponse.SC_OK);
    } else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "Method not handled=" + request.getMethod(), null);
    }
}