Example usage for org.json.simple JSONObject containsKey

List of usage examples for org.json.simple JSONObject containsKey

Introduction

In this page you can find the example usage for org.json.simple JSONObject containsKey.

Prototype

boolean containsKey(Object key);

Source Link

Document

Returns true if this map contains a mapping for the specified key.

Usage

From source file:com.grantedbyme.example.ServletCallback.java

public void doProcess(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json; charset=UTF-8");
    // setup default response
    HashMap<String, Object> resultHashMap = new HashMap<>();
    resultHashMap.put("success", false);
    resultHashMap.put("error", 0);
    JSONObject result = null;//from ww  w.  j  av a  2s  . co m
    // get request parameters
    String reqSignature = request.getParameter("signature");
    String reqPayload = request.getParameter("payload");
    String reqMessage = request.getParameter("message");
    // process request
    if (reqSignature != null && reqPayload != null) {
        // read private key
        String privateKey = null;
        InputStream privateKeyInputStream = getClass().getResourceAsStream("/private_key.pem");
        try {
            privateKey = IOUtils.toString(privateKeyInputStream);
        } finally {
            privateKeyInputStream.close();
        }
        // read server key
        String serverKey = null;
        InputStream serverKeyInputStream = getClass().getResourceAsStream("/server_key.pem");
        try {
            serverKey = IOUtils.toString(serverKeyInputStream);
        } finally {
            serverKeyInputStream.close();
        }
        // _log(serverKey);
        // initialize BouncyCastle security provider
        Security.insertProviderAt(new org.bouncycastle.jce.provider.BouncyCastleProvider(), 0);
        // decrypt request
        HashMap<String, Object> params = new HashMap<>();
        params.put("signature", reqSignature);
        params.put("payload", reqPayload);
        params.put("message", reqMessage);
        /*System.out.println("Signature: " + reqSignature);
        System.out.println("Payload: " + reqPayload);
        System.out.println("Message: " + reqMessage);*/
        JSONObject requestJSON = CryptoUtil.decryptAndVerify(new JSONObject(params), serverKey, privateKey);
        if (requestJSON != null) {
            _log(requestJSON.toJSONString());
            if (requestJSON.containsKey("operation")) {
                String operation = (String) requestJSON.get("operation");
                if (operation.equals("ping")) {
                    resultHashMap.put("success", true);
                } else if (operation.equals("unlink_account")) {
                    if (requestJSON.containsKey("authenticator_secret_hash")) {
                        // TODO: implement
                    }
                    resultHashMap.put("success", false);
                } else if (operation.equals("rekey_account")) {
                    if (requestJSON.containsKey("authenticator_secret_hash")) {
                        // TODO: implement
                    }
                    resultHashMap.put("success", false);
                } else if (operation.equals("revoke_challenge")) {
                    if (requestJSON.containsKey("challenge")) {
                        // TODO: implement
                    }
                    resultHashMap.put("success", false);
                } else {
                    // operation not handled
                }
            }
        }
        result = CryptoUtil.encryptAndSign(new JSONObject(resultHashMap), serverKey, privateKey);
    }
    // write out response
    PrintWriter out = response.getWriter();
    if (result != null) {
        out.print(result.toJSONString());
    } else {
        out.print(new JSONObject(resultHashMap).toJSONString());
    }
    out.close();
}

From source file:com.framework.testcase.testrail.APIClient.java

