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.appcelerator.titanium.desktop.ui.wizard.Packager.java

private void pollPackagingRequest(final IProject project, final String ticket) throws CoreException {
    Job pollingJob = new Job(Messages.Packager_PollingPackageStatusTaskName) {

        @Override//from  www  . j  av a  2 s  . c o m
        protected IStatus run(IProgressMonitor monitor) {
            monitor.beginTask(Messages.Packager_PollingPackageStatusTaskName, -1);
            try {
                while (true) {
                    Map<String, String> data = new HashMap<String, String>();
                    data.put("ticket", ticket); //$NON-NLS-1$

                    IStatus result = invokeCloudService(new URL(PUBLISH_STATUS_URL), data, "POST"); //$NON-NLS-1$
                    if (!result.isOK()) {
                        return result;
                    }

                    String rawJSON = result.getMessage();
                    Object parsed = new JSONParser().parse(rawJSON);
                    JSONObject json = (JSONObject) parsed;

                    if ("complete".equals(json.get("status"))) //$NON-NLS-1$//$NON-NLS-2$
                    {
                        Release.updateForProject(project, json);
                        // We don't show packages in UI when we are testing
                        if (!EclipseUtil.isTesting()) {
                            showPackages(project);
                        }
                        return Status.OK_STATUS;
                    } else if (json.containsKey("success") && !((Boolean) json.get("success"))) //$NON-NLS-1$ //$NON-NLS-2$
                    {
                        return new Status(IStatus.ERROR, DesktopPlugin.PLUGIN_ID, 0,
                                Messages.Packager_PackagingFailedError + json.get("message"), null); //$NON-NLS-1$
                    }
                    if (monitor != null && monitor.isCanceled()) {
                        return Status.CANCEL_STATUS;
                    }
                    // Retry in 10 seconds
                    Thread.sleep(10000);
                }
            } catch (Exception e) {
                return new Status(IStatus.ERROR, DesktopPlugin.PLUGIN_ID, 0, e.getMessage(), e);
            }
        }
    };

    pollingJob.setUser(true);
    pollingJob.schedule();

    // Make this a blocking job for unit tests
    if (EclipseUtil.isTesting()) {
        try {
            pollingJob.join();
            if (pollingJob.getResult() != Status.OK_STATUS) {
                throw new CoreException(new Status(IStatus.ERROR, DesktopPlugin.PLUGIN_ID, 0,
                        "Polling Package Request Failed:" + pollingJob.getResult().getMessage(), null)); //$NON-NLS-1$
            }
        } catch (InterruptedException e) {
        }
    }
}

From source file:com.thesmartweb.swebrank.JSONparsing.java

/**
 * Get meta info for a Youtube link/*from  w ww . j a v  a 2s .  c  o m*/
 * @param ventry the id of the Youtube video
 * @return a String with all the meta info about the youtube video
 */
public String GetYoutubeDetails(String ventry) {
    try {
        String apikey = "AIzaSyDLm-MfYHcbTHQO1S8ROX2rpvsqd5oYSRI";
        String output = "";
        URL link_ur = new URL("https://www.googleapis.com/youtube/v3/videos?id=" + ventry + "&key=" + apikey
                + "&part=snippet");
        APIconn apicon = new APIconn();
        String line = apicon.connect(link_ur);
        JSONParser parser = new JSONParser();
        //Create the map
        Map json = (Map) parser.parse(line);
        // Get a set of the entries
        Set set = json.entrySet();
        Iterator iterator = set.iterator();
        Map.Entry entry = null;
        boolean flagfound = false;
        while (iterator.hasNext() && !flagfound) {
            entry = (Map.Entry) iterator.next();
            if (entry.getKey().toString().equalsIgnoreCase("items")) {
                flagfound = true;
            }
        }
        JSONArray jsonarray = (JSONArray) entry.getValue();
        Iterator iteratorarray = jsonarray.iterator();
        flagfound = false;
        JSONObject get = null;
        while (iteratorarray.hasNext() && !flagfound) {
            JSONObject next = (JSONObject) iteratorarray.next();
            if (next.containsKey("snippet")) {
                get = (JSONObject) next.get("snippet");
                flagfound = true;
            }
        }
        String description = "";
        String title = "";
        if (flagfound) {
            if (get.containsKey("description")) {
                description = get.get("description").toString();
            }
            if (get.containsKey("title")) {
                title = get.get("title").toString();
            }
            output = description + " " + title;
        }
        Stopwords stopwords = new Stopwords();
        output = stopwords.stop(output);
        return output;
    } catch (IOException | ArrayIndexOutOfBoundsException | ParseException ex) {
        Logger.getLogger(JSONparsing.class.getName()).log(Level.SEVERE, null, ex);
        String output = null;
        return output;
    }
}

