List of usage examples for org.json.simple.parser JSONParser getPosition
public int getPosition()
From source file:com.tobedevoured.json.SimpleStream.java
/** * Process the buffer into json entities. When allow for multiple attempts for malformed json, which * can be caused by a json fragment in the stream. * * @param allowedMalformedAttempts int//from w ww. j av a2 s .c om * @return List * @throws StreamException parser error */ public List processBuffer(int allowedMalformedAttempts) throws StreamException { JSONParser parser = new JSONParser(); JsonStreamHandler streamHandler = new JsonStreamHandler(); List entities = new ArrayList(); int pos = 0; // Check if the buffer is crammed to the brim boolean bufferOverflow = buffer.length() > bufferSize; while (pos < buffer.length() - 1) { String fragment = buffer.substring(pos); try { parser.parse(fragment, streamHandler); } catch (ParseException e) { if (ParseException.ERROR_UNEXPECTED_CHAR == e.getErrorType()) { // Check if should wait for more streaming json before declaring it malformed if (malformedFragmentAttempts < allowedMalformedAttempts) { malformedFragmentAttempts++; } else { throw new StreamException(e); } } else if (ParseException.ERROR_UNEXPECTED_TOKEN != e.getErrorType()) { throw new StreamException(e); } logger.debug("detected json fragment, buffering for the rest: {}", fragment); return entities; } // increment the position in the buffer int currentPos = pos; pos = pos + parser.getPosition() + 1; // Create entity from buffer Object val = null; try { val = parser.parse(buffer.substring(currentPos, pos).trim()); buffer.delete(currentPos, pos); pos = 0; } catch (ParseException e) { throw new StreamException(e); } // valid entity created, reset the malformed counter malformedFragmentAttempts = 0; if (callback != null) { logger.info("Executing callback with {}", val); try { callback.apply(val); } catch (Exception e) { logger.error("Failed to execute callback", e); throw new StreamException(e); } } entities.add(val); } // Compact the buffer after an overflow if (buffer.length() < bufferSize && bufferOverflow) { buffer.setLength(bufferSize); } return entities; }