Example usage for org.json JSONObject getNames

List of usage examples for org.json JSONObject getNames

Introduction

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

Prototype

public static String[] getNames(Object object) 

Source Link

Document

Get an array of field names from an Object.

Usage

From source file:com.jennifer.ui.util.DomUtil.java

public DomUtil css(JSONObject o) {

    String[] names = JSONObject.getNames(o);

    for (String key : names) {
        css(key, o.get(key));//from   w ww  .j  a  v a  2s. com
    }

    return this;
}

From source file:org.everit.json.schema.ObjectComparator.java

private static boolean deepEqualObjects(final JSONObject jsonObj1, final JSONObject jsonObj2) {
    String[] obj1Names = JSONObject.getNames(jsonObj1);
    if (!Arrays.equals(obj1Names, JSONObject.getNames(jsonObj2))) {
        return false;
    }// w  ww.j ava2 s  . com
    if (obj1Names == null) {
        return true;
    }
    for (String name : obj1Names) {
        if (!deepEquals(jsonObj1.get(name), jsonObj2.get(name))) {
            return false;
        }
    }
    return true;
}

From source file:gr.cti.android.experimentation.controller.api.AndroidExperimentationWS.java

private Result extractResultFromBody(String body) throws JSONException, IOException {

    body = body.replaceAll("atributeType", "attributeType")
            .replaceAll("org.ambientdynamix.contextplugins.NoiseLevel",
                    OrganicityAttributeTypes.Types.SOUND_PRESSURE_LEVEL.getUrn())
            .replaceAll("org.ambientdynamix.contextplugins.sound",
                    OrganicityAttributeTypes.Types.SOUND_PRESSURE_LEVEL.getUrn())
            .replaceAll("org.ambientdynamix.contextplugins.10pm",
                    OrganicityAttributeTypes.Types.PARTICLES10.getUrn())
            .replaceAll("org.ambientdynamix.contextplugins.25pm",
                    OrganicityAttributeTypes.Types.PARTICLES25.getUrn())
            .replaceAll("org.ambientdynamix.contextplugins.co",
                    OrganicityAttributeTypes.Types.CARBON_MONOXIDE.getUrn())
            .replaceAll("org.ambientdynamix.contextplugins.lpg", OrganicityAttributeTypes.Types.LPG.getUrn())
            .replaceAll("org.ambientdynamix.contextplugins.ch4",
                    OrganicityAttributeTypes.Types.METHANE.getUrn())
            .replaceAll("org.ambientdynamix.contextplugins.temperature",
                    OrganicityAttributeTypes.Types.TEMPERATURE.getUrn())
            .replaceAll("org.ambientdynamix.contextplugins.battery%",
                    OrganicityAttributeTypes.Types.BATTERY_LEVEL.getUrn())
            .replaceAll("org.ambientdynamix.contextplugins.batteryv",
                    OrganicityAttributeTypes.Types.BATTERY_VOLTAGE.getUrn());

    Report result = new ObjectMapper().readValue(body, Report.class);
    LOGGER.info("saving for deviceId:" + result.getDeviceId() + " jobName:" + result.getJobName());
    final Smartphone phone = smartphoneRepository.findById(result.getDeviceId());
    final Experiment experiment = experimentRepository.findById(Integer.parseInt(result.getJobName()));
    LOGGER.info("saving for PhoneId:" + phone.getPhoneId() + " ExperimentName:" + experiment.getName());

    final Result newResult = new Result();
    final JSONObject objTotal = new JSONObject();

    for (final String jobResult : result.getJobResults()) {

        LOGGER.info(jobResult);/*ww  w  .  j av a 2  s.  co  m*/
        if (jobResult.isEmpty()) {
            continue;
        }

        final Reading readingObj = new ObjectMapper().readValue(jobResult, Reading.class);
        final String value = readingObj.getValue();
        final long readingTime = readingObj.getTimestamp();

        try {
            final Set<Result> res = resultRepository.findByExperimentIdAndDeviceIdAndTimestampAndMessage(
                    experiment.getId(), phone.getId(), readingTime, value);
            if (!res.isEmpty()) {
                continue;
            }
        } catch (Exception e) {
            LOGGER.error(e, e);
        }
        LOGGER.info(jobResult);
        newResult.setDeviceId(phone.getId());
        newResult.setExperimentId(experiment.getId());
        final JSONObject obj = new JSONObject(value);
        for (final String key : JSONObject.getNames(obj)) {
            objTotal.put(key, obj.get(key));
        }
        newResult.setTimestamp(readingTime);
    }

    newResult.setMessage(objTotal.toString());

    LOGGER.info(newResult.toString());
    return newResult;
}

From source file:org.uiautomation.ios.grid.IOSCapabilitiesMonitor.java

