Example usage for org.json.simple.parser JSONParser parse

List of usage examples for org.json.simple.parser JSONParser parse

Introduction

In this page you can find the example usage for org.json.simple.parser JSONParser parse.

Prototype

public Object parse(Reader in) throws IOException, ParseException 

Source Link

Usage

From source file:com.apigee.edge.config.mavenplugin.MaskConfigMojo.java

public static List getOrgMaskConfig(ServerProfile profile) throws IOException {

    HttpResponse response = RestUtil.getOrgConfig(profile, "maskconfigs");
    if (response == null)
        return new ArrayList();
    JSONArray masks = null;//from w ww  .  j  a v  a  2  s. c  o  m
    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 = "{ \"masks\": " + payload + "}";

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

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

    return masks;
}

From source file:com.apigee.edge.config.mavenplugin.MaskConfigMojo.java

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

    HttpResponse response = RestUtil.getAPIConfig(profile, api, "maskconfigs");
    if (response == null)
        return new ArrayList();
    JSONArray masks = null;//from  w w  w  .j  ava  2  s  .c  o  m
    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 = "{ \"masks\": " + payload + "}";

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

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

    return masks;
}

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

public static HashMap<String, List<ActionEffect>> getActionEffects() {
    HashMap<String, List<ActionEffect>> actionEffects = new HashMap<String, List<ActionEffect>>();

    JSONParser parser = new JSONParser();

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

        JSONObject jsonObject = (JSONObject) obj;

        for (Object actionName : jsonObject.keySet()) {
            ActionEffect actionEffect = new ActionEffect();
            String myaction = (String) actionName;
            actionEffect.setActionType((String) actionName);
            actionEffect.setActionName(myaction);
            JSONObject object = (JSONObject) jsonObject.get(myaction);
            for (Object actions : object.keySet()) {

                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);

                            //System.out.println("metricName="+metricName+" metric effect="+metriceffects.get(metricName)+"Affected unit="+affectedUnit);

                        } catch (Exception e) {

                            actionEffect.setActionEffectForMetric(metricName,
                                    ((Long) metriceffects.get(metricName) + 0.0), affectedUnit);

                            //   System.out.println("metricName="+metricName+" metric effect="+metriceffects.get(metricName)+"Affected unit="+affectedUnit);

                        }
                    }
                }
            }
            List<ActionEffect> l = new ArrayList<ActionEffect>();
            l.add(actionEffect);
            actionEffects.put(actionEffect.getTargetedEntityID(), l);
        }

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

From source file:crossbear.convergence.ConvergenceConnector.java

/**
 * Transfer the Notary's answer from a JSON-representation into a HashSet of ConvergenceCertObservation
 * //  w  w  w. j a  va2s  . com
 * @param notaryAnswer The Response-String that the Notary sent as an answer. It should contain a JSON-encoded list of ConvergenceCertificateObservations 
 * @param hostPort The Hostname and port of the server on which the information about the certificate observations is desired.
 * @return The Notary's answer as a Set of ConvergenceCertObservations
 * @throws ParseException
 */
private static HashSet<ConvergenceCertObservation> parseNotaryAnswer(String notaryAnswer, String hostPort)
        throws ParseException {

    // Create a empty Set of ConvergenceCertObservations
    HashSet<ConvergenceCertObservation> re = new HashSet<ConvergenceCertObservation>();

    // Try to decode the Notary's answer as a JSONObject
    JSONParser parser = new JSONParser();
    JSONObject obj = (JSONObject) parser.parse(notaryAnswer);

    // If that worked extract the field called fingerprintList (which is basically a list of ConvergenceCertObservations in JSON encoding)
    JSONArray array = (JSONArray) obj.get("fingerprintList");

    // Go through the list ...
    for (int i = 0; i < array.size(); i++) {

        // ... read each entry ...
        JSONObject entry = (JSONObject) array.get(i);

        // .. extract its content ...
        byte[] fingerprint = Message.hexStringToByteArray(((String) entry.get("fingerprint")).replace(":", ""));
        JSONObject ts = (JSONObject) entry.get("timestamp");
        Timestamp firstObservation = new Timestamp(1000 * Long.valueOf((String) ts.get("start")));
        Timestamp lastObservation = new Timestamp(1000 * Long.valueOf((String) ts.get("finish")));
        Timestamp lastUpdate = new Timestamp(System.currentTimeMillis());

        // ... and create a new ConvergenceCertObservation-object based on that content.
        re.add(new ConvergenceCertObservation(hostPort, Message.byteArrayToHexString(fingerprint),
                firstObservation, lastObservation, lastUpdate));
    }

    // Finally return the Set containing all of the extracted ConvergenceCertObservations.
    return re;
}

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

