Example usage for org.json.simple JSONObject keySet

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

Introduction

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

Prototype

Set<K> keySet();

Source Link

Document

Returns a Set view of the keys contained in this map.

Usage

From source file:io.fabric8.mq.autoscaler.MQAutoScaler.java

private void bounceConnections(BrokerVitalSigns broker, int number) throws Exception {
    if (number > 0) {
        ObjectName root = broker.getRoot();
        Hashtable<String, String> props = root.getKeyPropertyList();
        props.put("connector", "clientConnectors");
        props.put("connectorName", "*");
        String objectName = root.getDomain() + ":" + getOrderedProperties(props);

        /**/*from   w  w  w .  ja  v  a  2  s . c o  m*/
         * not interested in StatisticsEnabled, just need a real attribute so we can get the root which we
         * can execute against
         */

        List<String> connectors = new ArrayList<>();
        J4pResponse<J4pReadRequest> response = broker.getClient()
                .execute(new J4pReadRequest(objectName, "StatisticsEnabled"));
        JSONObject value = response.getValue();
        for (Object key : value.keySet()) {
            connectors.add(key.toString());
        }

        List<String> targets = new ArrayList<>();
        for (String key : connectors) {
            ObjectName on = new ObjectName(key);
            Hashtable<String, String> p = on.getKeyPropertyList();
            p.put("connectionName", "*");
            p.put("connectionViewType", "clientId");
            String clientObjectName = root.getDomain() + ":" + getOrderedProperties(p);
            ObjectName on1 = new ObjectName(clientObjectName);
            J4pResponse<J4pReadRequest> response1 = broker.getClient().execute(new J4pReadRequest(on1, "Slow"));
            JSONObject value1 = response1.getValue();
            for (Object k : value1.keySet()) {
                targets.add(k.toString());
            }
        }

        int count = 0;
        for (String key : targets) {
            broker.getClient().execute(new J4pExecRequest(key, "stop"));
            LOG.info("Stopping Client " + key + " on broker " + broker.getBrokerIdentifier());
            if (++count >= number) {
                break;
            }
        }
    }

}

From source file:com.worldline.easycukes.rest.client.RestService.java

/**
 * Allows to send a POST request, with parameters using JSON format
 *
 * @param path path to be used for the POST request
 * @param data paremeters to be used (JSON format) as a string
 *//* w ww.java  2  s. co m*/