private Object sendRequest(String method, String uri, Object data) throws MalformedURLException, IOException {
    URL url = new URL(this.m_url + uri);

    // Create the connection object and set the required HTTP method
    // (GET/POST) and headers (content type and basic auth).
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.addRequestProperty("Content-Type", "application/json");

    String auth = getAuthorization(this.m_user, this.m_password);
    conn.addRequestProperty("Authorization", "Basic " + auth);

    if (method.equalsIgnoreCase("POST")) {
        // Add the POST arguments, if any. We just serialize the passed
        // data object (i.e. a dictionary) and then add it to the
        // request body.
        if (data != null) {
            byte[] block = JSONValue.toJSONString(data).getBytes("UTF-8");

            conn.setDoOutput(true);/*  w w  w.  ja va 2  s  .c  om*/
            OutputStream ostream = conn.getOutputStream();
            ostream.write(block);
            ostream.flush();
        }
    }

    // Execute the actual web request (if it wasn't already initiated
    // by getOutputStream above) and record any occurred errors (we use
    // the error stream in this case).
    int status = 0;
    try {
        status = conn.getResponseCode();
    } catch (SocketTimeoutException e) {
        e.printStackTrace();
        System.err.println("the request is timeout from the server ,we quite the test");

    } catch (SSLHandshakeException ex) {
        ex.printStackTrace();
        System.err.println("the request is  Remote host closed connection during handshake");
    }

    InputStream istream;
    if (status != 200) {
        istream = conn.getErrorStream();
        if (istream == null) {

            new Exception("TestRail API return HTTP " + status + " (No additional error message received)");

        }
    } else {
        istream = conn.getInputStream();
    }

    // Read the response body, if any, and deserialize it from JSON.
    String text = "";
    if (istream != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(istream, "UTF-8"));

        String line;
        while ((line = reader.readLine()) != null) {
            text += line;
            text += System.getProperty("line.separator");
        }

        reader.close();
    }

    Object result;
    if (text != "") {
        result = JSONValue.parse(text);
    } else {
        result = new JSONObject();
    }

    // Check for any occurred errors and add additional details to
    // the exception message, if any (e.g. the error message returned
    // by TestRail).
    if (status != 200) {
        String error = "No additional error message received";
        if (result != null && result instanceof JSONObject) {
            JSONObject obj = (JSONObject) result;
            if (obj.containsKey("error")) {
                error = '"' + (String) obj.get("error") + '"';
            }
        }

        new Exception("TestRail API returned HTTP " + status + "(" + error + ")");
    }

    return result;
}

From source file:edu.pitt.dbmi.facebase.hd.FileManager.java

/** populates an ArrayList with Instruction objects using the JSON-formatted fb_queue.instructions column data
 * The JSON string (from the database) is keyed by "csv", "text" and "files" depending on the type of data. 
 * Instructions descendants (InstructionsCsv, InstructionsText, InstructionsFiles) are constructed. 
 * File objects are constructed (and stuffed into their container Instructions objects). 
 * As an example, the JSON shown here would result in 6 Instructions objects, 2 of each kind shown:
 * </ b>/*w  w  w.j  av  a 2s .c  om*/
 * <pre>
 * {
 *     "csv": [
 *         {
 *             "content": "SELECT name FROM user",
 *             "path": "/Data/User Names.csv"
 *         },
 *         {
 *             "content": "SELECT uid FROM user",
 *             "path": "/Data/User IDs.csv"
 *         }
 *     ],
 *     "text": [
 *         {
 *             "content": "Your data was retrieved on 11-02-2011 and has 28 missing values...",
 *             "path": "/Data/Summary.txt"
 *         },
 *         {
 *             "content": "The Facebase Data User Agreement specifies...",
 *             "path": "/FaceBase Agreement.txt"
 *         }
 *     ],
 *     "files": [
 *         {
 *             "content": "/path/on/server/1101.obj",
 *             "path": "/meshes/1101.obj"
 *         },
 *         {
 *             "content": "/path/on/server/1102.obj",
 *             "path": "/meshes/1102.obj"
 *         }
 *     ]
 * }
 * </pre>
 * </ b>
 * 
 * @param instructionsString the JSON from the data request.
 * @param ali the list of Instructions objects that will be populated during execution of this method.
 * @return true if Instructions object creation effort succeeds.
 */
