Example usage for org.json.simple JSONObject get

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

Introduction

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

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:net.paissad.minus.api.MinusUtils.java

/**
 * Retrieves items from a gallery.//from  w  ww  . jav a 2 s .c  o m
 * 
 * @param user - The user who want to retrieve items.
 * @param gallery - The gallery for which we want to retrieve its items.
 * @param listener
 * @return The list of items stored in the specified gallery.
 * @throws MinusException
 * @see MinusGallery#getReaderId()
 */
static List<MinusItem> getItems(final MinusUser user, MinusGallery gallery,
        final MinusListener<Map<String, Object>> listener) throws MinusException {

    if (user == null) {
        throw new IllegalArgumentException("The user for who to download items cannot be null.");
    }
    if (gallery == null) {
        throw new IllegalArgumentException(
                "The user " + user + " must specify a non null gallery to use before downloading items.");
    }

    try {

        // The complete URL from where we will retrieve items.
        final String urlOfItems = MINUS_GET_ITEMS_URL + "/m" + gallery.getReaderId();

        MinusHttpResponse minusResp = HttpClientUtils.doGet(urlOfItems, null, user.getSessionId(), null,
                STRING);
        String httpResponse = (String) minusResp.getHttpResponse();
        validateHttpResponse(httpResponse);

        Map<String, Object> jsonResult = JSONUtils.getMapFromJSONString(httpResponse);
        validateJsonResult(jsonResult);

        List<MinusItem> items = new ArrayList<MinusItem>();

        // String galleryTitle = (String)
        // jsonResult.get(RESPONSE_KEY_GALLERY_TITLE);
        @SuppressWarnings("unchecked")
        List<String> itemsNames = (List<String>) jsonResult.get(RESPONSE_KEY_ITEMS_NAME);

        @SuppressWarnings("unchecked")
        List<String> itemsURLs = (List<String>) jsonResult.get(RESPONSE_KEY_ITEMS_GALLERY);

        @SuppressWarnings("unchecked")
        List<JSONObject> dimensionsAsObjects = (List<JSONObject>) jsonResult.get(RESPONSE_KEY_IMAGE_SIZES);
        List<Dimension> itemsDimensions = new ArrayList<Dimension>();

        for (JSONObject obj : dimensionsAsObjects) {
            int width = ((Long) obj.get(RESPONSE_KEY_WIDTH)).intValue();
            int height = ((Long) obj.get(RESPONSE_KEY_HEIGHT)).intValue();
            itemsDimensions.add(new Dimension(width, height));
        }

        // Normally, itemsURLs, itemsNames & itemDimesions lists should have
        // the same length, we are going to trust minus api ;)
        for (int i = 0; i < itemsURLs.size(); i++) {
            final String name = itemsNames.get(i);
            final String shortURL = itemsURLs.get(i);
            final Dimension dimension = itemsDimensions.get(i);
            MinusItem oneItem = new MinusItem(name, shortURL, dimension, "-1L");
            items.add(oneItem);
        }

        sendMessageToListenerIfNotNull(jsonResult, listener);

        return items;

    } catch (Exception e) {
        throw new MinusException("Error while downloading items for user (" + user + ") from gallery ("
                + gallery + ") : " + e.getMessage(), e);
    }
}

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

private static boolean waitForImportExport(boolean export, String id, String serverUrl, Options options) {
    String path;//from w  w w.ja  va2 s  .  c o  m
    if (export)
        path = "/services/exports/" + id + "/status";
    else
        path = "/services/imports/" + id + "/status";

    long startTime = System.currentTimeMillis();
    long timeout = export ? options.getTimeoutExportSec() * 1000 : options.getTimeoutImportSec() * 1000;

    while (System.currentTimeMillis() - startTime < timeout) {
        JSONObject json = getJson(serverUrl, path);
        String state = (String) ((JSONObject) json.get(export ? "exportStatus" : "importStatus")).get("status");

        switch (state) {
        case "success":
            return true;
        case "processing":
            console.println("Waiting for " + (export ? "export" : "import") + " to complete...");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
            }
            break;
        default:
        case "fail":
            return false;
        }
    }

    return false;
}

From source file:FactFind.PersonalDetails.java

