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.aerospike.load.Parser.java

/**
 * Process column definitions in JSON formated file and create two lists for metadata and bindata and one list for metadataLoader
 * @param file Config file name//  ww  w  .j  a va2  s  .  com
 * @param metadataLoader Map of metadata for loader to use, given in config file
 * @param metadataColumnDefs List of column definitions for metadata of bins like key,set 
 * @param binColumnDefs List of column definitions for bins
 * @param params User given parameters
 * @throws ParseException 
 * @throws IOException 
 */
public static boolean processJSONColumnDefinitions(File file, HashMap<String, String> metadataConfigs,
        List<ColumnDefinition> metadataColumnDefs, List<ColumnDefinition> binColumnDefs, Parameters params) {
    boolean processConfig = false;
    if (params.verbose) {
        log.setLevel(Level.DEBUG);
    }
    try {
        // Create parser object
        JSONParser jsonParser = new JSONParser();

        // Read the json config file
        Object obj;
        obj = jsonParser.parse(new FileReader(file));

        JSONObject jobj;
        // Check config file contains metadata for datafile
        if (obj == null) {
            log.error("Empty config File");
            return processConfig;
        } else {
            jobj = (JSONObject) obj;
            log.debug("Config file contents:" + jobj.toJSONString());
        }

        // Get meta data of loader
        // Search for input_type
        if ((obj = getJsonObject(jobj, Constants.VERSION)) != null) {
            metadataConfigs.put(Constants.VERSION, obj.toString());
        } else {
            log.error("\"" + Constants.VERSION + "\"  Key is missing in config file");
            return processConfig;
        }

        if ((obj = getJsonObject(jobj, Constants.INPUT_TYPE)) != null) {

            // Found input_type, check for csv 
            if (obj instanceof String && obj.toString().equals(Constants.CSV_FILE)) {
                // Found csv format
                metadataConfigs.put(Constants.INPUT_TYPE, obj.toString());

                // Search for csv_style
                if ((obj = getJsonObject(jobj, Constants.CSV_STYLE)) != null) {
                    // Found csv_style
                    JSONObject cobj = (JSONObject) obj;

                    // Number_Of_Columns in data file
                    if ((obj = getJsonObject(cobj, Constants.COLUMNS)) != null) {
                        metadataConfigs.put(Constants.COLUMNS, obj.toString());
                    } else {
                        log.error("\"" + Constants.COLUMNS + "\"  Key is missing in config file");
                        return processConfig;
                    }

                    // Delimiter for parsing data file
                    if ((obj = getJsonObject(cobj, Constants.DELIMITER)) != null)
                        metadataConfigs.put(Constants.DELIMITER, obj.toString());

                    // Skip first row of data file if it contains column names
                    if ((obj = getJsonObject(cobj, Constants.IGNORE_FIRST_LINE)) != null)
                        metadataConfigs.put(Constants.IGNORE_FIRST_LINE, obj.toString());

                } else {
                    log.error("\"" + Constants.CSV_STYLE + "\"  Key is missing in config file");
                    return processConfig;
                }
            } else {
                log.error("\"" + obj.toString() + "\"  file format is not supported in config file");
                return processConfig;
            }

        } else {
            log.error("\"" + Constants.INPUT_TYPE + "\"  Key is missing in config file");
            return processConfig;
        }

        // Get metadata of records
        // Get key definition of records
        if ((obj = getJsonObject(jobj, Constants.KEY)) != null) {
            metadataColumnDefs.add(getColumnDefs((JSONObject) obj, Constants.KEY));
        } else {
            log.error("\"" + Constants.KEY + "\"  Key is missing in config file");
            return processConfig;
        }

        // Get set definition of records. Optional because we can get "set" name from user.
        if ((obj = getJsonObject(jobj, Constants.SET)) != null) {
            if (obj instanceof String) {
                metadataColumnDefs.add(new ColumnDefinition(Constants.SET, obj.toString(), true, true, "string",
                        "string", null, -1, -1, null, null));
            } else {
                metadataColumnDefs.add(getColumnDefs((JSONObject) obj, Constants.SET));
            }
        }

        // Get bin column definitions 
        JSONArray binList;
        if ((obj = getJsonObject(jobj, Constants.BINLIST)) != null) {
            // iterator for bins
            binList = (JSONArray) obj;
            Iterator<?> i = binList.iterator();
            // take each bin from the JSON array separately
            while (i.hasNext()) {
                JSONObject binObj = (JSONObject) i.next();
                binColumnDefs.add(getColumnDefs(binObj, Constants.BINLIST));
            }

        } else {
            return processConfig;
        }
        log.info(String.format("Number of columns: %d(metadata) + %d(bins)", (metadataColumnDefs.size()),
                binColumnDefs.size()));
        processConfig = true;
    } catch (IOException ie) {
        log.error("File:" + Utils.getFileName(file.getName()) + " Config i/o Error: " + ie.toString());
        if (log.isDebugEnabled()) {
            ie.printStackTrace();
        }
    } catch (ParseException pe) {
        log.error("File:" + Utils.getFileName(file.getName()) + " Config parsing Error: " + pe.toString());
        if (log.isDebugEnabled()) {
            pe.printStackTrace();
        }

    } catch (Exception e) {
        log.error("File:" + Utils.getFileName(file.getName()) + " Config unknown Error: " + e.toString());
        if (log.isDebugEnabled()) {
            e.printStackTrace();
        }
    }

    return processConfig;
}

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