public boolean makeInstructionsObjects(String instructionsString, ArrayList<Instructions> ali) {
    log.debug("FileManager.makeInstructionsObjects() called.");
    long unixEpicTime = System.currentTimeMillis() / 1000L;
    String unixEpicTimeString = (new Long(unixEpicTime)).toString();
    this.setDataName(dataNamePrefix + unixEpicTimeString);
    trueCryptPath = trueCryptBasePath + dataName + trueCryptExtension;
    trueCryptFilename = dataName + trueCryptExtension;
    trueCryptVolumePath = trueCryptBasePath + dataName + trueCryptMountpoint;
    File trueCryptVolumePathDir = new File(trueCryptVolumePath);
    if (!trueCryptVolumePathDir.isDirectory()) {
        trueCryptVolumePathDir.mkdirs();
    }
    JSONObject jsonObj = (JSONObject) JSONValue.parse(instructionsString);

    if (jsonObj.containsKey("csv")) {
        log.debug("FileManager.makeInstructionsObjects() has a csv.");
        JSONArray jsonCsvArray = (JSONArray) jsonObj.get("csv");
        if (jsonCsvArray.size() > 0) {
            for (Object jsonObjectCsvItem : jsonCsvArray) {
                JSONObject jsonObjSql = (JSONObject) jsonObjectCsvItem;
                String sqlString = (String) jsonObjSql.get("content");
                JSONObject jsonObjSqlPath = (JSONObject) jsonObjectCsvItem;
                String sqlPathString = (String) jsonObjSql.get("path");
                File file = new File(trueCryptBasePath + dataName + sqlPathString);
                InstructionsCsv i = new InstructionsCsv(sqlString, file, sqlPathString);
                ali.add(i);
            }
        }
    }

    if (jsonObj.containsKey("text")) {
        log.debug("FileManager.makeInstructionsObjects() has a text.");
        JSONArray jsonTextArray = (JSONArray) jsonObj.get("text");
        if (jsonTextArray.size() > 0) {
            for (Object jsonObjectTextItem : jsonTextArray) {
                JSONObject jsonObjText = (JSONObject) jsonObjectTextItem;
                String contentString = (String) jsonObjText.get("content");
                JSONObject jsonObjTextPath = (JSONObject) jsonObjectTextItem;
                String textPathString = (String) jsonObjText.get("path");
                File file = new File(trueCryptBasePath + dataName + textPathString);
                InstructionsText i = new InstructionsText(contentString, file, textPathString);
                ali.add(i);
            }
        }
    }

    if (jsonObj.containsKey("files")) {
        log.debug("FileManager.makeInstructionsObjects() has a files.");
        JSONArray jsonFilesArray = (JSONArray) jsonObj.get("files");
        if (jsonFilesArray.size() > 0) {
            for (Object jsonObjectFilesItem : jsonFilesArray) {
                JSONObject jsonObjFiles = (JSONObject) jsonObjectFilesItem;
                String serverPathString = (String) jsonObjFiles.get("content");
                JSONObject jsonObjFilesPath = (JSONObject) jsonObjectFilesItem;
                String archivePathString = (String) jsonObjFiles.get("path");
                File fileSource = new File(serverPathString);
                File fileDest = new File(trueCryptBasePath + dataName + archivePathString);
                InstructionsFiles i = new InstructionsFiles(fileSource, fileDest, archivePathString);
                ali.add(i);
            }
        }
    }
    return true;
}

From source file:cc.siara.csv_ml.ParsedObject.java

/**
 * Deletes all attributes with name "parent_ref" in all levels in a
 * JSONObject hierarchy recursively.//from  w ww  .jav  a 2  s.c o m
 * 
 * @param obj
 *            Initially pass the root object
 */
private void deleteParentRefsRecursively(JSONObject obj) {
    if (obj.containsKey("parent_ref"))
        obj.remove("parent_ref");
    // Go through each child object or array
    // recursively
    for (Object set : obj.keySet()) {
        String key = (String) set;
        Object child_obj = obj.get(key);
        if (child_obj instanceof JSONArray) {
            JSONArray ja = (JSONArray) child_obj;
            for (Object ele : ja) {
                if (ele instanceof JSONObject)
                    deleteParentRefsRecursively((JSONObject) ele);
            }
        } else if (child_obj instanceof JSONObject) {
            deleteParentRefsRecursively((JSONObject) child_obj);
        }
    }
}

From source file:functions.TestOptions.java

@Test
public void testJson() {
    try {/*  w w w.j ava 2s .co m*/
        JSONObject inputJSON = ParseOptions.parseSingleJsonFile(testconfig);

        assertTrue(inputJSON.containsKey("exchangename"));
    } catch (ParseException e) {
        // e.printStackTrace();
    }
}

From source file:com.linemetrics.monk.api.ApiClient.java