public static boolean CustomerPersonalDetails() {

    int MaxCustomerreached = 0;
    JSONArray CustomerInformation_Array = (JSONArray) TestExecution.JSONTestData.get("Customerinformation");
    Iterator<JSONObject> CustomerInformationArray = CustomerInformation_Array.iterator();

    String FirstCustomerFlag = "Yes";
    try {/*w ww.  java 2s . c om*/

        WebDriverWait wait = new WebDriverWait(driver, 30);
        wait.until(ExpectedConditions.elementToBeClickable(NextButtonTopofthePage));

        while (CustomerInformationArray.hasNext()) {
            if (MaxCustomerreached >= 2) {
                break;
            }

            JSONObject CustomerInformation = CustomerInformationArray.next();

            if ((FirstCustomerFlag.equals("Yes") || CustomerInformation.get("IsApplicant").equals("Yes"))
                    && CustomerInformation.get("CustomerType").equals("Individual")) {

                if (FirstCustomerFlag.equals("Yes")) {
                    Applicant1.click();
                    Thread.sleep(3000);
                    MaxCustomerreached++;
                } else if (CustomerInformation.get("IsApplicant").equals("Yes")) {
                    Applicant2.click();
                    Thread.sleep(3000);
                    MaxCustomerreached++;
                }

                if (JSON.GetTestData(CustomerInformation, "CustomerNames").get("Title") != null
                        && Integer.parseInt(JSON.GetTestData(CustomerInformation, "CustomerNames").get("Title")
                                .toString()) >= 1) {
                    Title.click();
                    Helper.Keystrokeup(9);
                    Helper.Keystrokedown(Integer.parseInt(
                            JSON.GetTestData(CustomerInformation, "CustomerNames").get("Title").toString()));
                }

                if (JSON.GetTestData(CustomerInformation, "CustomerNames").get("MiddleName") != null) {
                    MiddleName.click();
                    MiddleName.clear();
                    MiddleName.sendKeys(JSON.GetTestData(CustomerInformation, "CustomerNames").get("MiddleName")
                            .toString());
                }

                if (CustomerInformation.get("Gender") != null) {
                    if (CustomerInformation.get("Gender").equals("Male")
                            || CustomerInformation.get("Gender").equals("Female")) {
                        Gender.click();
                        Gender.sendKeys(CustomerInformation.get("Gender").toString());
                        Helper.Keystrokeenter(1);
                    } else {
                        Gender.click();
                        Gender.sendKeys("Unspecified");
                        Helper.Keystrokeenter(1);
                    }
                }

                if (CustomerInformation.get("DOB") != null) {
                    if (FirstCustomerFlag.equals("Yes")) {
                        DateOfbirth.click();
                        DateOfbirth.clear();
                        DateOfbirth.sendKeys(CustomerInformation.get("DOB").toString());
                    } else if (CustomerInformation.get("IsApplicant").equals("Yes")) {
                        DateOfbirthSpouse.click();
                        DateOfbirthSpouse.clear();
                        DateOfbirthSpouse.sendKeys(CustomerInformation.get("DOB").toString());
                    }
                }

                if (CustomerInformation.get("ResidentialStatus") != null
                        && Integer.parseInt(CustomerInformation.get("ResidentialStatus").toString()) >= 1) {
                    if (Integer.parseInt(CustomerInformation.get("ResidentialStatus").toString()) == 1
                            || Integer.parseInt(CustomerInformation.get("ResidentialStatus").toString()) == 2
                            || Integer.parseInt(CustomerInformation.get("ResidentialStatus").toString()) == 3) {
                        ResidencyStatus.click();
                        Helper.Keystrokeup(3);
                        Helper.Keystrokedown(2);
                        Helper.Keystrokeenter(1);
                    } else if (Integer.parseInt(CustomerInformation.get("ResidentialStatus").toString()) == 4) {
                        ResidencyStatus.click();
                        Helper.Keystrokeup(3);
                        Helper.Keystrokedown(1);
                        Helper.Keystrokeenter(1);
                    } else if (Integer.parseInt(CustomerInformation.get("ResidentialStatus").toString()) == 5) {
                        ResidencyStatus.click();
                        Helper.Keystrokeup(3);
                        Helper.Keystrokedown(3);
                        Helper.Keystrokeenter(1);
                    }

                }

                if (JSON.GetTestData(CustomerInformation, "CustomerContactDetails").get("Mobile") != null) {
                    Mobile.click();
                    Mobile.clear();
                    Mobile.sendKeys(JSON.GetTestData(CustomerInformation, "CustomerContactDetails")
                            .get("Mobile").toString());
                }

                if (JSON.GetTestData(CustomerInformation, "CustomerContactDetails").get("HomePhone") != null) {
                    HomePhone.click();
                    HomePhone.clear();
                    HomePhone.sendKeys(JSON.GetTestData(CustomerInformation, "CustomerContactDetails")
                            .get("HomePhone").toString());
                }

                if (JSON.GetTestData(CustomerInformation, "CustomerContactDetails")
                        .get("BusinessPhone") != null) {
                    BusinessPhone.click();
                    BusinessPhone.clear();
                    BusinessPhone.sendKeys(JSON.GetTestData(CustomerInformation, "CustomerContactDetails")
                            .get("BusinessPhone").toString());
                }

                JSONObject FactFind = JSON.GetTestData(CustomerInformation, "FactFind");

                if (JSON.GetTestData(FactFind, "DriversLicense").get("DriversLicenceNumber") != null) {
                    DriversLicenceNumber.click();
                    DriversLicenceNumber.clear();
                    DriversLicenceNumber.sendKeys(JSON.GetTestData(FactFind, "DriversLicense")
                            .get("DriversLicenceNumber").toString());
                }

                if (JSON.GetTestData(FactFind, "DriversLicense").get("LicenseState") != null) {
                    LicenceState.click();
                    LicenceState.sendKeys(
                            JSON.GetTestData(FactFind, "DriversLicense").get("LicenseState").toString());
                    Helper.Keystrokeenter(1);
                }

                if (JSON.GetTestData(FactFind, "DriversLicense").get("LicenceIssued") != null) {
                    if (FirstCustomerFlag.equals("Yes")) {
                        LicenceIssued.click();
                        LicenceIssued.clear();
                        LicenceIssued.sendKeys(
                                JSON.GetTestData(FactFind, "DriversLicense").get("LicenceIssued").toString());
                    } else if (CustomerInformation.get("IsApplicant").equals("Yes")) {
                        LicenceIssuedSpouse.click();
                        LicenceIssuedSpouse.clear();
                        LicenceIssuedSpouse.sendKeys(
                                JSON.GetTestData(FactFind, "DriversLicense").get("LicenceIssued").toString());
                    }
                }

                if (JSON.GetTestData(FactFind, "DriversLicense").get("LicenceExpires") != null) {
                    if (FirstCustomerFlag.equals("Yes")) {
                        LicenceExpiry.click();
                        LicenceExpiry.clear();
                        LicenceExpiry.sendKeys(
                                JSON.GetTestData(FactFind, "DriversLicense").get("LicenceExpires").toString());
                    } else if (CustomerInformation.get("IsApplicant").equals("Yes")) {
                        LicenceExpirySpouse.click();
                        LicenceExpirySpouse.clear();
                        LicenceExpirySpouse.sendKeys(
                                JSON.GetTestData(FactFind, "DriversLicense").get("LicenceExpires").toString());
                    }
                }

                Thread.sleep(3000);

                if (JSON.GetTestData(CustomerInformation, "CustomerDependents")
                        .get("NumberOfDependents") != null) {
                    JSONArray DependantDOBArray = (JSONArray) JSON
                            .GetTestData(CustomerInformation, "CustomerDependents").get("DependentsDOB");
                    Iterator<String> DOBArray = DependantDOBArray.iterator();
                    while (DOBArray.hasNext()) {
                        Helper.ScroolToView(driver, AddDependant);
                        AddDependant.click();
                        Thread.sleep(2000);
                        AgeofDependant.sendKeys(CalculateAge(DOBArray.next().toString()));
                        Helper.ScroolToView(driver, SaveDependent);
                        SaveDependent.click();
                    }
                }

                FirstCustomerFlag = "No";
            }

        }
        Applicant1.click();
        Thread.sleep(5000);
        Helper.ScroolToView(driver, SaveMyDetails);
        SaveMyDetails.click();
        Thread.sleep(5000);
        Helper.ScroolToView(driver, NextButtonBottomofthePage);
        NextButtonBottomofthePage.click();
        Helper.ScreenDump(TestExecution.TestExecutionFolder, "FactFindPersonalDetails");
        logger.info("FactFind Customer personal details entered successfully");
        return true;

    } catch (InterruptedException e) {
        e.printStackTrace();
        logger.error(e.toString());
        Helper.ScreenDump(TestExecution.TestExecutionFolder, "Error");
        return false;
    }

}

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