@SuppressWarnings("unchecked")
public void sendPost(final String path, final String data) throws Exception {
    String fullpath = path;
    if (path.startsWith("/"))
        fullpath = baseUrl + path;

    log.info("Sending POST request to " + fullpath);
    final PostMethod method = new PostMethod(fullpath);
    for (final Map.Entry<String, String> header : requestHeaders.entrySet())
        method.setRequestHeader(header.getKey(), header.getValue());
    if (data != null) {
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONHelper.toJSONObject(data);
            for (final Iterator<String> iterator = jsonObject.keySet().iterator(); iterator.hasNext();) {
                final String param = iterator.next();
                method.setParameter(param,
                        (jsonObject.get(param) != null) ? jsonObject.get(param).toString() : null);
            }
        } catch (final ParseException e) {
            log.error("Sorry, parameters are not proper JSON...", e);
            throw new IOException(e.getMessage(), e);
        }

    }
    try {
        if (nonProxyHost != null && fullpath.contains(nonProxyHost)) {
            httpClient.getHostConfiguration().setProxyHost(null);
        }
        final int statusCode = httpClient.executeMethod(method);
        response = new ResponseWrapper(method.getResponseBodyAsString(), method.getResponseHeaders(),
                statusCode);
    } catch (final IOException e) {
        log.error(e.getMessage(), e);
        throw new IOException(e.getMessage(), e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.worldline.easycukes.rest.client.RestService.java

/**
* Allows to send a PUT request, with parameters using JSON format
*
* @param path path to be used for the PUT request
* @param data paremeters to be used (JSON format) as a string
*//*from   w  w  w. ja  v  a2  s. c  o m*/
@SuppressWarnings("unchecked")
public void sendPut(final String path, final String data) {
    String fullpath = path;

    if (path.startsWith("/"))
        fullpath = baseUrl + path;

    log.info("Sending PUT request to " + fullpath);

    final PutMethod method = new PutMethod(fullpath);

    for (final Map.Entry<String, String> header : requestHeaders.entrySet())
        method.setRequestHeader(header.getKey(), header.getValue());

    if (data != null) {
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONHelper.toJSONObject(data);

            for (final Iterator<String> iterator = jsonObject.keySet().iterator(); iterator.hasNext();) {
                final String param = iterator.next();
                HttpMethodParams methodParams = new HttpMethodParams();
                methodParams.setParameter(param,
                        (jsonObject.get(param) != null) ? jsonObject.get(param).toString() : null);
                method.setParams(methodParams);
            }
        } catch (final ParseException e) {
            log.error("Sorry, parameters are not proper JSON...", e);
        }
    }

    try {
        if (nonProxyHost != null && fullpath.contains(nonProxyHost)) {
            httpClient.getHostConfiguration().setProxyHost(null);
        }
        final int statusCode = httpClient.executeMethod(method);
        response = new ResponseWrapper(method.getResponseBodyAsString(), method.getResponseHeaders(),
                statusCode);
    } catch (final IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.worldline.easycukes.rest.client.RestService.java

/**
 * Allows to send a DELETE request, with parameters using JSON format
 *
 * @param path path to be used for the DELETE request
 * @param data paremeters to be used (JSON format) as a string
 *//*from ww w  .java2  s.  c om*/
@SuppressWarnings("unchecked")
public void sendDelete(final String path, final String data) {
    String fullpath = path;

    if (path.startsWith("/"))
        fullpath = baseUrl + path;

    log.info("Sending DELETE request to " + fullpath);

    final DeleteMethod method = new DeleteMethod(fullpath);

    for (final Map.Entry<String, String> header : requestHeaders.entrySet())
        method.setRequestHeader(header.getKey(), header.getValue());

    if (data != null) {
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONHelper.toJSONObject(data);

            for (final Iterator<String> iterator = jsonObject.keySet().iterator(); iterator.hasNext();) {
                final String param = iterator.next();
                HttpMethodParams methodParams = new HttpMethodParams();
                methodParams.setParameter(param,
                        (jsonObject.get(param) != null) ? jsonObject.get(param).toString() : null);
                method.setParams(methodParams);

            }
        } catch (final ParseException e) {
            log.error("Sorry, parameters are not proper JSON...", e);
        }

    }
    try {
        if (nonProxyHost != null && fullpath.contains(nonProxyHost)) {
            httpClient.getHostConfiguration().setProxyHost(null);
        }
        final int statusCode = httpClient.executeMethod(method);
        response = new ResponseWrapper(method.getResponseBodyAsString(), method.getResponseHeaders(),
                statusCode);
    } catch (final IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        method.releaseConnection();
    }
}

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

@SuppressWarnings("unchecked")
public Map<String, Long> getUnreadCounts() {
    if (!isLoggedIn()) {
        login(myUsername, myPassword);/*from   w w  w .  ja  va 2 s. c  o m*/
    }

    try {
        // go to an extremely high page so that it loads faster. Examine the
        // JSON feeds if you don't know what I mean by this.
        HttpGet get = new HttpGet(BASE + "/voice/inbox/recent?page=p1000");
        HttpResponse response = myClient.execute(get);
        String rsp = getJSON(response.getEntity());
        Object obj = JSONValue.parse(rsp);
        JSONObject msgs = (JSONObject) obj;

        Map<String, Long> unread = new HashMap<String, Long>();
        msgs = (JSONObject) msgs.get("unreadCounts");
        for (String key : (Set<String>) msgs.keySet()) {
            Object data = msgs.get(key);
            unread.put(key, (Long) data);
        }
        return unread;
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return new HashMap<String, Long>();
}

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

private ApiResponse getOrdersImpl(CurrencyPair pair) {
    ApiResponse apiResponse = new ApiResponse();
    ArrayList<Order> orderList = new ArrayList<Order>();
    boolean isGet = false;
    String url = API_BASE_URL;
    String method = API_GET_ORDERS;
    HashMap<String, String> query_args = new HashMap<>();

    String pairString = "all";
    if (pair != null) {
        pair = CurrencyPair.swap(pair);//w  w  w . j a  v  a 2s.c om
        pairString = pair.toStringSep().toUpperCase();
    }

    query_args.put("currencyPair", pairString);

    ApiResponse response = getQuery(url, method, query_args, true, isGet);
    if (response.isPositive()) {
        if (pairString.equals("all")) {
            JSONObject httpAnswerJson = (JSONObject) response.getResponseObject();
            Set<String> set = httpAnswerJson.keySet();
            for (String key : set) {
                JSONArray tempArray = (JSONArray) httpAnswerJson.get(key);
                for (int i = 0; i < tempArray.size(); i++) {
                    CurrencyPair cp = CurrencyPair.getCurrencyPairFromString(key, "_");
                    JSONObject orderObject = (JSONObject) tempArray.get(i);
                    Order tempOrder = parseOrder(orderObject, cp);
                    orderList.add(tempOrder);
                }
            }
        } else {
            JSONArray httpAnswerJson = (JSONArray) response.getResponseObject();
            for (int i = 0; i < httpAnswerJson.size(); i++) {
                JSONObject orderObject = (JSONObject) httpAnswerJson.get(i);
                Order tempOrder = parseOrder(orderObject, pair);
                orderList.add(tempOrder);
            }
        }
        apiResponse.setResponseObject(orderList);
    } else {
        apiResponse = response;
    }

    return apiResponse;
}

From source file:edu.ucsd.sbrg.escher.utilities.EscherParser.java

/**
 * @param id/*www. j  av a  2s  .c  om*/
 * @param json
 * @param escherMap
 * @return
 */
private EscherReaction[] parseReaction(Object id, JSONObject json, EscherMap escherMap) {
    EscherReaction reaction = new EscherReaction();
    reaction.setId(parseString(id));
    reaction.setBiggId(parseString(json.get(EscherKeywords.bigg_id.name())));
    reaction.setLabelX(parseDouble(json.get(EscherKeywords.label_x.name())));
    reaction.setLabelY(parseDouble(json.get(EscherKeywords.label_y.name())));
    reaction.setName(parseString(json.get(EscherKeywords.name.name())));
    reaction.setReversibility(parseBoolean(json.get(EscherKeywords.reversibility.name())));
    if (json.get(EscherKeywords.gene_reaction_rule.toString()) != null) {
        reaction.setGeneReactionRule(json.get(EscherKeywords.gene_reaction_rule.toString()).toString());
    }
    Object object = json.get(EscherKeywords.genes.name());
    if ((object != null) && (object instanceof JSONArray)) {
        JSONArray genes = (JSONArray) object;
        for (Object o : genes) {
            reaction.addGene(parseGene(o));
        }
    } else {
        logger.warning(MessageFormat.format(bundle.getString("EscherParser.cannotParse"),
                object.getClass().getName()));
    }
    object = json.get(EscherKeywords.metabolites.toString());
    if ((object != null) && (object instanceof JSONArray)) {
        JSONArray metabolites = (JSONArray) object;
        for (int i = 0; i < metabolites.size(); i++) {
            reaction.addMetabolite(parseMetabolite(reaction.getBiggId(), metabolites.get(i)));
        }
    } else {
        logger.warning(MessageFormat.format(bundle.getString("EscherParser.cannotParse"),
                object.getClass().getName()));
    }
    object = json.get(EscherKeywords.segments.name());
    if ((object != null) && (object instanceof JSONObject)) {
        JSONObject segments = (JSONObject) object;
        List<Segment> listOfSegments = new LinkedList<Segment>();
        // parse all segments and find the midmarker of the reaction
        Set<Node> setOfMidmarkers = new HashSet<Node>();
        Set<Node> setOfConnectedNodes = new HashSet<Node>();
        for (Object key : segments.keySet()) {
            Segment segment = parseSegment(key, (JSONObject) segments.get(key));
            listOfSegments.add(segment);
            Node fromNode = escherMap.getNode(segment.getFromNodeId());
            Node toNode = escherMap.getNode(segment.getToNodeId());
            if (fromNode.isMidmarker()) {
                setOfMidmarkers.add(fromNode);
            } else if (toNode.isMidmarker()) {
                setOfMidmarkers.add(toNode);
            }
            setOfConnectedNodes.add(fromNode);
            setOfConnectedNodes.add(toNode);
        }
        if (setOfMidmarkers.size() > 0) {
            if (setOfMidmarkers.size() == 1) {
                reaction.setMidmarker(setOfMidmarkers.iterator().next());
            } else {
                /*
                 * We have to separate all curve segments in this merged reaction, so
                 * that there is one such set for each midmarker.
                 * 
                 */
                Map<Node, Pair<Set<Node>, Set<Segment>>> midmarker2ReachableNodes = new HashMap<>();
                while (!listOfSegments.isEmpty()) {
                    for (Node midmarker : setOfMidmarkers) {
                        Set<Node> nodes;
                        Set<Segment> s;
                        if (!midmarker2ReachableNodes.containsKey(midmarker)) {
                            nodes = new HashSet<Node>();
                            s = new HashSet<Segment>();
                            nodes.add(midmarker);
                            midmarker2ReachableNodes.put(midmarker, pairOf(nodes, s));
                        } else {
                            Pair<Set<Node>, Set<Segment>> pair = midmarker2ReachableNodes.get(midmarker);
                            nodes = pair.getKey();
                            s = pair.getValue();
                        }
                        separateSegments(nodes, s, listOfSegments, escherMap);
                    }
                }

                /*
                 * Create one clone reaction for each midmarker and manipulate id and
                 * curve segments.
                 */
                EscherReaction reactions[] = new EscherReaction[setOfMidmarkers.size()];
                Iterator<Node> iterator = setOfMidmarkers.iterator();
                for (int i = 0; i < reactions.length; i++) {
                    Node midmarker = iterator.next();
                    reactions[i] = reaction.clone();
                    reactions[i].setMidmarker(midmarker);
                    reactions[i].setId(reaction.getId() + "_" + (i + 1));
                    linkSegmentsToReaction(reactions[i], midmarker2ReachableNodes.get(midmarker).getValue(),
                            escherMap);
                }
                return reactions;
            }
        }
        linkSegmentsToReaction(reaction, listOfSegments, escherMap);
    } else {
        logger.warning(MessageFormat.format(bundle.getString("EscherParser.cannotParse"),
                object.getClass().getName()));
    }
    return new EscherReaction[] { reaction };
}

From source file:com.impetus.ankush2.hadoop.utils.HadoopUtils.java

private static Set<String> getHostsFromJsonString(String nodesInfoJson, String nodeType)
        throws RegisterClusterException {
    JSONObject jsonNodesInfo = JsonMapperUtil.objectFromString(nodesInfoJson, JSONObject.class);
    if (jsonNodesInfo != null) {
        return jsonNodesInfo.keySet();
    }/*from w  w w  . j  a v a 2  s  .  c  o m*/
    throw new RegisterClusterException(
            "Could not fetch " + nodeType + " nodes information from NameNodeInfo bean.");
}

From source file:org.exfio.weave.storage.StorageContext.java

public Map<String, WeaveCollectionInfo> getInfoCollections(boolean getcount, boolean getusage)
        throws WeaveException {
    Log.getInstance().debug("getInfoCollections()");

    Map<String, WeaveCollectionInfo> wcols = new HashMap<String, WeaveCollectionInfo>();
    URI location = null;//www . j a  v  a 2s. c  o m
    JSONObject jsonObject = null;

    //Always get info/collections
    location = this.storageURL.resolve("info/collections");
    try {
        jsonObject = getJSONPayload(location);
    } catch (NotFoundException e) {
        throw new WeaveException("info/collections record not found - " + e.getMessage());
    }

    @SuppressWarnings("unchecked")
    Iterator<String> itCol = jsonObject.keySet().iterator();
    while (itCol.hasNext()) {
        String collection = itCol.next();
        WeaveCollectionInfo wcolInfo = new WeaveCollectionInfo(collection);
        wcolInfo.modified = JSONUtils.toDouble(jsonObject.get(collection));
        wcols.put(collection, wcolInfo);
    }

    //Optionally get info/collection_counts
    if (getcount) {
        location = this.storageURL.resolve("info/collection_counts");
        try {
            jsonObject = getJSONPayload(location);
        } catch (NotFoundException e) {
            throw new WeaveException("info/collection_counts record not found - " + e.getMessage());
        }

        @SuppressWarnings("unchecked")
        Iterator<String> itQuota = jsonObject.keySet().iterator();
        while (itQuota.hasNext()) {
            String collection = itQuota.next();
            if (wcols.containsKey(collection)) {
                wcols.get(collection).count = (Long) jsonObject.get(collection);
            } else {
                //quietly do nothing
                //throw new WeaveException(String.format("Collection '%s' not in info/collections", collection));
            }
        }
    }

    //Optionally get info/collection_usage
    if (getusage) {
        location = this.storageURL.resolve("info/collection_usage");
        try {
            jsonObject = getJSONPayload(location);
        } catch (NotFoundException e) {
            throw new WeaveException("info/collection_usage record not found - " + e.getMessage());
        }

        @SuppressWarnings("unchecked")
        Iterator<String> itUsage = jsonObject.keySet().iterator();
        while (itUsage.hasNext()) {
            String collection = itUsage.next();
            if (wcols.containsKey(collection)) {
                wcols.get(collection).usage = JSONUtils.toDouble(jsonObject.get(collection));
            } else {
                //quietly do nothing
                //throw new WeaveException(String.format("Collection '%s' not in info/collections", collection));
            }
        }
    }

    return wcols;
}

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

@Override
public ApiResponse getActiveOrders() {
    ApiResponse apiResponse = new ApiResponse();
    String url = API_BASE_URL + "/" + API_ORDER + "/" + API_LIST_ALL;
    HashMap<String, String> args = new HashMap<>();
    boolean isGet = false;
    ArrayList<Order> orderList = new ArrayList<>();

    ApiResponse response = getQuery(url, args, true, isGet);
    if (response.isPositive()) {
        JSONObject httpAnswerJson = (JSONObject) response.getResponseObject();
        JSONObject orders;
        try {//from  w  w  w .  java2  s .  co  m
            orders = (JSONObject) httpAnswerJson.get("orders");
        } catch (ClassCastException cce) {
            apiResponse.setResponseObject(orderList);
            return apiResponse;
        }
        Set<String> keys = orders.keySet();
        for (Iterator<String> key = keys.iterator(); key.hasNext();) {
            String thisKey = key.next();
            CurrencyPair thisPair = CurrencyPair.getCurrencyPairFromString(thisKey, "_");
            JSONArray pairOrders = (JSONArray) orders.get(thisKey);
            for (Iterator<JSONObject> order = pairOrders.iterator(); order.hasNext();) {
                orderList.add(parseOrder(order.next(), thisPair));
            }
        }
        apiResponse.setResponseObject(orderList);
    } else {
        apiResponse = response;
    }

    return apiResponse;
}