Example usage for org.json.simple.parser ParseException ParseException

List of usage examples for org.json.simple.parser ParseException ParseException

Introduction

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

Prototype

public ParseException(int errorType) 

Source Link

Usage

From source file:com.conwet.xjsp.json.JSONUtil.java

/**
 * Extracts from the buffer a whole stanza or an stream finalizer "]}".
 * The recognized text is removed from the buffer.
 * /*from  ww w.j a va 2 s  .  co  m*/
 * Stanza recognition is implemented as a FSM. States:
 * <ul>
 *      <li>0. starting</li>
 *      <li>1. accepting text</li>
 *      <li>2. within an string</li>
 *      <li>3. finalizer</li>
 * </ul>
 * 
 * <img src="../../../../../resources/fsm.png"/>
 * 
 * @return Recognized text or <code>null</code>
 */
public static String extractStanza(StringBuilder buffer) throws ParseException {
    discardSpaces(buffer);

    int state = 0;
    int pos = 0;
    int level = 1;

    while (pos < buffer.length()) {
        char c = buffer.charAt(pos);
        switch (state) {
        case 0:
            switch (c) {
            case '{':
                state = 1;
                break;
            case ']':
                state = 3;
                break;
            default:
                throw new ParseException(ParseException.ERROR_UNEXPECTED_CHAR);
            }
            break;

        case 1:
            switch (c) {
            case '{':
                level++;
                break;
            case '}':
                level--;
                if (level == 0) {
                    String stanza = buffer.substring(0, pos + 1);
                    buffer.replace(0, pos + 1, "");
                    return stanza;
                }
                break;

            case '"':
                state = 2;
                break;

            default:
                // nothing
            }
            break;

        case 2:
            switch (c) {
            case '\\':
                pos++;
                break;

            case '"':
                state = 1;
                break;

            default:
                // nothing
            }
            break;

        case 3:
            if (isSpace(c)) {
                pos++;
            } else if (c == '}') {
                buffer.replace(0, pos + 1, "");
                return "]}";
            }

        default:
            throw new IllegalStateException();
        }
        pos++;
    }

    return null;
}

From source file:org.exoplatform.social.client.core.util.SocialJSONDecodingSupport.java

/**
 * HttpResponse text into java Map object from the input source.
 *  /*from  w w w .j  a v  a 2 s  .  co m*/
 * @param response HttpResponse to get the content.
 * @throws ParseException Throw this exception if any
 */
public static Map parser(HttpResponse response) throws ParseException {
    String jsonContent = null;
    try {
        jsonContent = SocialHttpClientSupport.getContent(response);
    } catch (SocialHttpClientException e) {
        throw new ParseException(0);
    }
    return parser(jsonContent);
}

From source file:com.aerospike.load.AsWriterTask.java