private static boolean serverTest(String serverUrl) {
    JSONObject json = getJson(serverUrl, "/services/info/status");
    String state = (String) ((JSONObject) json.get("infoStatus")).get("status");

    switch (state) {
    case "LIFERAY_NOT_FOUND":
        console.printlnError("Error: No Liferay server found!");
        console.exit(EXIT_STATUS_FAIL);/*from www .j a v  a2 s.  c  o m*/
    case "LIFERAY_VERSION_NOT_SUPPORTED":
        console.printlnError("Error: Liferay version not supported!");
        console.exit(EXIT_STATUS_FAIL);
    case "NOT_READY":
        return false;
    default:
    case "READY":
        console.println("Server is ready.");
        return true;
    }
}

From source file:com.netbase.insightapi.bestpractice.TopicDownloader.java

/**
 * Download all the documents of a topic, in sequential order, by
 * publication date.//w  w  w. ja  v a 2  s . c  o m
 * 
 * @param masterQuery
 * @param user
 * @param startTimestamp
 *            inclusive
 * @param endTimestamp
 *            exclusive
 * @param handler
 * @throws InterruptedException
 * @throws InsightAPIQueryException
 */
public static void downloadHistory(InsightAPIQuery masterQuery, UserChannel user, int startTimestamp,
        int endTimestamp, ResultHandler handler) throws InterruptedException, InsightAPIQueryException {
    // clone the original query so we don't change it
    InsightAPIQuery query = new InsightAPIQuery(masterQuery);

    // force the parameters we rely on, leaving the others set by caller
    query.setParameter("sort", "timestamp");
    query.setOp("retrieveDocuments");

    // The caller can set "sizeNeeded" to any legal value, particularly for
    // testing purposes. In production, bigger is better unless we start
    // experiencing timeout or communication reliability issues.
    if (query.getParameters("sizeNeeded") == null)
        query.setParameter("sizeNeeded", 2000);

    /*
     * each call to the Insight API will return a (typically small) number
     * of documents that we already received in the prior call. This is
     * because we start the time range for call "n+1" with the highest
     * timestamp received during call "n". We do this because we are not
     * guaranteed to have received *all* of the documents containing the
     * highest timestamp.
     * 
     * Timestamp resolution is 1/10 second; so, typically, we'll receive
     * exactly one document at the end of call "n" and the beginning of
     * "n+1".
     * 
     * This set arranges for us to ignore the overlapped documents.
     */
    Set<String> docIdsAlreadySeen = new HashSet<String>();

    /*
     * the query for the first request covers the entire span for the
     * download. Since we're sorting and filtering by timestamp, we'll get
     * the earliest documents in the range.
     */
    query.setPublishedTimestampRange(startTimestamp, endTimestamp);

    while (true) {

        InsightAPIQuery q = new InsightAPIQuery(query);

        // run the query and toss an exception if it didn't work
        user.run(q);
        q.checkSuccess();

        // get the parsed json result
        JSONObject jsonResult = (JSONObject) q.getParsedContent();

        // get the array of documents
        JSONArray docs = (JSONArray) jsonResult.get("documents");

        // no documents at all? We're done
        if (docs == null || docs.size() == 0)
            break;

        // traverse the beginning of the list, counting up the duplicates
        int first = 0;
        while (first < docs.size()) {
            JSONObject doc = (JSONObject) docs.get(first);
            String docID = (String) getDocProperty(doc, "docID");
            if (!docIdsAlreadySeen.contains(docID))
                break;
            first++;
        }

        // all duplicates? we're done.
        if (first >= docs.size())
            break;

        // call the ResultHandler to process the documents, beginning
        // with the first unique one
        handler.handleResult(docs, first);

        int last = docs.size() - 1;
        docIdsAlreadySeen.clear();

        // get the timestamp of the last document received
        int lastTimestamp = ((Number) getDocProperty(docs.get(last), "timestamp")).intValue();

        // if it's later than (shouldn't be) or equal to (could be) the
        // end of the requested range, we're done
        if (lastTimestamp >= endTimestamp)
            break;

        /*
         * traverse backwards through the list from the end, looking for the
         * next-lower timestamp. Write down all the docIDs of these
         * documents, because we're going to see them again at the beginning
         * of the next query
         */
        while (last >= 0
                && ((Number) getDocProperty(docs.get(last), "timestamp")).intValue() == lastTimestamp) {
            docIdsAlreadySeen.add((String) getDocProperty(docs.get(last), "docID"));
            last--;
        }

        /*
         * If we get through this loop with last < 0, it means that the
         * entire block of documents we received had the same timestamp.
         * This is a failure of this algorithm.
         * 
         * For this to happen, it means that the topic contains more than
         * query.sizeNeeded (current max: 2000) documents with publication
         * timestamps in the same 1/10 second.
         * 
         * We have no choice but to increment the timestamp by 1/10 of a
         * second and move on. If we don't, we'll keep getting the same
         * result in an infinite loop.
         */
        if (last < 0) {
            user.logWarning(query.getSerial() + " too many docs with same timestamp=" + lastTimestamp
                    + ", num of docs=" + docs.size());

            docIdsAlreadySeen.clear();
            lastTimestamp++;
        }

        // set the query's timestamp range to start with the last timestamp
        // we received, and rinse and repeat
        query.setPublishedTimestampRange(lastTimestamp, endTimestamp);
    }
}

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