private List<DesiredCapabilities> getNodeCapabilities() {
    try {/*from   w w w. jav  a  2 s  .  c om*/
        List<DesiredCapabilities> capabilities = new ArrayList<DesiredCapabilities>();

        JSONObject status = getNodeStatusJson();
        if (status == null) {
            return null;
        }

        String ios = status.getJSONObject("value").getJSONObject("ios").optString("simulatorVersion");
        JSONArray supportedApps = status.getJSONObject("value").getJSONArray("supportedApps");

        for (int i = 0; i < supportedApps.length(); i++) {
            Map<String, Object> capability = new HashMap<String, Object>();
            capability.put("maxInstances", "1");
            if (ios.isEmpty()) {
                capability.put("ios", "5.1");
                capability.put("browserName", "IOS Device");
                capability.put(IOSCapabilities.DEVICE, DeviceType.iphone);
            } else {
                capability.put("ios", ios);
                capability.put("browserName", "IOS Simulator");
            }
            JSONObject app = supportedApps.getJSONObject(i);
            for (String key : JSONObject.getNames(app)) {
                if ("locales".equals(key)) {
                    JSONArray loc = app.getJSONArray(key);
                    List<String> locales = new ArrayList<String>();
                    for (int j = 0; j < loc.length(); j++) {
                        locales.add(loc.getString(j));
                    }
                    capability.put("locales", locales);
                } else {
                    Object o = app.get(key);
                    capability.put(key, o);
                }
            }
            capabilities.add(new DesiredCapabilities(capability));
        }
        return capabilities;
    } catch (Exception e) {
        return null;
    }
}

From source file:com.grillecube.editor.ModelEditor.java

private void fillConfig(JSONObject json) {
    this._config = new HashMap<String, Integer>();
    String[] keys = JSONObject.getNames(json);

    for (String key : keys) {
        try {/* ww w  .jav  a  2s. c  om*/
            this._config.put(key, json.getInt(key));
        } catch (Exception e) {
            Logger.get().log(Level.ERROR, "Config value can only be integer!");
        }
    }
}

From source file:org.dasein.cloud.benchmark.Suite.java

static public void main(String... args) throws Exception {
    ArrayList<Map<String, Object>> suites = new ArrayList<Map<String, Object>>();
    ArrayList<Map<String, Object>> tests = new ArrayList<Map<String, Object>>();

    for (String suiteFile : args) {
        HashMap<String, Object> suite = new HashMap<String, Object>();

        ArrayList<Benchmark> benchmarks = new ArrayList<Benchmark>();

        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(suiteFile)));
        StringBuilder json = new StringBuilder();
        String line;// w  ww .j  a v a 2s .c  om

        while ((line = reader.readLine()) != null) {
            json.append(line);
            json.append("\n");
        }
        JSONObject ob = new JSONObject(json.toString());

        suite.put("name", ob.getString("name"));
        suite.put("description", ob.getString("description"));

        JSONArray benchmarkClasses = ob.getJSONArray("benchmarks");

        for (int i = 0; i < benchmarkClasses.length(); i++) {
            String cname = benchmarkClasses.getString(i);

            benchmarks.add((Benchmark) Class.forName(cname).newInstance());
        }

        JSONArray clouds = ob.getJSONArray("clouds");

        for (int i = 0; i < clouds.length(); i++) {
            JSONObject cloud = clouds.getJSONObject(i);

            if (cloud.has("regions")) {
                JSONObject regions = cloud.getJSONObject("regions");
                String[] regionIds = JSONObject.getNames(regions);

                if (regionIds != null) {
                    for (String regionId : regionIds) {
                        final JSONObject regionCfg = regions.getJSONObject(regionId);
                        String cname = cloud.getString("providerClass");
                        CloudProvider provider = (CloudProvider) Class.forName(cname).newInstance();
                        JSONObject ctxCfg = cloud.getJSONObject("context");
                        ProviderContext ctx = new ProviderContext();

                        ctx.setEndpoint(regionCfg.getString("endpoint"));
                        ctx.setAccountNumber(ctxCfg.getString("accountNumber"));
                        ctx.setRegionId(regionId);
                        if (ctxCfg.has("accessPublic")) {
                            ctx.setAccessPublic(ctxCfg.getString("accessPublic").getBytes("utf-8"));
                        }
                        if (ctxCfg.has("accessPrivate")) {
                            ctx.setAccessPrivate(ctxCfg.getString("accessPrivate").getBytes("utf-8"));
                        }
                        ctx.setCloudName(ctxCfg.getString("cloudName"));
                        ctx.setProviderName(ctxCfg.getString("providerName"));
                        if (ctxCfg.has("x509Cert")) {
                            ctx.setX509Cert(ctxCfg.getString("x509Cert").getBytes("utf-8"));
                        }
                        if (ctxCfg.has("x509Key")) {
                            ctx.setX509Key(ctxCfg.getString("x509Key").getBytes("utf-8"));
                        }
                        if (ctxCfg.has("customProperties")) {
                            JSONObject p = ctxCfg.getJSONObject("customProperties");
                            String[] names = JSONObject.getNames(p);

                            if (names != null) {
                                Properties props = new Properties();

                                for (String name : names) {
                                    String value = p.getString(name);

                                    if (value != null) {
                                        props.put(name, value);
                                    }
                                }
                                ctx.setCustomProperties(props);
                            }
                        }
                        provider.connect(ctx);

                        Suite s = new Suite(benchmarks, provider);

                        tests.add(s.runBenchmarks(regionCfg));
                    }
                }
            }
        }
        suite.put("benchmarks", tests);
        suites.add(suite);
    }
    System.out.println((new JSONArray(suites)).toString());
}

