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:it.polimi.geinterface.network.MessageUtils.java

/**
 * Method returning a list of {@link Entity} objects retrieved from a message having type {@link MessageType#PROX_BEACONS} or 
 * {@link MessageType#SYNC_RESP}/*from w  w  w . j a v a 2s .com*/
 */
public static ArrayList<Entity> getBeaconsFromMsg(String message) {

    JSONObject jsonMsg;
    JSONParser parser = new JSONParser();
    MessageType type = getMsgType(message);

    if (type.ordinal() == MessageType.PROX_BEACONS.ordinal()
            || type.ordinal() == MessageType.SYNC_REQ.ordinal())
        try {
            jsonMsg = (JSONObject) parser.parse(message);
            JSONObject msg = (JSONObject) jsonMsg.get(JsonStrings.MESSAGE);
            JSONArray beaconsJsonArray = (JSONArray) msg.get(JsonStrings.BEACONS);
            ArrayList<Entity> beacons = new ArrayList<>();
            for (Object o : beaconsJsonArray) {
                JSONObject beaconJsonObject = (JSONObject) o;
                String beaconId = (String) beaconJsonObject.get(JsonStrings.BEACON_ID);
                String jsonDistance = (String) beaconJsonObject.get(JsonStrings.DISTANCE_RANGE);
                DistanceRange distance = null;
                for (DistanceRange d : DistanceRange.values())
                    if (d.name().equals(jsonDistance))
                        distance = d;
                Entity beacon = new Entity.Builder(beaconId, Type.BLE_BEACON).setDistance(distance).build();
                beacons.add(beacon);
            }
            return beacons;
        } catch (ParseException e) {
            e.printStackTrace();
        }
    return null;
}

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

/**
 * Parses the json, extracts the rules and deploy those rules into modsecurity. It takes the rule 
 * string from the json and creates a rule file then copy it to modsecurity rule file folder. It alsp
 * restarts the modsecurity after deploying the rule
 * @param json reponses whether the rule is successfully deployed or not.
 *//*from  w  ww .j a v  a  2  s.  c o  m*/