private static void handleError(Response response) {
    if (response.getStatusCode() != 200) {
        String message = response.getStatusCode() + ": " + response.getStatusMessage();

        try {/*ww  w.ja v  a 2  s  . c  om*/
            if (response.getContentType().contains("json")) {
                String jsonString = response.getResponseAsString();
                JSONObject json = (JSONObject) JSONValue.parse(jsonString);
                message = (String) ((JSONObject) json.get("error")).get("message");
            }
        } catch (Exception e) {
            if (debug)
                console.printStacktrace(e);
        }

        console.printlnError("Error: " + message);
        console.exit(EXIT_STATUS_FAIL);
    }
}

From source file:com.twosigma.beaker.core.rest.UtilRest.java

private static Set<String> mergeListSetting(String settingsListName, JSONObject configs, JSONObject prefs) {
    Set<String> settings = new LinkedHashSet<>();
    Set<String> settingsToRemove = new HashSet<>();
    { // settings from config
        JSONArray s = (JSONArray) configs.get(settingsListName);
        if (s != null) {
            @SuppressWarnings("unchecked")
            Iterator<String> iterator = s.iterator();
            while (iterator.hasNext()) {
                settings.add(iterator.next());
            }/*from w  w  w  . ja  va2  s . c om*/
        }
    }
    { // settings from preference
        JSONArray s = (JSONArray) prefs.get(settingsListName);
        if (s != null) {
            @SuppressWarnings("unchecked")
            Iterator<String> iterator = s.iterator();
            while (iterator.hasNext()) {
                settings.add(iterator.next());
            }
        }
    }
    { // to-remove settings from preference
        JSONArray s = (JSONArray) prefs.get(TO_REMOVE_PREFIX + settingsListName);
        if (s != null) {
            @SuppressWarnings("unchecked")
            Iterator<String> iterator = s.iterator();
            while (iterator.hasNext()) {
                settingsToRemove.add(iterator.next());
            }
        }
    }
    settings.removeAll(settingsToRemove);
    return settings;
}