From source file:com.nubits.nubot.trading.wrappers.PoloniexWrapper.java

private ApiResponse getBalanceImpl(CurrencyPair pair, Currency currency) {
    LOG.trace("get balance");

    //Swap the pair for the request
    ApiResponse apiResponse = new ApiResponse();

    String url = API_BASE_URL;
    String method = API_GET_BALANCES;
    HashMap<String, String> query_args = new HashMap<>();
    boolean isGet = false;

    LOG.trace("get from " + url);
    LOG.trace("method " + method);
    ApiResponse response = getQuery(url, method, query_args, true, isGet);

    LOG.trace("response " + response);
    if (!response.isPositive()) {
        return response;
    }// w w  w  . ja va2 s.  c  om

    JSONObject httpAnswerJson = (JSONObject) response.getResponseObject();
    LOG.trace("balance answer " + httpAnswerJson);

    if (currency != null) {
        //looking for a specific currency
        String lookingFor = currency.getCode().toUpperCase();
        if (httpAnswerJson.containsKey(lookingFor)) {
            JSONObject balanceJSON = (JSONObject) httpAnswerJson.get(lookingFor);
            double balanceD = Utils.getDouble(balanceJSON.get("available"));
            LOG.trace("balance double : " + balanceD);
            apiResponse.setResponseObject(new Amount(balanceD, currency));
        } else {
            String errorMessage = "Cannot find a balance for currency " + lookingFor;
            ApiError apiErr = errors.apiReturnError;
            apiErr.setDescription(errorMessage);
            apiResponse.setError(apiErr);
        }
    } else {
        //get all balances for the pair
        boolean foundNBTavail = false;
        boolean foundPEGavail = false;
        Amount NBTAvail = new Amount(0, pair.getOrderCurrency());
        Amount PEGAvail = new Amount(0, pair.getPaymentCurrency());

        Amount PEGonOrder = new Amount(0, pair.getPaymentCurrency());
        Amount NBTonOrder = new Amount(0, pair.getOrderCurrency());

        String NBTcode = pair.getOrderCurrency().getCode().toUpperCase();
        String PEGcode = pair.getPaymentCurrency().getCode().toUpperCase();

        if (httpAnswerJson.containsKey(NBTcode)) {
            JSONObject balanceJSON = (JSONObject) httpAnswerJson.get(NBTcode);
            double tempAvailablebalance = Utils.getDouble(balanceJSON.get("available"));
            double tempLockedebalance = Utils.getDouble(balanceJSON.get("onOrders"));
            NBTAvail = new Amount(tempAvailablebalance, pair.getOrderCurrency());
            NBTonOrder = new Amount(tempLockedebalance, pair.getOrderCurrency());
            foundNBTavail = true;
        }
        if (httpAnswerJson.containsKey(PEGcode)) {
            JSONObject balanceJSON = (JSONObject) httpAnswerJson.get(PEGcode);
            double tempAvailablebalance = Utils.getDouble(balanceJSON.get("available"));
            double tempLockedebalance = Utils.getDouble(balanceJSON.get("onOrders"));
            PEGAvail = new Amount(tempAvailablebalance, pair.getPaymentCurrency());
            PEGonOrder = new Amount(tempLockedebalance, pair.getPaymentCurrency());
            foundPEGavail = true;
        }
        PairBalance balance = new PairBalance(PEGAvail, NBTAvail, PEGonOrder, NBTonOrder);
        apiResponse.setResponseObject(balance);
        if (!foundNBTavail || !foundPEGavail) {
            LOG.warn("Cannot find a balance for currency with code " + "" + NBTcode + " or " + PEGcode
                    + " in your balance. " + "NuBot assumes that balance is 0");
        }
    }

    return apiResponse;
}

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