private boolean processLine() {
    log.debug("processing  File:line " + Utils.getFileName(fileName) + this.lineNumber);
    bins = new ArrayList<Bin>();
    boolean lineProcessed = false;
    long errorTotal = 0;
    try {/*from  w w  w .  j  a v a2s .c  o  m*/
        if (columns.size() != counters.write.colTotal) {
            if (columns.size() < counters.write.colTotal) {
                log.error("File:" + Utils.getFileName(this.fileName) + " Line:" + lineNumber
                        + " Number of column mismatch:Columns in data file is less than number of column in config file.");
            } else {
                throw new ParseException(lineNumber);
            }
        }

        //retrieve set name first
        for (ColumnDefinition metadataColumn : this.metadataMapping) {
            if (metadataColumn.staticValue
                    && metadataColumn.getBinNameHeader().equalsIgnoreCase(Constants.SET)) {
                this.set = metadataColumn.binValueHeader;
            } else {
                String metadataRawText = this.columns.get(metadataColumn.getBinValuePos());
                if (metadataColumn.getBinNameHeader().equalsIgnoreCase(Constants.SET)) {
                    if (this.set == null) {
                        this.set = metadataRawText;
                    }
                }
            }
        }
        // use set name to create key
        for (ColumnDefinition metadataColumn : this.metadataMapping) {
            if (metadataColumn.getBinNameHeader().equalsIgnoreCase(Constants.KEY)) {
                String metadataRawText = this.columns.get(metadataColumn.getBinValuePos());
                if (metadataColumn.getSrcType() == SrcColumnType.INTEGER) {
                    Long integer = Long.parseLong(metadataRawText);
                    this.key = new Key(this.nameSpace, this.set, integer);
                } else {
                    this.key = new Key(this.nameSpace, this.set, metadataRawText);
                }
            }
        }

        for (ColumnDefinition binColumn : this.binMapping) {
            Bin bin = null;

            if (!binColumn.staticName) {
                binColumn.binNameHeader = this.columns.get(binColumn.binNamePos);
            }

            if (!binColumn.staticValue) {
                String binRawText = null;
                if (binColumn.binValueHeader != null
                        && binColumn.binValueHeader.toLowerCase().equals(Constants.SYSTEM_TIME)) {
                    SimpleDateFormat sdf = new SimpleDateFormat(binColumn.getEncoding());//dd/MM/yyyy
                    Date now = new Date();
                    binRawText = sdf.format(now);
                } else {
                    binRawText = this.columns.get(binColumn.getBinValuePos());
                }

                if (binRawText.equals(""))
                    continue;

                switch (binColumn.getSrcType()) {
                case INTEGER:
                    //Server stores all integer type data in 64bit so use long
                    Long integer;
                    try {
                        integer = Long.parseLong(binRawText);
                        bin = new Bin(binColumn.getBinNameHeader(), integer);
                    } catch (Exception pi) {
                        log.error("File:" + Utils.getFileName(this.fileName) + " Line:" + lineNumber
                                + " Integer/Long Parse Error:" + pi);
                    }

                    break;
                case FLOAT:

                    /**
                     * Floating type data can be stored as 8 byte byte array.
                      */
                    try {
                        float binfloat = Float.parseFloat(binRawText);
                        byte[] byteFloat = ByteBuffer.allocate(8).putFloat(binfloat).array();
                        bin = new Bin(binColumn.getBinNameHeader(), byteFloat);
                    } catch (Exception e) {
                        log.error("File:" + Utils.getFileName(this.fileName) + " Line:" + lineNumber
                                + " Floating number Parse Error:" + e);
                    }
                    break;
                case STRING:
                    bin = new Bin(binColumn.getBinNameHeader(), binRawText);
                    break;
                case BLOB:
                    if (binColumn.getDstType().equals(DstColumnType.BLOB)) {
                        if (binColumn.encoding.equalsIgnoreCase(Constants.HEX_ENCODING))
                            bin = new Bin(binColumn.getBinNameHeader(), this.toByteArray(binRawText)); //TODO
                    }

                    break;
                case LIST:
                    /*
                     * Assumptions
                     * 1. Items are separated by a colon ','
                     * 2. Item value will be a string
                     * 3. List will be in double quotes
                     * 
                     * No support for nested maps or nested lists
                     * 
                     */
                    List<String> list = new ArrayList<String>();
                    String[] listValues = binRawText.split(Constants.LIST_DELEMITER, -1);
                    if (listValues.length > 0) {
                        for (String value : listValues) {
                            list.add(value.trim());
                        }
                        bin = Bin.asList(binColumn.getBinNameHeader(), list);
                    } else {
                        bin = null;
                        log.error("Error: Cannot parse to a list: " + binRawText);
                    }
                    break;
                case MAP:
                    /*
                     * Asumptions:
                     * 1. Items are separated by a colon ','
                     * 2. Name value pairs are separated by equals ':'
                     * 3. Map key is a string
                     * 4. Map value will be a string
                     * 5. Map will be in double quotes
                     * 
                     * No support for nested maps or nested lists
                     * 
                     */
                    Map<String, Object> map = new HashMap<String, Object>();
                    String[] mapValues = binRawText.split(Constants.MAP_DELEMITER, -1);
                    if (mapValues.length > 0) {
                        for (String value : mapValues) {
                            String[] kv = value.split(Constants.MAPKEY_DELEMITER);
                            if (kv.length != 2)
                                log.error("Error: Cannot parse map <k,v> using: " + kv);
                            else
                                map.put(kv[0].trim(), kv[1].trim());
                        }
                        log.debug(map.toString());
                        bin = Bin.asMap(binColumn.getBinNameHeader(), map);
                    } else {
                        bin = null;
                        log.error("Error: Cannot parse to a map: " + binRawText);
                    }
                    break;
                case JSON:
                    try {
                        log.debug(binRawText);
                        if (jsonParser == null)
                            jsonParser = new JSONParser();

                        Object obj = jsonParser.parse(binRawText);
                        if (obj instanceof JSONArray) {
                            JSONArray jsonArray = (JSONArray) obj;
                            bin = Bin.asList(binColumn.getBinNameHeader(), jsonArray);
                        } else {
                            JSONObject jsonObj = (JSONObject) obj;
                            bin = Bin.asMap(binColumn.getBinNameHeader(), jsonObj);
                        }
                    } catch (ParseException e) {
                        log.error("Failed to parse JSON", e);
                    }
                    break;
                case TIMESTAMP:
                    if (binColumn.getDstType().equals(DstColumnType.INTEGER)) {
                        DateFormat format = new SimpleDateFormat(binColumn.getEncoding());
                        try {
                            Date formatDate = format.parse(binRawText);
                            long miliSecondForDate = formatDate.getTime() - timeZoneOffset;

                            if (binColumn.getEncoding().contains(".SSS")
                                    && binColumn.binValueHeader.toLowerCase().equals(Constants.SYSTEM_TIME)) {
                                //We need time in miliseconds so no need to change it to seconds
                            } else {
                                miliSecondForDate = miliSecondForDate / 1000;
                            }
                            bin = new Bin(binColumn.getBinNameHeader(), miliSecondForDate);
                            log.trace("Date format:" + binRawText + " in seconds:" + miliSecondForDate);
                        } catch (java.text.ParseException e) {
                            e.printStackTrace();
                        }
                    } else if (binColumn.getDstType().equals(DstColumnType.STRING)) {
                        bin = new Bin(binColumn.getBinNameHeader(), binRawText);
                    }
                    break;

                default:

                }
            } else {
                bin = new Bin(binColumn.getBinNameHeader(), binColumn.getBinValueHeader());
            }

            if (bin != null) {
                bins.add(bin);
            }
        }
        lineProcessed = true;
        log.trace("Formed key and bins for line " + lineNumber + " Key: " + this.key.userKey + " Bins:"
                + this.bins.toString());
    } catch (AerospikeException ae) {
        log.error("File:" + Utils.getFileName(this.fileName) + " Line:" + lineNumber
                + " Aerospike Bin processing Error:" + ae.getResultCode());
        if (log.isDebugEnabled()) {
            ae.printStackTrace();
        }
        counters.write.processingErrors.getAndIncrement();
        counters.write.recordProcessed.addAndGet(this.lineSize);
        errorTotal = (counters.write.readErrors.get() + counters.write.writeErrors.get()
                + counters.write.processingErrors.get());
        if (this.abortErrorCount != 0 && this.abortErrorCount < errorTotal) {
            System.exit(-1);
        }
    } catch (ParseException pe) {
        log.error("File:" + Utils.getFileName(this.fileName) + " Line:" + lineNumber + " Parsing Error:" + pe);
        if (log.isDebugEnabled()) {
            pe.printStackTrace();
        }
        counters.write.processingErrors.getAndIncrement();
        counters.write.recordProcessed.addAndGet(this.lineSize);
        errorTotal = (counters.write.readErrors.get() + counters.write.writeErrors.get()
                + counters.write.processingErrors.get());
        if (this.abortErrorCount != 0 && this.abortErrorCount < errorTotal) {
            System.exit(-1);
        }
    } catch (Exception e) {
        log.error("File:" + Utils.getFileName(this.fileName) + " Line:" + lineNumber + " Unknown Error:" + e);
        if (log.isDebugEnabled()) {
            e.printStackTrace();
        }
        counters.write.processingErrors.getAndIncrement();
        counters.write.recordProcessed.addAndGet(this.lineSize);
        errorTotal = (counters.write.readErrors.get() + counters.write.writeErrors.get()
                + counters.write.processingErrors.get());
        if (this.abortErrorCount != 0 && this.abortErrorCount < errorTotal) {
            System.exit(-1);
        }
    }

    return lineProcessed;
}

