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:com.apigee.edge.config.mavenplugin.KVMMojo.java

public static List getAPIKVM(ServerProfile profile, String api) throws IOException {

    HttpResponse response = RestUtil.getAPIConfig(profile, api, "keyvaluemaps");
    if (response == null)
        return new ArrayList();
    JSONArray kvms = null;//from   www .  jav  a  2 s.com
    try {
        logger.debug("output " + response.getContentType());
        // response can be read only once
        String payload = response.parseAsString();
        logger.debug(payload);

        /* Parsers fail to parse a string array.
         * converting it to an JSON object as a workaround */
        String obj = "{ \"kvms\": " + payload + "}";

        JSONParser parser = new JSONParser();
        JSONObject obj1 = (JSONObject) parser.parse(obj);
        kvms = (JSONArray) obj1.get("kvms");

    } catch (ParseException pe) {
        logger.error("Get KVM parse error " + pe.getMessage());
        throw new IOException(pe.getMessage());
    } catch (HttpResponseException e) {
        logger.error("Get KVM error " + e.getMessage());
        throw new IOException(e.getMessage());
    }

    return kvms;
}

From source file:hoot.services.controllers.job.JobResource.java

private static void setJobInfo(JSONObject jobInfo, JSONObject child, JSONArray children, String stat,
        String detail) {/*w ww  .j a v  a 2s . c o  m*/
    for (Object aChildren : children) {
        JSONObject c = (JSONObject) aChildren;
        if (c.get("id").toString().equals(child.get("id").toString())) {
            c.put("status", stat);
            c.put("detail", detail);
            return;
        }
    }

    child.put("status", stat);
    child.put("detail", detail);
    children.add(child);
    jobInfo.put("children", children);
}

From source file:com.walmartlabs.mupd8.application.Config.java

public static Object getScopedValue(JSONObject object, String[] path) {
    if (path == null) {
        throw new NullPointerException("path parameter to getScopedValue may not be null");
    }//from   w  w w.  j a  va2s . c  om
    if (path.length == 0) {
        return object;
    }
    String key = path[0];
    if (!object.containsKey(key)) {
        // TODO ...or return new JSONObject()?
        return null;
    }
    if (path.length == 1) {
        return object.get(key); // not necessarily JSONObject
    }
    return getScopedValue((JSONObject) object.get(key), Arrays.copyOfRange(path, 1, path.length));
}

From source file:com.cloudera.hoop.client.fs.HoopFileSystem.java

/**
 * Validates the status of an <code>HttpURLConnection</code> against an expected HTTP
 * status code. If the current status code is not the expected one it throws an exception
 * with a detail message using Server side error messages if available.
 *
 * @param conn the <code>HttpURLConnection</code>.
 * @param expected the expected HTTP status code.
 * @throws IOException thrown if the current status code does not match the expected one.
 *//*from  w w w.ja v  a 2s  .  c  om*/
private static void validateResponse(HttpURLConnection conn, int expected) throws IOException {
    int status = conn.getResponseCode();
    if (status != expected) {
        try {
            JSONObject json = (JSONObject) jsonParse(conn);
            throw new IOException(MessageFormat.format("HTTP status [{0}], {1} - {2}", json.get("status"),
                    json.get("reason"), json.get("message")));
        } catch (IOException ex) {
            if (ex.getCause() instanceof IOException) {
                throw (IOException) ex.getCause();
            }
            throw new IOException(
                    MessageFormat.format("HTTP status [{0}], {1}", status, conn.getResponseMessage()));
        }
    }
}

From source file:hoot.services.controllers.job.JobResource.java

private static Map<String, String> paramsToMap(JSONObject command) {
    JSONArray paramsList = (JSONArray) command.get("params");

    Map<String, String> paramsMap = new HashMap<>();
    for (Object aParamsList : paramsList) {
        JSONObject o = (JSONObject) aParamsList;
        for (Object o1 : o.entrySet()) {
            Map.Entry<Object, Object> mEntry = (Map.Entry<Object, Object>) o1;
            String key = (String) mEntry.getKey();
            String val = (String) mEntry.getValue();
            paramsMap.put(key, val);
        }// ww  w  . j a  va  2s.com
    }
    return paramsMap;
}

From source file:at.ac.tuwien.dsg.rSybl.planningEngine.staticData.ActionEffects.java