public static HashMap<String, List<ActionEffect>> getActionEffects() {
    if (actionEffects.isEmpty()) {
        actionEffects = new HashMap<String, List<ActionEffect>>();

        JSONParser parser = new JSONParser();

        try {//w w  w  . jav 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()) {
                ActionEffect actionEffect = new ActionEffect();
                String myaction = (String) actionName;
                actionEffect.setActionType((String) actionName);
                actionEffect.setActionName(myaction);
                JSONObject object = (JSONObject) jsonObject.get(myaction);
                List<ActionEffect> l = new ArrayList<ActionEffect>();
                for (Object actions : object.keySet()) {

                    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);

                                //System.out.println("metricName="+metricName+" metric effect="+metriceffects.get(metricName)+"Affected unit="+affectedUnit);

                            } catch (Exception e) {

                                actionEffect.setActionEffectForMetric(metricName,
                                        ((Long) metriceffects.get(metricName) + 0.0), affectedUnit);

                                //   System.out.println("metricName="+metricName+" metric effect="+metriceffects.get(metricName)+"Affected unit="+affectedUnit);

                            }
                        }
                    }
                }

                l.add(actionEffect);
                actionEffects.put(actionEffect.getTargetedEntityID(), l);
            }

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

From source file:agileinterop.AgileInterop.java