From source file:com.sonoport.freesound.response.mapping.Mapper.java

/**
 * Transform a JSON dictionary into a {@link Map} of key-value pairs.
 *
 * @param jsonDictionaryObject The dictionary object to convert
 * @return {@link Map} of values/*from w  w w . j a  v a 2 s.c  o  m*/
 */
protected Map<String, String> parseDictionary(final JSONObject jsonDictionaryObject) {
    final Map<String, String> dictionaryAsMap = new HashMap<>();
    if (jsonDictionaryObject != null) {
        for (final String key : JSONObject.getNames(jsonDictionaryObject)) {
            dictionaryAsMap.put(key, extractFieldValue(jsonDictionaryObject, key, String.class));
        }
    }

    return dictionaryAsMap;
}

From source file:com.rapid.actions.Timer.java

public Timer(RapidHttpServlet rapidServlet, JSONObject jsonAction) throws Exception {
    // call super constructor to set xml version
    super();//ww w  .ja  v a 2 s  .  com
    // save all key/values from the json into the properties 
    for (String key : JSONObject.getNames(jsonAction)) {
        // add all json properties to our properties (except for sessionVariables)
        if (!"actions".equals(key))
            addProperty(key, jsonAction.get(key).toString());
    }
    // grab any actions
    JSONArray jsonActions = jsonAction.optJSONArray("actions");
    // if we had some instantiate our collection
    if (jsonActions != null)
        _actions = Control.getActions(rapidServlet, jsonActions);

}

From source file:pt.webdetails.cdb.query.AbstractQuery.java

@Override
public void fromJSON(JSONObject json) {
    String _id, _key, _group, _name;
    HashMap<String, Object> _properties = new HashMap<String, Object>();
    try {//from   www. j  av a 2  s  . com
        /* Load everything into temporary variables */
        _id = json.getString("guid");
        _key = json.getString("@rid");
        _group = json.getString("group");
        _name = json.getString("name");
        JSONObject props = json.getJSONObject("definition");
        for (String key : JSONObject.getNames(props)) {
            _properties.put(key, props.get(key));
        }
        /* Seems like we managed to safely load everything, so it's
         * now safe to copy all the values over to the object
         */
        id = _id;
        key = _key;
        group = _group;
        name = _name;
        properties = _properties;
    } catch (JSONException jse) {
        logger.error("Error while reading values from JSON", jse);
    }
}

From source file:com.rapid.actions.Logic.java

public Logic(RapidHttpServlet rapidServlet, JSONObject jsonAction) throws Exception {
    // call the super parameterless constructor which sets the xml version
    super();//www .j a  v  a  2s . c  om
    // save all key/values from the json into the properties 
    for (String key : JSONObject.getNames(jsonAction)) {
        // add all json properties to our properties, except for the ones we want directly accessible
        if (!"conditions".equals(key) && !"conditionsType".equals(key) && !"trueActions".equals(key)
                && !"falseActions".equals(key))
            addProperty(key, jsonAction.get(key).toString());
    }

    // initialise list
    _conditions = new ArrayList<Condition>();
    // grab conditions from json
    JSONArray jsonConditions = jsonAction.optJSONArray("conditions");

    // if we got some
    if (jsonConditions != null) {
        // loop them
        for (int i = 0; i < jsonConditions.length(); i++) {
            // add to our list
            _conditions.add(new Condition(jsonConditions.getJSONObject(i)));
        }
    }

    // get conditions type
    _conditionsType = jsonAction.getString("conditionsType");

    // grab any successActions
    JSONArray jsonTrueActions = jsonAction.optJSONArray("trueActions");
    // if we had some
    if (jsonTrueActions != null) {
        _trueActions = Control.getActions(rapidServlet, jsonTrueActions);
    }

    // grab any errorActions
    JSONArray jsonFalseActions = jsonAction.optJSONArray("falseActions");
    // if we had some
    if (jsonFalseActions != null) {
        // instantiate our contols collection
        _falseActions = Control.getActions(rapidServlet, jsonFalseActions);
    }

}