public static String getLogIdFromMessage(String msg) {
    JSONObject jsonMsg;/*from w w w  .  j a  v  a  2s .co m*/
    JSONParser parser = new JSONParser();

    try {
        jsonMsg = (JSONObject) parser.parse(msg);
        JSONObject msgObject = (JSONObject) jsonMsg.get(JsonStrings.MESSAGE);
        return (String) msgObject.get(JsonStrings.LOG_ID);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.nhn.android.archetype.base.object.BaseObj.java

@SuppressWarnings("unchecked")
public static <T extends BaseObj> T parse(String json, Class<? extends BaseObj> clazz) {
    T item = null;/*from  w  ww. j av  a2 s .  c  o m*/

    if (json == null) {
        logger.w("parse(), json is null");
        return null;
    }

    json = json.trim();
    if (json.startsWith("[") && json.endsWith("]")) {
        json = String.format("{\"data\" : %s}", json);
    }

    try {
        item = (T) clazz.newInstance();
    } catch (Exception e) {
        logger.e(e);
        return null;
    }

    Map<String, Object> dataMap = null;

    try {
        JSONParser parser = new JSONParser();
        dataMap = (Map) parser.parse(json);
    } catch (Exception e) {
        logger.e(e);

        dataMap = new LinkedHashMap<String, Object>();
        dataMap.put(CODE, -1);
        dataMap.put(MESSAGE, "Unexpected Error");
    }

    item.setDataMap(dataMap);

    return item;
}

From source file:com.dropbox.client2.RESTUtility.java

/**
 * Reads in content from an {@link HttpResponse} and parses it as JSON.
 *
 * @param response the {@link HttpResponse}.
 *
 * @return a parsed JSON object, typically a Map or a JSONArray.
 *
 * @throws DropboxServerException if the server responds with an error
 *         code. See the constants in {@link DropboxServerException} for
 *         the meaning of each error code.
 * @throws DropboxIOException if any network-related error occurs while
 *         reading in content from the {@link HttpResponse}.
 * @throws DropboxUnlinkedException if the user has revoked access.
 * @throws DropboxParseException if a malformed or unknown response was
 *         received from the server.//w  ww  .jav  a 2  s .  co  m
 * @throws DropboxException for any other unknown errors. This is also a
 *         superclass of all other Dropbox exceptions, so you may want to
 *         only catch this exception which signals that some kind of error
 *         occurred.
 */
public static Object parseAsJSON(HttpResponse response) throws DropboxException {
    Object result = null;

    BufferedReader bin = null;
    try {
        HttpEntity ent = response.getEntity();
        if (ent != null) {
            InputStreamReader in = new InputStreamReader(ent.getContent());
            // Wrap this with a Buffer, so we can re-parse it if it's
            // not JSON
            // Has to be at least 16384, because this is defined as the buffer size in
            //     org.json.simple.parser.Yylex.java
            // and otherwise the reset() call won't work
            bin = new BufferedReader(in, 16384);
            bin.mark(16384);

            JSONParser parser = new JSONParser();
            result = parser.parse(bin);
        }
    } catch (IOException e) {
        throw new DropboxIOException(e);
    } catch (ParseException e) {
        if (DropboxServerException.isValidWithNullBody(response)) {
            // We have something from Dropbox, but it's an error with no reason
            throw new DropboxServerException(response);
        } else {
            // This is from Dropbox, and we shouldn't be getting it
            throw new DropboxParseException(bin);
        }
    } catch (OutOfMemoryError e) {
        throw new DropboxException(e);
    } finally {
        if (bin != null) {
            try {
                bin.close();
            } catch (IOException e) {
            }
        }
    }

    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode != DropboxServerException._200_OK) {
        if (statusCode == DropboxServerException._401_UNAUTHORIZED) {
            throw new DropboxUnlinkedException();
        } else {
            throw new DropboxServerException(response, result);
        }
    }

    return result;
}

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

public static String addLogField(String message, String logId) {
    JSONParser parser = new JSONParser();
    try {/*from   www .  ja  va  2 s. c o  m*/
        JSONObject msg = (JSONObject) parser.parse(message);
        JSONObject m = (JSONObject) msg.get(JsonStrings.MESSAGE);
        MessageType msgType = MessageType.valueOf((String) m.get(JsonStrings.MSG_TYPE));
        if (msgType.equals(MessageType.CHECK_OUT)) {
            m.put(JsonStrings.LOG_ID, logId);
            JSONObject newJsonMsg = new JSONObject();
            newJsonMsg.put(JsonStrings.MESSAGE, m);
            return newJsonMsg.toJSONString();
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return message;
}

From source file:com.nubits.nubot.trading.TradeUtils.java

public static String getCCDKEvalidNonce(String htmlString) {

    JSONParser parser = new JSONParser();
    try {//from w  w  w .  ja  v  a 2  s  .co  m
        //{"errors":{"nonce":"incorrect range `nonce`=`1234567891`, must be from `1411036100` till `1411036141`"}
        JSONObject httpAnswerJson = (JSONObject) (parser.parse(htmlString));
        JSONObject errors = (JSONObject) httpAnswerJson.get("errors");
        String nonceError = (String) errors.get("nonce");

        //String startStr = " must be from";
        //int indexStart = nonceError.lastIndexOf(startStr) + startStr.length() + 2;
        //String from = nonceError.substring(indexStart, indexStart + 10);

        String startStr2 = " till";
        int indexStart2 = nonceError.lastIndexOf(startStr2) + startStr2.length() + 2;
        String to = nonceError.substring(indexStart2, indexStart2 + 10);

        //if (to.equals(from)) {
        //    LOG.info("Detected ! " + to + " = " + from);
        //    return "retry";
        //}

        return to;
    } catch (ParseException ex) {
        LOG.severe(htmlString + " " + ex.toString());
        return "1234567891";
    }
}

From source file:com.telefonica.iot.cygnus.utils.CommonUtils.java

/**
 * Gets the timestamp within a TimeInstant metadata, if exists.
 * @param metadata/*from ww  w  .  j a  va2  s .  c o m*/
 * @return The timestamp within a TimeInstant metadata
 */
public static Long getTimeInstant(String metadata) {
    Long res = null;
    JSONParser parser = new JSONParser();
    JSONArray mds;

    try {
        mds = (JSONArray) parser.parse(metadata);
    } catch (ParseException e) {
        LOGGER.error("Error while parsing the metadaga. Details: " + e.getMessage());
        return null;
    } // try catch

    for (Object mdObject : mds) {
        JSONObject md = (JSONObject) mdObject;
        String mdName = (String) md.get("name");

        if (mdName.equals("TimeInstant")) {
            String mdValue = (String) md.get("value");

            if (isANumber(mdValue)) {
                res = new Long(mdValue);
            } else {
                DateTime dateTime;

                try {
                    // ISO 8601 without miliseconds
                    dateTime = FORMATTER1.parseDateTime(mdValue);
                } catch (Exception e1) {
                    LOGGER.debug(e1.getMessage());

                    try {
                        // ISO 8601 with miliseconds
                        dateTime = FORMATTER2.parseDateTime(mdValue);
                    } catch (Exception e2) {
                        LOGGER.debug(e2.getMessage());

                        try {
                            // ISO 8601 with microsencods
                            String mdValueTruncated = mdValue.substring(0, mdValue.length() - 4) + "Z";
                            dateTime = FORMATTER2.parseDateTime(mdValueTruncated);
                        } catch (Exception e3) {
                            LOGGER.debug(e3.getMessage());

                            try {
                                // SQL timestamp without miliseconds
                                dateTime = FORMATTER3.parseDateTime(mdValue);
                            } catch (Exception e4) {
                                LOGGER.debug(e4.getMessage());

                                try {
                                    // SQL timestamp with miliseconds
                                    dateTime = FORMATTER4.parseDateTime(mdValue);
                                } catch (Exception e5) {
                                    LOGGER.debug(e5.getMessage());

                                    try {
                                        // SQL timestamp with microseconds
                                        String mdValueTruncated = mdValue.substring(0, mdValue.length() - 3);
                                        dateTime = FORMATTER4.parseDateTime(mdValueTruncated);
                                    } catch (Exception e6) {
                                        LOGGER.debug(e6.getMessage());

                                        try {
                                            // ISO 8601 with offset (without milliseconds)
                                            dateTime = FORMATTER5.parseDateTime(mdValue);
                                        } catch (Exception e7) {
                                            LOGGER.debug(e7.getMessage());

                                            try {
                                                // ISO 8601 with offset (with milliseconds)
                                                Matcher matcher = FORMATTER6_PATTERN.matcher(mdValue);
                                                if (matcher.matches()) {
                                                    String mdValueTruncated = matcher.group(1) + "."
                                                            + matcher.group(2).substring(0, 3)
                                                            + matcher.group(3);
                                                    dateTime = FORMATTER6.parseDateTime(mdValueTruncated);
                                                } else {
                                                    LOGGER.debug("ISO8601 format does not match");
                                                    return null;
                                                } // if
                                            } catch (Exception e8) {
                                                LOGGER.debug(e8.getMessage());
                                                return null;
                                            } // try catch
                                        } // try catch
                                    } // try catch
                                } // try catch
                            } // try catch
                        } // try catch
                    } // try catch
                } // try catch

                GregorianCalendar cal = dateTime.toGregorianCalendar();
                res = cal.getTimeInMillis();
            } // if else

            break;
        } // if
    } // for

    return res;
}

From source file:agileinterop.AgileInterop.java

private static JSONObject getPSRData(String body) throws ParseException, InterruptedException, APIException {
    // Parse body as JSON
    JSONParser parser = new JSONParser();
    JSONArray jsonBody = (JSONArray) parser.parse(body);

    Map<String, Object> data = new HashMap<>();

    class GetObjectData implements Runnable {
        private String psrNumber;
        private Map<String, Object> data;
        private IServiceRequest psr;

        public GetObjectData(String psrNumber, Map<String, Object> data)
                throws APIException, InterruptedException {
            this.psrNumber = psrNumber;
            this.data = data;

            psr = (IServiceRequest) Agile.session.getObject(IServiceRequest.OBJECT_TYPE, psrNumber);
        }/*  w  w w  .  j av a  2  s.c o  m*/

        @Override
        public void run() {
            this.data.put(psrNumber, new HashMap<String, Object>());

            try {
                if (psr != null) {
                    getCellValues();
                    getAttachments();
                    getHistory();
                }
            } catch (APIException ex) {
                Logger.getLogger(AgileInterop.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        private void getCellValues() throws APIException {
            Map<String, Object> cellValues = new HashMap<>();

            long startTime = System.currentTimeMillis();

            // Get cell values
            ICell[] cells = psr.getCells();
            for (ICell cell : cells) {
                if (cell.getDataType() == DataTypeConstants.TYPE_DATE) {
                    if (cell.getValue() != null) {
                        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a zz");
                        sdf.setTimeZone(TimeZone.getTimeZone("Europe/London"));
                        cellValues.put(cell.getName(), sdf.format((Date) cell.getValue()));
                    } else {
                        cellValues.put(cell.getName(), cell.toString());
                    }
                } else {
                    cellValues.put(cell.getName(), cell.toString());
                }
            }

            long endTime = System.currentTimeMillis();

            String logMessage = String.format("%s: getCellValues executed in %d milliseconds", psrNumber,
                    endTime - startTime);
            System.out.println(logMessage);

            ((HashMap<String, Object>) this.data.get(psrNumber)).put("cellValues", cellValues);
        }

        private void getAttachments() throws APIException {
            List<Map<String, String>> attachments = new ArrayList<>();

            long startTime = System.currentTimeMillis();

            // Get attachments information
            ITable table = psr.getTable("Attachments");
            ITwoWayIterator tableIterator = table.getTableIterator();
            while (tableIterator.hasNext()) {
                IRow row = (IRow) tableIterator.next();
                Map<String, String> attachment = new HashMap<>();

                ICell[] cells = row.getCells();
                for (ICell cell : cells) {
                    if (cell.getDataType() == DataTypeConstants.TYPE_DATE) {
                        if (cell.getValue() != null) {
                            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a zz");
                            sdf.setTimeZone(TimeZone.getTimeZone("Europe/London"));
                            attachment.put(cell.getName(), sdf.format((Date) cell.getValue()));
                        } else {
                            attachment.put(cell.getName(), cell.toString());
                        }
                    } else {
                        attachment.put(cell.getName(), cell.toString());
                    }
                }

                attachments.add(attachment);
            }

            long endTime = System.currentTimeMillis();

            String logMessage = String.format("%s: getAttachments executed in %d milliseconds", psrNumber,
                    endTime - startTime);
            System.out.println(logMessage);

            ((HashMap<String, Object>) this.data.get(psrNumber)).put("attachments", attachments);
        }

        private void getHistory() throws APIException {
            List<Map<String, String>> histories = new ArrayList<>();

            long startTime = System.currentTimeMillis();

            // Get history information
            ITable table = psr.getTable("History");
            ITwoWayIterator tableIterator = table.getTableIterator();
            while (tableIterator.hasNext()) {
                IRow row = (IRow) tableIterator.next();
                Map<String, String> history = new HashMap<>();

                ICell[] cells = row.getCells();
                for (ICell cell : cells) {
                    if (cell.getDataType() == DataTypeConstants.TYPE_DATE) {
                        if (cell.getValue() != null) {
                            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a zz");
                            sdf.setTimeZone(TimeZone.getTimeZone("Europe/London"));
                            history.put(cell.getName(), sdf.format((Date) cell.getValue()));
                        } else {
                            history.put(cell.getName(), cell.toString());
                        }
                    } else {
                        history.put(cell.getName(), cell.toString());
                    }
                }

                histories.add(history);
            }

            long endTime = System.currentTimeMillis();

            String logMessage = String.format("%s: getHistory executed in %d milliseconds", psrNumber,
                    endTime - startTime);
            System.out.println(logMessage);

            ((HashMap<String, Object>) this.data.get(psrNumber)).put("history", histories);
        }
    }

    synchronized (data) {
        // Do something funky with the first one
        Thread t = new Thread(new GetObjectData(jsonBody.get(0).toString(), data));
        t.start();
        t.join();

        ExecutorService executor = Executors.newFixedThreadPool(10);
        for (Object object : jsonBody.subList(1, jsonBody.size() - 1)) {
            executor.execute(new Thread(new GetObjectData(object.toString(), data)));
        }

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

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

From source file:freebase.api.FreebaseHelper.java

public static JSONArray getJSON(String fromDate, String toDate) {
    try {/*from ww w  . j a  v  a  2s . c  om*/
        properties.load(new FileInputStream("freebase.properties"));
        HttpTransport httpTransport = new NetHttpTransport();
        HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
        JSONParser parser = new JSONParser();
        String query = readQueryFromFile("queries/q1.json");
        query = manipulateQuery(query, fromDate, toDate);
        GenericUrl url = new GenericUrl("https://www.googleapis.com/freebase/v1/mqlread");
        url.put("query", query);
        url.put("key", properties.get("API_KEY"));
        System.out.println("URL:" + url);
        HttpRequest request = requestFactory.buildGetRequest(url);
        HttpResponse httpResponse = request.execute();
        JSONObject response = (JSONObject) parser.parse(httpResponse.parseAsString());
        JSONArray results = (JSONArray) response.get("result");
        Utils.writeDataIntoFile(results.toString() + "\n", FreebaseAPI.JSON_DUMP_FILE);

        return results;
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;
}

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;//  www .  j  a  v  a2s.  c  om
    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();
    }
}