/**
 * Emit the end-tag associated with an MML property
 * @param defn the property definition/*from  w  ww.  ja v a2  s. c o m*/
 * @param length of the property
 * @return the text associated with the end of the property
 */
String mmlEndTag(JSONObject defn, int len) {
    String kind = (String) defn.get("kind");
    DialectKeys key = DialectKeys.valueOf(kind);
    switch (key) {
    case sections:
        return "\n\n\n";
    case paragraph:
        return "\n\n";
    case headings:
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len - 1; i++)
            sb.append(defn.get("tag"));
        return "\n" + sb.toString() + "\n\n";
    case charformats:
        if (defn.containsKey("tag"))
            return (String) defn.get("tag");
        else
            return (String) defn.get("rightTag");
    case lineformats:
        return (String) defn.get("rightTag") + "\n";
    case paraformats:
        return (String) defn.get("rightTag") + "\n\n";
    default:
        return "";
    }
}

From source file:io.openvidu.java.client.Session.java

@SuppressWarnings("unchecked")
protected Session resetSessionWithJson(JSONObject json) {
    this.sessionId = (String) json.get("sessionId");
    this.createdAt = (long) json.get("createdAt");
    this.recording = (boolean) json.get("recording");
    SessionProperties.Builder builder = new SessionProperties.Builder()
            .mediaMode(MediaMode.valueOf((String) json.get("mediaMode")))
            .recordingMode(RecordingMode.valueOf((String) json.get("recordingMode")))
            .defaultOutputMode(Recording.OutputMode.valueOf((String) json.get("defaultOutputMode")));
    if (json.containsKey("defaultRecordingLayout")) {
        builder.defaultRecordingLayout(RecordingLayout.valueOf((String) json.get("defaultRecordingLayout")));
    }/*from w  w w .j  a v  a2  s  .co m*/
    if (json.containsKey("defaultCustomLayout")) {
        builder.defaultCustomLayout((String) json.get("defaultCustomLayout"));
    }
    if (this.properties != null && this.properties.customSessionId() != null) {
        builder.customSessionId(this.properties.customSessionId());
    } else if (json.containsKey("customSessionId")) {
        builder.customSessionId((String) json.get("customSessionId"));
    }
    this.properties = builder.build();
    JSONArray jsonArrayConnections = (JSONArray) ((JSONObject) json.get("connections")).get("content");
    this.activeConnections.clear();
    jsonArrayConnections.forEach(connection -> {
        JSONObject con = (JSONObject) connection;

        Map<String, Publisher> publishers = new ConcurrentHashMap<>();
        JSONArray jsonArrayPublishers = (JSONArray) con.get("publishers");
        jsonArrayPublishers.forEach(publisher -> {
            JSONObject pubJson = (JSONObject) publisher;
            JSONObject mediaOptions = (JSONObject) pubJson.get("mediaOptions");
            Publisher pub = new Publisher((String) pubJson.get("streamId"), (long) pubJson.get("createdAt"),
                    (boolean) mediaOptions.get("hasAudio"), (boolean) mediaOptions.get("hasVideo"),
                    mediaOptions.get("audioActive"), mediaOptions.get("videoActive"),
                    mediaOptions.get("frameRate"), mediaOptions.get("typeOfVideo"),
                    mediaOptions.get("videoDimensions"));
            publishers.put(pub.getStreamId(), pub);
        });

        List<String> subscribers = new ArrayList<>();
        JSONArray jsonArraySubscribers = (JSONArray) con.get("subscribers");
        jsonArraySubscribers.forEach(subscriber -> {
            subscribers.add((String) ((JSONObject) subscriber).get("streamId"));
        });

        this.activeConnections.put((String) con.get("connectionId"),
                new Connection((String) con.get("connectionId"), (long) con.get("createdAt"),
                        OpenViduRole.valueOf((String) con.get("role")), (String) con.get("token"),
                        (String) con.get("location"), (String) con.get("platform"),
                        (String) con.get("serverData"), (String) con.get("clientData"), publishers,
                        subscribers));
    });
    return this;
}