From source file:net.modsec.ms.connector.ConnRequestHandler.java

/**
 * Starts the modsecurity instance if not running.
 * @param json    /* ww w. j a  v a 2  s.  co m*/
 */
@SuppressWarnings("unchecked")
public static void onStartRequest(JSONObject json) {

    log.info("onStartRequest called.. : " + json.toJSONString());
    MSConfig config = MSConfig.getInstance();
    String cmd = config.getConfigMap().get("MSStart");

    JSONObject resp = executeShScript(cmd, json);
    if (((String) resp.get("status")).equals("0")) {
        resp.put("message", "Modsecuity Sucessfully Started");
    }

    log.info("Sending Json :" + resp.toJSONString());
    ConnectorService.getConnectorProducer().send(resp.toJSONString());
    resp.clear();

}

From source file:net.modsec.ms.connector.ConnRequestHandler.java

/**
 * Stops the modsecurity instance if not stopped before.
 * @param json//from w ww.j  a v  a2s  .  c  om
 */
@SuppressWarnings("unchecked")
public static void onStopRequest(JSONObject json) {

    log.info("onStopRequest called.. : " + json.toJSONString());
    MSConfig config = MSConfig.getInstance();
    String cmd = config.getConfigMap().get("MSStop");

    JSONObject resp = executeShScript(cmd, json);
    if (((String) resp.get("status")).equals("0")) {
        resp.put("message", "Modsecuity Sucessfully Stoped");
    }

    log.info("Sending Json :" + resp.toJSONString());
    ConnectorService.getConnectorProducer().send(resp.toJSONString());
    resp.clear();

}

From source file:net.modsec.ms.connector.ConnRequestHandler.java

/**
 * Restarts the instance./* w  ww  .j  a v a  2 s  . c o m*/
 * @param json
 */
@SuppressWarnings("unchecked")
public static void onRestartRequest(JSONObject json) {

    log.info("onRestartRequest called.. : " + json.toJSONString());
    MSConfig config = MSConfig.getInstance();
    String cmd = config.getConfigMap().get("MSRestart");

    JSONObject resp = executeShScript(cmd, json);
    if (((String) resp.get("status")).equals("0")) {
        resp.put("message", "Modsecuity Sucessfully Restarted");
    }

    log.info("Sending Json :" + resp.toJSONString());
    ConnectorService.getConnectorProducer().send(resp.toJSONString());
    resp.clear();

}