public List<DataItem> getRange(Number dataStreamId, final long time_from, final long time_to, final TDB tdb,
        final TimeZone tz) throws ApiException {

    List<DataItem> list = new ArrayList<>();

    Map<String, String> reqParameters = new HashMap<String, String>() {
        {//from   w w w .j a  v  a 2s .c o m
            put("tdb", "" + tdb.getMilliseconds());
            put("time_to", "" + time_to);
            put("time_from", "" + time_from);
            put("time_offset", "" + (tz.getRawOffset() + tz.getDSTSavings()));
        }
    };
    String reqURl = getBaseUri() + "/data/" + dataStreamId;

    System.out.print("URL: " + reqURl + " -> " + reqParameters);

    int retries = MAX_RETRIES;
    boolean isError = false;

    while (retries-- >= 0) {

        if (isError) {
            System.out.println("WAIT CAUSE OF ERROR AND RETRY (" + (MAX_RETRIES - retries) + ")...");
            try {
                Thread.sleep(WAIT_MILLIS_AFTER_ERROR);
            } catch (InterruptedException iexp) {
                //                    iexp.printStackTrace();
            }
        }

        long millis = System.currentTimeMillis();
        isError = false;

        try {
            URI uri = restclient.buildURI(reqURl, reqParameters);

            JSONObject result = restclient.get(uri);

            if (result.containsKey("data") && result.get("data") instanceof List) {
                for (Object dataItem : (List) result.get("data")) {
                    DataItem di = new DataItem(dataItem);
                    di.setTimestampEnd(di.getTimestampStart() + tdb.getMilliseconds());
                    list.add(di);
                }

                if (list.isEmpty()) {
                    System.out.print(" DATA BUT EMPTY ");
                }
                break;
            } else {
                System.out.print(" NO DATA ");
                isError = true;
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.print(" UNABLE: " + ex.getMessage());
            isError = true;
        } finally {
            System.out.println(": " + (System.currentTimeMillis() - millis) + "ms ");
        }
    }

    if (isError) {
        throw new ApiException("Unable to grab data");
    }

    Collections.sort(list, DataItemComparator.getInstance());

    DataItem currItem;

    Iterator<DataItem> itemIterator = list.iterator();
    while (itemIterator.hasNext()) {
        currItem = itemIterator.next();

        if (currItem.getTimestamp() < time_from || currItem.getTimestamp() > time_to) {

            itemIterator.remove();
        }
    }

    return list;
}

From source file:fr.bmartel.speedtest.test.SpeedTestServerTest.java

@Test
public void serverListTest() throws IOException, ParseException, TimeoutException {

    initSocket();/*from w ww .ja v a2 s .co m*/

    final URL url = getClass().getResource("/" + TestCommon.SERVER_LIST_FILENAME);

    final Object obj = new JSONParser().parse(new FileReader(url.getPath()));

    final JSONArray servers = (JSONArray) obj;

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

        final JSONObject serverObj = (JSONObject) servers.get(i);

        if (serverObj.containsKey("host")) {

            final String host = serverObj.get("host").toString();

            if (serverObj.containsKey("download")) {

                final JSONArray downloadEndpoints = (JSONArray) serverObj.get("download");

                for (int j = 0; j < downloadEndpoints.size(); j++) {

                    final JSONObject downloadEndpoint = (JSONObject) downloadEndpoints.get(j);

                    if (downloadEndpoint.containsKey("protocol")) {

                        final String protocol = downloadEndpoint.get("protocol").toString();

                        if (downloadEndpoint.containsKey("uri")) {

                            final String uri = downloadEndpoint.get("uri").toString();

                            switch (protocol) {
                            case "http":
                                System.out.println("[download] HTTP - testing " + host + " with uri " + uri);
                                mWaiter = new Waiter();
                                mSocket.startDownload(host, uri);
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                mWaiter = new Waiter();
                                mSocket.forceStopTask();
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                break;
                            case "ftp":

                                String username = SpeedTestConst.FTP_DEFAULT_USER;
                                String password = SpeedTestConst.FTP_DEFAULT_PASSWORD;

                                if (downloadEndpoint.containsKey("username")) {
                                    username = downloadEndpoint.get("username").toString();
                                }
                                if (downloadEndpoint.containsKey("password")) {
                                    password = downloadEndpoint.get("password").toString();
                                }
                                System.out.println("[download] FTP - testing " + host + " with uri " + uri);
                                mWaiter = new Waiter();
                                mSocket.startFtpDownload(host, SpeedTestConst.FTP_DEFAULT_PORT, uri, username,
                                        password);
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                mWaiter = new Waiter();
                                mSocket.forceStopTask();
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                break;
                            default:
                                break;
                            }

                        } else {
                            Assert.fail("download for host " + host + " has no uri");
                        }
                    } else {
                        Assert.fail("download for host " + host + " has no protocol");
                    }
                }
            }
            if (serverObj.containsKey("upload")) {

                final JSONArray uploadEndpoints = (JSONArray) serverObj.get("upload");

                for (int j = 0; j < uploadEndpoints.size(); j++) {

                    final JSONObject uploadEndpoint = (JSONObject) uploadEndpoints.get(j);

                    if (uploadEndpoint.containsKey("protocol")) {

                        final String protocol = uploadEndpoint.get("protocol").toString();

                        if (uploadEndpoint.containsKey("uri")) {

                            final String uri = uploadEndpoint.get("uri").toString();

                            switch (protocol) {
                            case "http":
                                System.out.println("[upload] HTTP - testing " + host + " with uri " + uri);
                                mWaiter = new Waiter();
                                mSocket.startUpload(host, uri, TestCommon.FILE_SIZE_LARGE);
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                mWaiter = new Waiter();
                                mSocket.forceStopTask();
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                break;
                            case "ftp":
                                String username = SpeedTestConst.FTP_DEFAULT_USER;
                                String password = SpeedTestConst.FTP_DEFAULT_PASSWORD;

                                if (uploadEndpoint.containsKey("username")) {
                                    username = uploadEndpoint.get("username").toString();
                                }
                                if (uploadEndpoint.containsKey("password")) {
                                    password = uploadEndpoint.get("password").toString();
                                }
                                System.out.println("[upload] FTP - testing " + host + " with uri " + uri);
                                final String fileName = generateFileName() + ".txt";
                                mWaiter = new Waiter();
                                mSocket.startFtpUpload(host, SpeedTestConst.FTP_DEFAULT_PORT,
                                        uri + "/" + fileName, TestCommon.FILE_SIZE_LARGE, username, password);
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                mWaiter = new Waiter();
                                mSocket.forceStopTask();
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                break;
                            default:
                                break;
                            }

                        } else {
                            Assert.fail("upload for host " + host + " has no uri");
                        }

                    } else {
                        Assert.fail("upload for host " + host + " has no protocol");
                    }
                }
            }
        }
    }

    mSocket.clearListeners();
}