private static JSONObject getPSRList(String body)
        throws ParseException, InterruptedException, java.text.ParseException, Exception {
    // Parse body as JSON
    JSONParser parser = new JSONParser();
    JSONObject jsonBody = (JSONObject) parser.parse(body);

    Date startDateOriginated = new SimpleDateFormat("MM/dd/yyyy")
            .parse(jsonBody.get("startDateOriginated").toString());
    Date endDateOriginated = new SimpleDateFormat("MM/dd/yyyy")
            .parse(jsonBody.get("endDateOriginated").toString());

    List<String> data = new ArrayList<>();

    class getPSRListForDate implements Runnable {
        private Date dateOriginated;
        private List<String> data;

        public getPSRListForDate(Date dateOriginated, List<String> data) {
            this.dateOriginated = dateOriginated;
            this.data = data;
        }/*from   ww w.  j av a  2 s .c o m*/

        public getPSRListForDate(List<String> data) {
            this.data = data;
        }

        @Override
        public void run() {
            try {
                String dateOriginatedString = new SimpleDateFormat("MM/dd/yyyy").format(dateOriginated);

                Long startTime = System.currentTimeMillis();

                IQuery query = (IQuery) Agile.session.createObject(IQuery.OBJECT_TYPE,
                        "Product Service Requests");

                String criteria = "[Cover Page.Date Originated] == '" + dateOriginatedString
                        + " 12:00:00 AM GMT' AND "
                        + "[Cover Page.Type] IN ('Customer Complaint', 'Customer Inquiry', 'Partner Complaint', "
                        + "'Reportable Malfunction / Adverse Event', 'Ancillary Devices & Applications', 'Distributors / Partners', "
                        + "'MDR Decision Tree', 'Investigation Report - No RGA', 'Investigation Report - RGA')";
                query.setCriteria(criteria);

                query.setResultAttributes(new Integer[] { 4856 }); // 4856 = Object ID of [Cover Page.PSR Number]

                ITable queryResults = query.execute();
                queryResults.setPageSize(5000);

                ITwoWayIterator tableIterator = queryResults.getTableIterator();
                while (tableIterator.hasNext()) {
                    IRow row = (IRow) tableIterator.next();
                    data.add(row.getCell(4856).toString()); // 4856 = Object ID of [Cover Page.PSR Number]
                }

                Long endTime = System.currentTimeMillis();

                String logMessage = String.format("getPSRList: Query for %s executed in %d milliseconds",
                        new SimpleDateFormat("yyyy-MM-dd").format(dateOriginated), endTime - startTime);
                System.out.println(logMessage);
            } catch (APIException ex) {
                Logger.getLogger(AgileInterop.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    if (startDateOriginated.after(endDateOriginated)) {
        throw new Exception("startDateOriginated is after endDateOriginated. This makes no sense, silly.");
    }

    synchronized (data) {
        Date currentDateOriginated = startDateOriginated;

        ExecutorService executor = Executors.newFixedThreadPool(6);
        do {
            executor.execute(new Thread(new getPSRListForDate(currentDateOriginated, data)));

            Calendar c = Calendar.getInstance();
            c.setTime(currentDateOriginated);
            c.add(Calendar.DATE, 1);

            currentDateOriginated = c.getTime();
        } while (currentDateOriginated.before(endDateOriginated)
                | currentDateOriginated.equals(endDateOriginated));

        executor.shutdown();
        while (!executor.isTerminated()) {
        }
    }

    JSONObject obj = new JSONObject();
    obj.put("data", data);
    return obj;
}

From source file:com.apigee.edge.config.utils.ConsolidatedConfigReader.java

/**
 * Example Hierarchy/*w w  w .j  av a2 s  .  com*/
 * orgConfig.developerApps.<developerId>.apps
 * 
 * Returns Map of
 * <developerId> => [ {app1}, {app2}, {app3} ]
 */
public static Map<String, List<String>> getOrgConfigWithId(File configFile, String scope, String resource)
        throws ParseException, IOException {

    Logger logger = LoggerFactory.getLogger(ConfigReader.class);

    JSONParser parser = new JSONParser();
    Map<String, List<String>> out = null;
    List<String> outStrs = null;
    try {
        BufferedReader bufferedReader = new BufferedReader(new java.io.FileReader(configFile));

        JSONObject edgeConf = (JSONObject) parser.parse(bufferedReader);
        if (edgeConf == null)
            return null;

        // orgConfig
        JSONObject scopeConf = (JSONObject) edgeConf.get(scope);
        if (scopeConf == null)
            return null;

        // orgConfig.developerApps
        Map sConfig = (Map) scopeConf.get(resource);
        if (sConfig == null)
            return null;

        // orgConfig.developerApps.<developerId>
        Iterator it = sConfig.entrySet().iterator();
        out = new HashMap<String, List<String>>();
        while (it.hasNext()) {
            Map.Entry pair = (Map.Entry) it.next();
            JSONArray confs = (JSONArray) pair.getValue();
            outStrs = new ArrayList<String>();
            for (Object conf : confs) {
                outStrs.add(((JSONObject) conf).toJSONString());
            }
            out.put((String) pair.getKey(), outStrs);
        }

    } catch (IOException ie) {
        logger.info(ie.getMessage());
        throw ie;
    } catch (ParseException pe) {
        logger.info(pe.getMessage());
        throw pe;
    }

    return out;
}

From source file:com.justgiving.raven.kissmetrics.utils.KissmetricsLocalSchemaExtractor.java

/****
 * This function counts the total occurrences of keys, in the json records files
 *  /*  w  ww  . ja  va 2  s.  co m*/
 * @param input_filename path to a json file
 * @return a HashMap with the keys / total counts pairs
 */
private static KeyValueCounter countKeysInJsonRecordsFile(String input_filename) {
    InputStream fis;
    BufferedReader bufferedReader;
    String line;
    JSONParser jsonParser = new JSONParser();
    KeyValueCounter keyValueCounter = new KeyValueCounter();
    String jsonValue = "";
    try {
        fis = new FileInputStream(input_filename);
        bufferedReader = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));
        while ((line = bufferedReader.readLine()) != null) {
            JSONObject jsonObject = (JSONObject) jsonParser.parse(line);
            Set<String> keyset = jsonObject.keySet();
            for (String jsonkey : keyset) {
                if (jsonObject.get(jsonkey) != null) {
                    jsonValue = (String) jsonObject.get(jsonkey).toString();
                    if (jsonValue == null || jsonValue == "") {
                        jsonValue = "";
                    }
                    int lenValue = jsonValue.length();
                    keyValueCounter.incrementKeyCounter(jsonkey);
                    keyValueCounter.putValueLength(jsonkey, lenValue);
                } else {
                    if (jsonkey.compareTo("user_agent") != 0) {
                        logger.error("Errot typing to get jsonkey " + jsonkey);
                    }

                }
            }
        }
        bufferedReader.close();
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    //System.out.println(keyCounter.toString());
    //System.out.println(sortHashByKey(keyCounter));      
    return keyValueCounter;
}

From source file:com.dynamobi.network.DynamoNetworkUdr.java

/**
 * Fetches the master metadata.json file on a given repository and returns the
 * data as a JSONObject.//  w  w w .jav  a2s.c o  m
 */
private static JSONObject downloadMetadata(String repo) throws SQLException {
    if (repo == null)
        return null;

    try {
        // Grab master metadata.json
        URL u = new URL(repo + "/metadata.json");
        URLConnection uc = u.openConnection();
        uc.setConnectTimeout(1000); // generous max-of-1-second to connect
        uc.setReadTimeout(1000);
        uc.connect();
        InputStreamReader in = new InputStreamReader(uc.getInputStream());
        BufferedReader buff = new BufferedReader(in);
        StringBuffer sb = new StringBuffer();
        String line = null;
        do {
            line = buff.readLine();
            if (line != null)
                sb.append(line);
        } while (line != null);
        String data = sb.toString();

        // Parse it
        JSONParser parser = new JSONParser();
        JSONObject ob = (JSONObject) parser.parse(data);
        return ob;

    } catch (SocketTimeoutException e) {
        throw new SQLException(URL_TIMEOUT);
    } catch (MalformedURLException e) {
        throw new SQLException("Bad URL.");
    } catch (IOException e) {
        throw new SQLException(URL_TIMEOUT);
    } catch (ParseException e) {
        throw new SQLException("Could not parse data from URL.");
    }

}

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

/**
 * Convenience method that JSON Parses the <code>InputStream</code> of a <code>HttpURLConnection</code>.
 *
 * @param conn the <code>HttpURLConnection</code>.
 * @return the parsed JSON object./*from  w  w w  . j a  v a 2s  . c  om*/
 * @throws IOException thrown if the <code>InputStream</code> could not be JSON parsed.
 */
private static Object jsonParse(HttpURLConnection conn) throws IOException {
    try {
        JSONParser parser = new JSONParser();
        return parser.parse(new InputStreamReader(conn.getInputStream()));
    } catch (ParseException ex) {
        throw new IOException("JSON parser error, " + ex.getMessage(), ex);
    }
}