From source file:nl.vumc.biomedbridges.galaxy.GalaxyWorkflowTest.java

/**
 * Test the constructor when the JSONParser.parse method throws a parse exception (which is caught by the parseJson
 * method)./*  ww w  .  ja v a  2  s .co  m*/
 */
@Test
public void testConstructorWithParseException() throws ParseException {
    final JSONParser jsonParserMock = Mockito.mock(JSONParser.class);
    Mockito.when(jsonParserMock.parse(Mockito.anyString())).thenThrow(new ParseException(6));
    new GalaxyWorkflow(Constants.CONCATENATE_WORKFLOW, null, jsonParserMock);
}

From source file:semRewrite.substitutor.ExternalSubstitutor.java

/****************************************************************
 * {//from ww  w .  j  a  v  a 2 s .  c  o m
 * "query": "blah blah blah",
 *      "annotatations": [
 *          {
 *              "types": [
 *                  "...",
 *                  ...
 *              ],
 *              "segmentation": [
 *                  "...",
 *                  ...
 *              ],
 *          }
 *      ],
 * }
 */
private Segmentation parseNERJson(String json) {

    try {
        Segmentation result = new Segmentation();
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(json);
        JSONObject jsonObject = (JSONObject) obj;
        System.out.println("ExternaSubstitutor.parseNERJson(): Reading JSON file: " + jsonObject);

        JSONArray anno = (JSONArray) jsonObject.get("annotatations");
        System.out.println("ExternalSubstitutor.parseNERJson(): annotations: " + anno);
        if (anno == null || anno.size() == 0 || anno.get(0) == null) {
            System.out.println("ExternalSubstitutor.parseNERJson(): bad JSON: " + json);
            throw new ParseException(0);
        }
        JSONObject msg = (JSONObject) anno.get(0);
        JSONArray typeObj = (JSONArray) msg.get("types");
        Iterator<String> iterator = typeObj.iterator();
        ArrayList<String> types = new ArrayList<String>();
        while (iterator.hasNext()) {
            result.types.add(iterator.next());
        }

        JSONArray msg2 = (JSONArray) msg.get("segmentation");
        Iterator<String> iterator2 = msg2.iterator();
        tokenCounter = 1;
        while (iterator2.hasNext()) {
            result.addStringSegment(iterator2.next());
        }
        return result;
    } catch (ParseException pe) {
        System.out.println("Error in ExternaSubstitutor.prepare(): parseException: " + json);
        pe.printStackTrace();
        return null;
    }
}