public static void setActionEffects(String eff) {
    PlanningLogger.logger.info("~~~~~~~~~~Action effects set through web serv, setting the effects ! ");

    JSONParser parser = new JSONParser();
    applicationSpecificActionEffects = new HashMap<String, List<ActionEffect>>();
    Object obj;/*  w ww.j  a v  a2s  .  c o m*/
    try {
        obj = parser.parse(eff);

        JSONObject jsonObject = (JSONObject) obj;

        for (Object actionName : jsonObject.keySet()) {

            String myaction = (String) actionName;

            JSONObject object = (JSONObject) jsonObject.get(myaction);

            for (Object actions : object.keySet()) {
                ActionEffect actionEffect = new ActionEffect();
                actionEffect.setActionType((String) myaction);
                actionEffect.setActionName((String) actions);
                JSONObject scaleinDescription = (JSONObject) object.get(actions);
                if (scaleinDescription.containsKey("conditions")) {
                    JSONArray conditions = (JSONArray) jsonObject.get("conditions");
                    for (int i = 0; i < conditions.size(); i++) {
                        actionEffect.addCondition((String) conditions.get(i));
                    }
                }
                String targetUnit = (String) scaleinDescription.get("targetUnit");
                actionEffect.setTargetedEntityID(targetUnit);

                JSONObject effects = (JSONObject) scaleinDescription.get("effects");

                for (Object effectPerUnit : effects.keySet()) {
                    //System.out.println(effects.toString());
                    String affectedUnit = (String) effectPerUnit;
                    JSONObject metriceffects = (JSONObject) effects.get(affectedUnit);
                    for (Object metric : metriceffects.keySet()) {
                        String metricName = (String) metric;
                        try {
                            actionEffect.setActionEffectForMetric(metricName,
                                    (Double) metriceffects.get(metricName), affectedUnit);
                        } catch (Exception e) {
                            actionEffect.setActionEffectForMetric(metricName,
                                    ((Long) metriceffects.get(metricName)).doubleValue(), affectedUnit);
                        }
                    }

                }

                if (!applicationSpecificActionEffects.containsKey(actionEffect.getTargetedEntityID().trim())) {
                    List<ActionEffect> l = new ArrayList<ActionEffect>();
                    l.add(actionEffect);
                    applicationSpecificActionEffects.put(actionEffect.getTargetedEntityID().trim(), l);
                    //PlanningLogger.logger.info("New Action effects "+actionEffect.getActionType()+" "+actionEffect.getActionName()+" "+actionEffect.getTargetedEntityID());

                } else {
                    applicationSpecificActionEffects.get(actionEffect.getTargetedEntityID().trim())
                            .add(actionEffect);
                    //PlanningLogger.logger.info("Adding Action effects "+actionEffect.getActionType()+" "+actionEffect.getActionName()+" "+actionEffect.getTargetedEntityID());

                }
            }
        }
    } catch (ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}

From source file:it.polimi.geinterface.network.MessageUtils.java

/**
 * Method that return the sender {@link Entity} identifier from a message 
 *//*  www  .  ja  va2 s .  c  o  m*/
public static String getSenderID(String msgJson) {
    JSONParser parser = new JSONParser();
    JSONObject jsonMsg;
    String senderID = "";
    try {
        jsonMsg = (JSONObject) parser.parse(msgJson);
        JSONObject message = (JSONObject) jsonMsg.get(JsonStrings.MESSAGE);
        senderID = (String) message.get(JsonStrings.SENDER);
        return senderID;
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:iracing.webapi.TrackParser.java

public static List<Track> parse(String json) {
    JSONParser parser = new JSONParser();
    List<Track> output = null;
    try {/*from  w  w w .  j a va2 s.  c  om*/
        //[{"config":"Legends+Oval","priority":3,"pkgid":36,"skuname":"Atlanta+Motor+Speedway","retired":0,"price":14.95,"hasNightLighting":false,"name":"Atlanta+Motor+Speedway","lowername":"atlanta+motor+speedway","nominalLapTime":15.5574207,"lowerNameAndConfig":"atlanta+motor+speedway+legends+oval","catid":1,"priceDisplay":"14.95","id":52,"sku":10039},{"config":"Road+Course","priority":2,"pkgid":36,"skuname":"Atlanta+Motor+Speedway","retired":0,"price":14.95,"hasNightLighting":false,"name":"Atlanta+Motor+Speedway","lowername":"atlanta+motor+speedway","nominalLapTime":82.5555344,"lowerNameAndConfig":"atlanta+motor+speedway+road+course","catid":2,"priceDisplay":"14.95","id":51,"sku":10039}]
        JSONArray root = (JSONArray) parser.parse(json);
        output = new ArrayList<Track>();
        for (int i = 0; i < root.size(); i++) {
            JSONObject o = (JSONObject) root.get(i);
            Track track = new Track();
            track.setId(getInt(o, "id"));
            track.setPackageId(getInt(o, "pkgid"));
            track.setCategoryId(getInt(o, "catid"));
            track.setPriority(getInt(o, "priority"));
            track.setSku(getLong(o, "sku"));
            track.setSkuName(getString(o, "skuname", true));
            track.setRetired((getInt(o, "retired")) == 1);
            track.setName(getString(o, "name", true));
            track.setConfigName(getString(o, "config", true));
            track.setHasNightLighting((Boolean) o.get("hasNightLighting"));
            track.setPrice(getDouble(o, "price"));
            track.setPriceDisplay(getString(o, "priceDisplay"));
            track.setNominalLapTime(getDouble(o, "nominalLapTime"));
            output.add(track);
        }
    } catch (ParseException ex) {
        Logger.getLogger(LicenseParser.class.getName()).log(Level.SEVERE, null, ex);
    }
    return output;
}

From source file:it.polimi.geinterface.network.MessageUtils.java

/**
 * Method retrieving message type form a {@link String} representing the message received.
 *//*from  w w  w .  j  a va2  s  .  co  m*/
public static MessageType getMsgType(String msgJson) {

    JSONParser parser = new JSONParser();
    JSONObject jsonMsg;
    String msgType = "";
    try {
        jsonMsg = (JSONObject) parser.parse(msgJson);
        JSONObject message = (JSONObject) jsonMsg.get(JsonStrings.MESSAGE);
        msgType = ((String) message.get(JsonStrings.MSG_TYPE)).toUpperCase().trim();
    } catch (ParseException e) {
        e.printStackTrace();
    }

    for (MessageType type : MessageType.values())
        if (type.name().equals(msgType))
            return type;

    return null;
}

From source file:at.ac.tuwien.dsg.rSybl.planningEngine.staticData.ActionEffects.java

public static HashMap<String, List<ActionEffect>> getActionEffects() {
    if (applicationSpecificActionEffects.isEmpty()) {
        PlanningLogger.logger.info("~~~~~~~~~~Action effects is empty, reading the effects ! ");
        JSONParser parser = new JSONParser();

        try {//w w w.j a v a  2 s .  c om
            InputStream inputStream = Configuration.class.getClassLoader()
                    .getResourceAsStream(Configuration.getEffectsPath());
            Object obj = parser.parse(new InputStreamReader(inputStream));

            JSONObject jsonObject = (JSONObject) obj;

            for (Object actionName : jsonObject.keySet()) {

                String myaction = (String) actionName;

                JSONObject object = (JSONObject) jsonObject.get(myaction);

                for (Object actions : object.keySet()) {
                    ActionEffect actionEffect = new ActionEffect();
                    actionEffect.setActionType((String) myaction);
                    actionEffect.setActionName((String) actions);
                    JSONObject scaleinDescription = (JSONObject) object.get(actions);
                    String targetUnit = (String) scaleinDescription.get("targetUnit");
                    actionEffect.setTargetedEntityID(targetUnit);

                    JSONObject effects = (JSONObject) scaleinDescription.get("effects");

                    for (Object effectPerUnit : effects.keySet()) {
                        //System.out.println(effects.toString());
                        String affectedUnit = (String) effectPerUnit;
                        JSONObject metriceffects = (JSONObject) effects.get(affectedUnit);
                        for (Object metric : metriceffects.keySet()) {
                            String metricName = (String) metric;
                            try {
                                actionEffect.setActionEffectForMetric(metricName,
                                        (Double) metriceffects.get(metricName), affectedUnit);
                            } catch (Exception e) {
                                actionEffect.setActionEffectForMetric(metricName,
                                        ((Long) metriceffects.get(metricName)).doubleValue(), affectedUnit);
                            }
                        }

                    }

                    if (applicationSpecificActionEffects.get(actionEffect.getTargetedEntityID()) == null) {
                        List<ActionEffect> l = new ArrayList<ActionEffect>();
                        l.add(actionEffect);
                        applicationSpecificActionEffects.put(actionEffect.getTargetedEntityID(), l);

                    } else {
                        applicationSpecificActionEffects.get(actionEffect.getTargetedEntityID())
                                .add(actionEffect);
                    }
                }

            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }
    return applicationSpecificActionEffects;
}