From source file:functionaltests.RestSchedulerTagTest.java

@Test
public void testTaskResultValueByTag() throws Exception {
    HttpResponse response = sendRequest("jobs/" + submittedJobId + "/tasks/tag/LOOP-T2-1/result/value");
    JSONObject jsonObject = toJsonObject(response);

    System.out.println(jsonObject.toJSONString());

    assertTrue(jsonObject.containsKey("T1#1"));
    assertTrue(jsonObject.containsKey("Print1#1"));
    assertTrue(jsonObject.containsKey("Print2#1"));
    assertTrue(jsonObject.containsKey("T2#1"));
    assertEquals(4, jsonObject.size());//  ww w.j  a va 2s.  c om
}

From source file:functionaltests.RestSchedulerTagTest.java

@Test
public void testTaskResultSerializedvalueByTag() throws Exception {
    HttpResponse response = sendRequest(
            "jobs/" + submittedJobId + "/tasks/tag/LOOP-T2-1/result/serializedvalue");
    JSONObject jsonObject = toJsonObject(response);

    System.out.println(jsonObject.toJSONString());

    assertTrue(jsonObject.containsKey("T1#1"));
    assertTrue(jsonObject.containsKey("Print1#1"));
    assertTrue(jsonObject.containsKey("Print2#1"));
    assertTrue(jsonObject.containsKey("T2#1"));
    assertEquals(4, jsonObject.size());//from  ww  w  . j  a  va2s  .  co  m
}

From source file:com.orthancserver.DicomDecoder.java

private String[] SortSlicesBy3D(OrthancConnection c, JSONArray instances) throws IOException {
    ArrayList<Slice> slices = new ArrayList<Slice>();
    float normal[] = null;

    float minDistance = Float.POSITIVE_INFINITY;
    float maxDistance = Float.NEGATIVE_INFINITY;

    for (int i = 0; i < instances.size(); i++) {
        String uuid = (String) instances.get(i);
        JSONObject instance = (JSONObject) c.ReadJson("/instances/" + uuid + "/tags?simplify");
        if (!instance.containsKey("ImageOrientationPatient") || !instance.containsKey("ImagePositionPatient")) {
            return null;
        }/*from w ww.j  a  v a  2  s. c  o m*/

        if (i == 0) {
            String[] tokens = ((String) instance.get("ImageOrientationPatient")).split("\\\\");
            if (tokens.length != 6) {
                return null;
            }

            float cosines[] = new float[6];
            for (int j = 0; j < 6; j++) {
                cosines[j] = Float.parseFloat(tokens[j]);
            }

            normal = new float[] { cosines[1] * cosines[5] - cosines[2] * cosines[4],
                    cosines[2] * cosines[3] - cosines[0] * cosines[5],
                    cosines[0] * cosines[4] - cosines[1] * cosines[3] };
        }

        String[] tokens = ((String) instance.get("ImagePositionPatient")).split("\\\\");
        if (tokens.length != 3) {
            return null;
        }

        float distance = 0;
        for (int j = 0; j < 3; j++) {
            distance += normal[j] * Float.parseFloat(tokens[j]);
        }

        minDistance = Math.min(minDistance, distance);
        maxDistance = Math.max(minDistance, distance);
        slices.add(new Slice(distance, uuid));
    }

    if (maxDistance - minDistance < 0.001) {
        return null;
    }

    return SortSlices(slices);
}