From source file:com.tremolosecurity.unison.openshiftv3.OpenShiftTarget.java

public boolean isObjectExists(String token, HttpCon con, String uri, String json)
        throws IOException, ClientProtocolException, ProvisioningException, ParseException {

    JSONParser parser = new JSONParser();
    JSONObject root = (JSONObject) parser.parse(json);
    JSONObject metadata = (JSONObject) root.get("metadata");

    String name = (String) metadata.get("name");

    StringBuffer b = new StringBuffer();

    b.append(uri).append('/').append(name);

    json = this.callWS(token, con, b.toString());

    root = (JSONObject) parser.parse(json);
    if (root.containsKey("kind") && root.get("kind").equals("Status") && ((Long) root.get("code")) == 404) {
        return false;
    } else {/*from   w ww .j  a v a2 s. c  om*/
        return true;
    }

}

From source file:com.thesmartweb.swebrank.JSONparsing.java

public void DandelionParsing(String input, String query, boolean StemFlag) {
    try {// w  ww .  j  a v a  2  s.  co  m
        ent_avg_dand_score = 0.0;
        //Create a parser
        JSONParser parser = new JSONParser();
        //Create the map
        Object parse = parser.parse(input);
        Map json = (Map) parser.parse(input);
        Set entrySet = json.entrySet();
        Iterator iterator = entrySet.iterator();
        Map.Entry entry = null;
        boolean flagfound = false;
        //we are going to search if we have semantic annotations
        while (iterator.hasNext() && !flagfound) {
            entry = (Map.Entry) iterator.next();
            if (entry.getKey().toString().equalsIgnoreCase("annotations")) {
                flagfound = true;
            }
        }
        if (flagfound) {
            //if we have annotations we get the value
            JSONArray jsonarray = (JSONArray) entry.getValue();
            Iterator iteratorarray = jsonarray.iterator();
            flagfound = false;
            JSONObject get = null;
            while (iteratorarray.hasNext() && !flagfound) {
                JSONObject next = (JSONObject) iteratorarray.next();
                if (next.containsKey("label")) {
                    String entityString = next.get("label").toString().toLowerCase();
                    if (StemFlag) {
                        String[] splitEntity = entityString.split(" ");
                        entityString = "";
                        StemmerSnow stemmer = new StemmerSnow();
                        List<String> splitEntityList = stemmer.stem(Arrays.asList(splitEntity));
                        StringBuilder sb = new StringBuilder();
                        for (String s : splitEntityList) {
                            sb.append(s.trim());
                            sb.append(" ");
                        }
                        entityString = sb.toString().trim();
                    }
                    entitiesDand.add(entityString);
                }
                if (next.containsKey("categories")) {
                    jsonarray = (JSONArray) next.get("categories");
                    for (int i = 0; i < jsonarray.size(); i++) {
                        String categoryString = jsonarray.get(i).toString().toLowerCase();
                        if (StemFlag) {
                            String[] splitEntity = categoryString.split(" ");
                            categoryString = "";
                            StemmerSnow stemmer = new StemmerSnow();
                            List<String> splitEntityList = stemmer.stem(Arrays.asList(splitEntity));
                            StringBuilder sb = new StringBuilder();
                            for (String s : splitEntityList) {
                                sb.append(s.trim());
                                sb.append(" ");
                            }
                            categoryString = sb.toString().trim();
                        }
                        categoriesDand.add(categoryString);
                    }
                }
                if (next.containsKey("confidence")) {
                    ent_avg_dand_score = ent_avg_dand_score
                            + Double.parseDouble(next.get("confidence").toString());
                }
            }
            ent_avg_dand_score = ent_avg_dand_score / (double) entitiesDand.size();
            ent_query_cnt_dand = 0;
            cat_query_cnt_dand = 0;
            ent_query_cnt_dand_whole = 0;
            cat_query_cnt_dand_whole = 0;
            query = query.toLowerCase();
            String[] split = query.split("\\+");
            if (StemFlag) {
                List<String> splitQuery = Arrays.asList(split);
                StemmerSnow stemmer = new StemmerSnow();
                splitQuery = stemmer.stem(splitQuery);
                split = splitQuery.toArray(new String[splitQuery.size()]);
            }
            int ent_count = 0;
            for (String s : entitiesDand) {
                ent_count = 0;
                for (String splitStr : split) {
                    if (s.contains(splitStr)) {
                        ent_query_cnt_dand++;
                        ent_count++;
                    }
                }
                if (ent_count == split.length) {
                    ent_query_cnt_dand_whole++;
                }
            }
            int cat_count = 0;
            for (String s : categoriesDand) {
                cat_count = 0;
                for (String splitStr : split) {
                    if (s.contains(splitStr)) {
                        cat_query_cnt_dand++;
                        cat_count++;
                    }
                }
                if (cat_count == split.length) {
                    cat_query_cnt_dand_whole++;
                }
            }

        }
    } catch (ParseException ex) {
        Logger.getLogger(JSONparsing.class.getName()).log(Level.SEVERE, null, ex);

    }

}