@SuppressWarnings("unchecked")
public static void onDeployMSRules(JSONObject json) {

    log.info("onDeployMSRules called.. : " + json.toJSONString());

    MSConfig serviceCfg = MSConfig.getInstance();
    JSONObject jsonResp = new JSONObject();

    String ruleDirPath = serviceCfg.getConfigMap().get("RuleFileDir");
    String ruleFileString = (String) json.get("ruleString");
    String ruleFileName = "";

    InputStream ins = null;
    FileOutputStream out = null;
    BufferedReader br = null;

    if (json.containsKey("groupName")) {

        ruleFileName += ((String) json.get("groupName")).toLowerCase() + ".conf";

    } else {

        UUID randomName = UUID.randomUUID();
        ruleFileName += randomName.toString() + ".conf";

    }

    try {

        //modified string writing to modsecurity configurations
        log.info("Writing a rule to File :" + ruleFileName);
        File file = new File(ruleDirPath + "/" + ruleFileName);
        file.createNewFile();
        out = new FileOutputStream(file);
        out.write(ruleFileString.getBytes());
        out.close();

        log.info("ModSecurity Rules Written ... ");

        //For Restarting modsecurity so that modified configuration can be applied
        JSONObject restartJson = new JSONObject();
        restartJson.put("action", "restart");

        String cmd = serviceCfg.getConfigMap().get("MSRestart");

        String status = (String) executeShScript(cmd, restartJson).get("status");

        //if rule file is giving syntax error while deploying rules on server end 
        if (status.equals("1")) {

            if (file.delete()) {
                log.info("Successfully deleted conflicting file : " + file.getName());
                executeShScript(cmd, restartJson);
            } else {
                log.info("unable to delete file : " + file.getName());
            }
            jsonResp.put("action", "deployRules");
            jsonResp.put("status", "1");
            jsonResp.put("message", "Unable to deploy specified Rules. They either"
                    + "conflicting to the already deployed rules");

        } else {

            jsonResp.put("action", "deployRules");
            jsonResp.put("status", "0");
            jsonResp.put("message", "Rules Deployed!");

        }

    } catch (FileNotFoundException e1) {

        jsonResp.put("action", "deployRules");
        jsonResp.put("status", "1");
        jsonResp.put("message", "Internal Service is down!");
        e1.printStackTrace();

    } catch (IOException | NullPointerException e) {

        jsonResp.put("action", "deployRules");
        jsonResp.put("status", "0");
        jsonResp.put("message", "Unable to create rule file on Server.");
        e.printStackTrace();

    }

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

From source file:com.nubits.nubot.options.OptionsJSON.java

public static JSONObject parseFiles(ArrayList<String> filePaths) {
    JSONObject optionsObject = new JSONObject();
    Map setMap = new HashMap();

    for (int i = 0; i < filePaths.size(); i++) {
        try {/*from w ww  . j  av a  2s. c om*/
            JSONParser parser = new JSONParser();

            JSONObject fileJSON = (JSONObject) (parser.parse(FileSystem.readFromFile(filePaths.get(i))));
            JSONObject tempOptions = (JSONObject) fileJSON.get("options");

            Set tempSet = tempOptions.entrySet();
            for (Object o : tempSet) {
                Map.Entry entry = (Map.Entry) o;
                setMap.put(entry.getKey(), entry.getValue());
            }

        } catch (ParseException ex) {
            LOG.severe("Parse exception \n" + ex.toString());
            System.exit(0);
        }
    }

    JSONObject content = new JSONObject(setMap);
    optionsObject.put("options", content);
    return optionsObject;
}

From source file:eu.wordnice.wnconsole.WNCUtils.java

public static Map<String, Object> sortObject(JSONObject jo) {
    Object[] names = new Object[jo.size()];
    Object[] values = new Object[jo.size()];
    boolean[] used = new boolean[jo.size()];
    boolean curHas = false;
    Object[] in = jo.keySet().toArray();
    int i = 0;/*from  w  w w .  java 2 s .c  o  m*/
    int i2 = 0;
    for (; i < jo.size(); i++) {
        curHas = false;
        for (i2 = 0; i2 < jo.size(); i2++) {
            String cname = (String) in[i2];
            if (!used[i2] && cname.startsWith("get")) {
                names[i] = ("" + cname);
                values[i] = jo.get(cname);
                used[i2] = true;
                curHas = true;
                break;
            }
        }
        if (!curHas) {
            break;
        }
    }

    i2 = 0;
    for (/* continue */; i < jo.size(); i++) {
        for (/* continue */; i2 < jo.size(); i2++) {
            String cname = (String) in[i2];
            if (!used[i2]) {
                names[i] = cname;
                values[i] = jo.get(cname);
                used[i2] = true;
                curHas = true;
                break;
            }
        }
    }
    Map<String, Object> map = new Map<String, Object>();
    map.names = names;
    map.values = values;
    map.size = names.length;
    return map;
}

From source file:com.stratio.deep.commons.utils.CellsUtils.java

/**
 * Gets object from json.//from  w  w w.  jav a 2s  .  c o  m
 *
 * @param classEntity the class entity
 * @param bsonObject  the bson object
 * @return the object from json
 * @throws IllegalAccessException    the illegal access exception
 * @throws InstantiationException    the instantiation exception
 * @throws InvocationTargetException the invocation target exception
 */
public static <T> T getObjectFromJson(Class<T> classEntity, JSONObject bsonObject)
        throws IllegalAccessException, InstantiationException, InvocationTargetException {
    T t = classEntity.newInstance();

    Field[] fields = AnnotationUtils.filterDeepFields(classEntity);

    Object insert = null;

    for (Field field : fields) {
        Object currentBson = null;
        Method method = null;
        try {
            method = Utils.findSetter(field.getName(), classEntity, field.getType());

            Class<?> classField = field.getType();

            currentBson = bsonObject.get(AnnotationUtils.deepFieldName(field));
            if (currentBson != null) {

                if (Iterable.class.isAssignableFrom(classField)) {
                    Type type = field.getGenericType();

                    insert = subDocumentListCase(type,
                            (List) bsonObject.get(AnnotationUtils.deepFieldName(field)));

                } else if (IDeepType.class.isAssignableFrom(classField)) {
                    insert = getObjectFromJson(classField,
                            (JSONObject) bsonObject.get(AnnotationUtils.deepFieldName(field)));
                } else {
                    insert = currentBson;
                }
                method.invoke(t, insert);
            }
        } catch (IllegalAccessException | InstantiationException | InvocationTargetException
                | IllegalArgumentException e) {
            LOG.error("impossible to create a java object from Bson field:" + field.getName() + " and type:"
                    + field.getType() + " and value:" + t + "; bsonReceived:" + currentBson
                    + ", bsonClassReceived:" + currentBson.getClass());

            method.invoke(t, Utils.castNumberType(insert, t.getClass()));
        }

    }

    return t;
}

From source file:com.stratio.deep.commons.utils.CellsUtils.java

public static <T> T getObjectWithMapFromJson(Class<T> classEntity, JSONObject bsonObject)
        throws IllegalAccessException, InstantiationException, InvocationTargetException {
    T t = classEntity.newInstance();//from w  w  w  . j a v a2  s  .c  o m

    Field[] fields = AnnotationUtils.filterDeepFields(classEntity);

    Object insert = null;

    for (Field field : fields) {
        Object currentBson = null;
        Method method = null;
        try {
            method = Utils.findSetter(field.getName(), classEntity, field.getType());

            Class<?> classField = field.getType();

            currentBson = bsonObject.get(AnnotationUtils.deepFieldName(field));
            if (currentBson != null) {

                if (Collection.class.isAssignableFrom(classField)) {
                    Type type = field.getGenericType();
                    List list = new ArrayList();
                    for (Object o : (List) bsonObject.get(AnnotationUtils.deepFieldName(field))) {
                        list.add((String) o);
                    }
                    insert = list;

                } else if (IDeepType.class.isAssignableFrom(classField)) {
                    insert = getObjectFromJson(classField,
                            (JSONObject) bsonObject.get(AnnotationUtils.deepFieldName(field)));
                } else {
                    insert = currentBson;
                }
                if (insert != null) {
                    method.invoke(t, insert);
                }

            }
        } catch (IllegalAccessException | InstantiationException | InvocationTargetException
                | IllegalArgumentException e) {
            LOG.error("impossible to create a java object from Bson field:" + field.getName() + " and type:"
                    + field.getType() + " and value:" + t + "; bsonReceived:" + currentBson
                    + ", bsonClassReceived:" + currentBson.getClass());
            method.invoke(t, Utils.castNumberType(insert, t.getClass()));
        }

    }

    return t;
}

From source file:mas.MAS.java

public static void extractConference(int start) {
    String file_prefix = "conferences";
    String csv_file_path = "data/" + file_prefix + ".csv";
    String json_dump_file_path = "data/" + file_prefix + "_dump.json";
    String url = "https://api.datamarket.azure.com/MRC/MicrosoftAcademic/v2/Conference?";
    url += "$format=json";
    while (true) {
        try {/*from w  w w .j  a va2 s . c  o  m*/
            StringBuilder csv_str = new StringBuilder();
            final String json = getData2(url, start);
            JSONParser parser = new JSONParser();
            JSONObject jsonObj = (JSONObject) parser.parse(json);
            final JSONObject dObj = (JSONObject) jsonObj.get("d");
            final JSONArray results = (JSONArray) dObj.get("results");
            if (results.size() == 0) {
                System.out.println("results is Empty, break.");
                break;
            } else {
                System.out.println("Conference: start = " + start + " results# = " + results.size());
                for (Object paper : results) {
                    JSONObject paperObj = (JSONObject) paper;
                    Long id = (Long) paperObj.get("ID");
                    String shortName = normalized((String) paperObj.get("ShortName"));
                    String fullName = normalized((String) paperObj.get("FullName"));
                    String homepage = normalized((String) paperObj.get("Homepage"));
                    csv_str.append(id).append(SEPERATOR).append(shortName).append(SEPERATOR).append(fullName)
                            .append(SEPERATOR).append(homepage).append(NEWLINE);
                }
                IOUtils.writeDataIntoFile(json + "\n", json_dump_file_path);
                IOUtils.writeDataIntoFile(csv_str.toString(), csv_file_path);
                start += 100;
                Thread.sleep(300L);
            }
            //                System.out.println("json= " + jsonObj);
        } catch (ParseException ex) {
            Logger.getLogger(MAS.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InterruptedException ex) {
            Logger.getLogger(MAS.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:mas.MAS.java

public static void extractJournal(int start) {
    String file_prefix = "journals";
    String csv_file_path = "data/" + file_prefix + ".csv";
    String json_dump_file_path = "data/" + file_prefix + "_dump.json";
    String url = "https://api.datamarket.azure.com/MRC/MicrosoftAcademic/v2/Journal?";
    url += "$format=json";
    while (true) {
        try {//from w  ww.j a  v a2  s  .  c  o  m
            StringBuilder csv_str = new StringBuilder();
            final String json = getData2(url, start);
            JSONParser parser = new JSONParser();
            JSONObject jsonObj = (JSONObject) parser.parse(json);
            final JSONObject dObj = (JSONObject) jsonObj.get("d");
            final JSONArray results = (JSONArray) dObj.get("results");
            if (results.size() == 0) {
                System.out.println("results is Empty, break.");
                break;
            } else {
                System.out.println("Journals: start = " + start + " results# = " + results.size());
                for (Object paper : results) {
                    JSONObject paperObj = (JSONObject) paper;
                    Long id = (Long) paperObj.get("ID");
                    String shortName = normalized((String) paperObj.get("ShortName"));
                    String fullName = normalized((String) paperObj.get("FullName"));
                    String homepage = normalized((String) paperObj.get("Homepage"));
                    csv_str.append(id).append(SEPERATOR).append(shortName).append(SEPERATOR).append(fullName)
                            .append(SEPERATOR).append(homepage).append(NEWLINE);
                }
                IOUtils.writeDataIntoFile(json + "\n", json_dump_file_path);
                IOUtils.writeDataIntoFile(csv_str.toString(), csv_file_path);
                start += 100;
                Thread.sleep(300L);
            }
            //                System.out.println("json= " + jsonObj);
        } catch (ParseException ex) {
            Logger.getLogger(MAS.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InterruptedException ex) {
            Logger.getLogger(MAS.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:mas.MAS.java

public static void extractAuthor(int start) {
    String file_prefix = "authors";
    String csv_file_path = "data/" + file_prefix + ".csv";
    String json_dump_file_path = "data/" + file_prefix + "_dump.json";
    String url = "https://api.datamarket.azure.com/MRC/MicrosoftAcademic/v2/Author?$select=ID,Name,NativeName,Affiliation,AffiliationID,Version";
    url += "&$format=json";
    while (true) {
        try {/*from  w w  w . j  a v  a  2  s  . com*/
            StringBuilder csv_str = new StringBuilder();
            final String json = getData2(url, start);
            JSONParser parser = new JSONParser();
            JSONObject jsonObj = (JSONObject) parser.parse(json);
            final JSONObject dObj = (JSONObject) jsonObj.get("d");
            final JSONArray results = (JSONArray) dObj.get("results");
            if (results.size() == 0) {
                System.out.println("results is Empty, break.");
                break;
            } else {
                System.out.println("Author: start = " + start + " results# = " + results.size());
                for (Object paper : results) {
                    JSONObject paperObj = (JSONObject) paper;
                    Long id = (Long) paperObj.get("ID");
                    String name = normalized((String) paperObj.get("Name"));
                    String nativeName = normalized((String) paperObj.get("NativeName"));
                    String affiliation = normalized((String) paperObj.get("Affiliation"));
                    Long affiliationID = (Long) paperObj.get("AffiliationID");
                    Long version = (Long) paperObj.get("Version");
                    csv_str.append(id).append(SEPERATOR).append(name).append(SEPERATOR).append(nativeName)
                            .append(SEPERATOR).append(affiliation).append(SEPERATOR).append(affiliationID)
                            .append(SEPERATOR).append(version).append(NEWLINE);
                }
                IOUtils.writeDataIntoFile(json + "\n", json_dump_file_path);
                IOUtils.writeDataIntoFile(csv_str.toString(), csv_file_path);
                start += 100;
                Thread.sleep(300L);
            }
            //                System.out.println("json= " + jsonObj);
        } catch (ParseException ex) {
            Logger.getLogger(MAS.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InterruptedException ex) {
            Logger.getLogger(MAS.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}