From source file:com.piusvelte.hydra.MSSQLConnection.java

@SuppressWarnings("unchecked")
@Override/*from   www  . j a va2  s .c o m*/
public JSONObject execute(String statement) {
    JSONObject response = new JSONObject();
    JSONArray errors = new JSONArray();
    Statement s = null;
    ResultSet rs = null;
    try {
        s = mConnection.createStatement();
        rs = s.executeQuery(statement);
        response.put("result", getResult(rs));
    } catch (SQLException e) {
        errors.add(e.getMessage());
    } finally {
        if (s != null) {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    errors.add(e.getMessage());
                }
            }
            try {
                s.close();
            } catch (SQLException e) {
                errors.add(e.getMessage());
            }
        }
    }
    response.put("errors", errors);
    if (!response.containsKey("result")) {
        JSONArray rows = new JSONArray();
        JSONArray rowData = new JSONArray();
        rows.add(rowData);
        response.put("result", rows);
    }
    return response;
}

From source file:com.nubits.nubot.trading.wrappers.BterWrapper.java

private ApiResponse getBalanceImpl(Currency currency, CurrencyPair pair) {
    ApiResponse apiResponse = new ApiResponse();

    String url = API_BASE_URL + API_GET_INFO;
    boolean isGet = false;
    HashMap<String, String> query_args = new HashMap<>();

    ApiResponse response = getQuery(url, query_args, true, isGet);
    if (response.isPositive()) {
        JSONObject httpAnswerJson = (JSONObject) response.getResponseObject();
        boolean somethingLocked = false;
        JSONObject lockedFundsJSON = null;
        JSONObject availableFundsJSON = (JSONObject) httpAnswerJson.get("available_funds");

        if (httpAnswerJson.containsKey("locked_funds")) {
            lockedFundsJSON = (JSONObject) httpAnswerJson.get("locked_funds");
            somethingLocked = true;/*  w ww.  j a v  a2s.co m*/
        }

        if (currency == null) { //Get all balances
            boolean foundNBTavail = false;
            boolean foundPEGavail = false;
            Amount NBTAvail = new Amount(0, pair.getOrderCurrency()),
                    PEGAvail = new Amount(0, pair.getPaymentCurrency());
            Amount PEGonOrder = new Amount(0, pair.getPaymentCurrency());
            Amount NBTonOrder = new Amount(0, pair.getOrderCurrency());
            String NBTcode = pair.getOrderCurrency().getCode().toUpperCase();
            String PEGcode = pair.getPaymentCurrency().getCode().toUpperCase();
            if (availableFundsJSON.containsKey(NBTcode)) {
                double tempbalance = Double.parseDouble((String) availableFundsJSON.get(NBTcode));
                NBTAvail = new Amount(tempbalance, pair.getOrderCurrency());
                foundNBTavail = true;
            }
            if (availableFundsJSON.containsKey(PEGcode)) {
                double tempbalance = Double.parseDouble((String) availableFundsJSON.get(PEGcode));
                PEGAvail = new Amount(tempbalance, pair.getPaymentCurrency());
                foundPEGavail = true;
            }
            if (somethingLocked) {
                if (lockedFundsJSON.containsKey(NBTcode)) {
                    double tempbalance = Double.parseDouble((String) lockedFundsJSON.get(NBTcode));
                    NBTonOrder = new Amount(tempbalance, pair.getOrderCurrency());
                }

                if (lockedFundsJSON.containsKey(PEGcode)) {
                    double tempbalance = Double.parseDouble((String) lockedFundsJSON.get(PEGcode));
                    PEGonOrder = new Amount(tempbalance, pair.getOrderCurrency());
                }
            }
            PairBalance balance = new PairBalance(PEGAvail, NBTAvail, PEGonOrder, NBTonOrder);
            apiResponse.setResponseObject(balance);
            if (!foundNBTavail || !foundPEGavail) {
                LOG.info("Cannot find a balance for currency with code " + "" + NBTcode + " or " + PEGcode
                        + " in your balance. " + "NuBot assumes that balance is 0");
            }
        } else { //Get specific balance
            boolean found = false;
            Amount avail = new Amount(0, currency);
            String code = currency.getCode().toUpperCase();
            if (availableFundsJSON.containsKey(code)) {
                double tempbalance = Double.parseDouble((String) availableFundsJSON.get(code));
                avail = new Amount(tempbalance, currency);
                found = true;
            }
            apiResponse.setResponseObject(avail);
            if (!found) {
                LOG.warn("Cannot find a balance for currency with code " + code
                        + " in your balance. NuBot assumes that balance is 0");
            }
        }
    } else {
        apiResponse = response;
    }

    return apiResponse;
}

From source file:com.nubits.nubot.trading.wrappers.ComkortWrapper.java

private Order parseOrder(JSONObject in, CurrencyPair pair) {
    Order out = new Order();

    out.setId(in.get("id").toString());
    String type = (String) in.get("type");
    out.setType(type.equalsIgnoreCase("sell") ? Constant.SELL : Constant.BUY);
    Amount amount = new Amount(Utils.getDouble(in.get("amount").toString()), pair.getOrderCurrency());
    out.setAmount(amount);//from w  ww .  java2 s. co  m
    Amount price = new Amount(Utils.getDouble(in.get("price").toString()), pair.getPaymentCurrency());
    out.setPrice(price);
    out.setPair(pair);
    if (in.containsKey("added")) {
        long timeStamp = (long) Utils.getDouble(in.get("added").toString());
        Date insertDate = new Date(timeStamp * 1000);
        out.setInsertedDate(insertDate);
    }

    return out;
}