/** * Returns a list of {@link ParameterBinding}s found in the given {@code input} or an * {@link Collections#emptyList()}. * * @param input - the string with parameter bindings * @return - the list of parameters */ public List<ParameterBinding> parseParameterBindingsFrom(String input) { if (!StringUtils.hasText(input)) { return Collections.emptyList(); } List<ParameterBinding> bindings = new ArrayList<>(); String parseableInput = makeParameterReferencesParseable(input); try { collectParameterReferencesIntoBindings(bindings, JSON.parse(parseableInput)); } catch(JSONParseException e) { // the parseable input is not JSON - some stages like $unwind and $count only have strings. // nothing to do here. LOGGER.trace("JSONParseException:", e); } return bindings; }
/** * Search the request for a field named 'metadata' (or 'properties') which * must contain valid JSON * * @param formData * @return the parsed BsonDocument from the form data or an empty * BsonDocument */ protected static BsonDocument extractMetadata( final FormData formData) throws JSONParseException { BsonDocument metadata = new BsonDocument(); final String metadataString; metadataString = formData.getFirst(FILE_METADATA) != null ? formData.getFirst(FILE_METADATA).getValue() : formData.getFirst(PROPERTIES) != null ? formData.getFirst(PROPERTIES).getValue() : null; if (metadataString != null) { metadata = BsonDocument.parse(metadataString); } return metadata; }
static Object parseJSONExpr( String jsonExpr ) throws OdaException { try { return JSON.parse( jsonExpr ); } catch( JSONParseException ex ) { String errMsg = Messages.bind( Messages.driverUtil_parsingError, jsonExpr ); DriverUtil.getLogger().log( Level.INFO, errMsg, ex ); // caller may choose to ignore it; log at INFO level OdaException newEx = new OdaException( errMsg ); newEx.initCause( ex ); throw newEx; } }
@Override public MongoQueryOptions buildQueryOptions(String rowLimit) { MongoQueryOptions mongoQueryOptions = new MongoQueryOptions(); try { mongoQueryOptions.setFilter(getQueryFrom(selectEditor)); mongoQueryOptions.setProjection(getQueryFrom(projectionEditor)); mongoQueryOptions.setSort(getQueryFrom(sortEditor)); } catch (JSONParseException ex) { notifyOnErrorForOperator(selectEditor.getComponent(), ex); } if (StringUtils.isNotBlank(rowLimit)) { mongoQueryOptions.setResultLimit(Integer.parseInt(rowLimit)); } return mongoQueryOptions; }
void notifyOnErrorForOperator(JComponent component, Exception ex) { String message; if (ex instanceof JSONParseException) { message = StringUtils.removeStart(ex.getMessage(), "\n"); } else { message = String.format("%s: %s", ex.getClass().getSimpleName(), ex.getMessage()); } NonOpaquePanel nonOpaquePanel = new NonOpaquePanel(); JTextPane textPane = Messages.configureMessagePaneUi(new JTextPane(), message); textPane.setFont(COURIER_FONT); textPane.setBackground(MessageType.ERROR.getPopupBackground()); nonOpaquePanel.add(textPane, BorderLayout.CENTER); nonOpaquePanel.add(new JLabel(MessageType.ERROR.getDefaultIcon()), BorderLayout.WEST); JBPopupFactory.getInstance().createBalloonBuilder(nonOpaquePanel) .setFillColor(MessageType.ERROR.getPopupBackground()) .createBalloon() .show(new RelativePoint(component, new Point(0, 0)), Balloon.Position.above); }
@Test(expected=JSONParseException.class) public void testTBSONSerializerMapObjectObject() throws Exception { TBSONSerializer tbsonSerializer = new TBSONSerializer(); BSonThrift inputBsonThrift = new BSonThrift(); inputBsonThrift.setOneString("string value"); inputBsonThrift.setOneBigInteger(123456); // A Map like Java Map Map<KeyObject,AnotherThrift> oneMap = new HashMap<KeyObject,AnotherThrift>(); oneMap.put(new KeyObject("key1",1), new AnotherThrift("value1", 1)); oneMap.put(new KeyObject("key2",2), new AnotherThrift("value2", 2)); inputBsonThrift.setOneMapObjectKeyObjectValue(oneMap); // serialize into DBObject DBObject dbObject = tbsonSerializer.serialize(inputBsonThrift); assertEquals(inputBsonThrift, dbObject); }
/** * extract datas from a GET REQUEST (query string params) * @param request * @return request datas as a BSONObject */ private static BasicBSONObject extractGetRequestData(HttpServletRequest request){ try{ String query; if(useBSON) query = ServletUtils.decryptBSON(request.getQueryString()); else query = request.getQueryString(); if(query!=null){ query = query.replaceAll("(%22|%27)", "\""); query = query.replaceAll("%20", " "); BasicBSONObject params = (BasicBSONObject) JSON.parse(query); return params; } else return new BasicBSONObject(); } catch (JSONParseException e){ return new BasicBSONObject(); } }
@Override public void echo(int type, String msg) { String msgType = ""; switch(type){ case Echo.ERR: msgType = "error"; break; case Echo.INFO: msgType = "info"; break; default: msgType = "message"; break; } String str = "{'"+msgType+"' : '"+msg+"'}"; try{ BSONObject obj = (BSONObject) JSON.parse(str); this.echo(obj); } catch (JSONParseException e){ } }
private boolean isInvalidJson(String body) { if (StringUtils.isBlank(body)) { return true; } try { JSON.parse(body); } catch (JSONParseException e) { return true; } return false; }
private boolean isValidJson(String json) { if (StringUtils.isBlank(json)) { return false; } else { try { JSON.parse(json); } catch (JSONParseException e) { return false; } } return true; }
private boolean isInvalidJson(String json) { if (StringUtils.isBlank(json)) { return true; } try { JSON.parse(json); } catch (JSONParseException e) { return true; } return false; }
private void validateJsonField(String name, String jsonString) { try { JSON.parse(jsonString); } catch (JSONParseException ex) { throw new ConfigException(String.format("Invalid JSON string was given for '%s' parameter. [%s]", name, jsonString)); } }
/** * Read the current character, making sure that it is a hexidecimal character. * * @throws JSONParseException * if the current character is not a hexidecimal character */ public void readHex() { if (pos < s.length() && ((s.charAt(pos) >= '0' && s.charAt(pos) <= '9') || (s.charAt(pos) >= 'A' && s.charAt(pos) <= 'F') || (s.charAt(pos) >= 'a' && s .charAt(pos) <= 'f'))) { pos++; } else { throw new JSONParseException(s, pos); } }
/** * Parses the next array. * * @return the array * @throws JSONParseException * if invalid JSON is found */ protected Object parseArray(String name) { if (name != null) { _callback.arrayStart(name); } else { _callback.arrayStart(); } read('['); int i = 0; char current = get(); while (current != ']') { String elemName = String.valueOf(i++); Object elem = parse(elemName); doCallback(elemName, elem); if ((current = get()) == ',') { read(','); } else if (current == ']') { break; } else { throw new JSONParseException(s, pos); } } read(']'); return _callback.arrayDone(); }
@Override public MongoQueryOptions buildQueryOptions(String rowLimit) { MongoQueryOptions mongoQueryOptions = new MongoQueryOptions(); try { mongoQueryOptions.setOperations(getQuery()); } catch (JSONParseException ex) { notifyOnErrorForOperator(editor.getComponent(), ex); } if (StringUtils.isNotBlank(rowLimit)) { mongoQueryOptions.setResultLimit(Integer.parseInt(rowLimit)); } return mongoQueryOptions; }
@Override public void echo(String msg) { try{ BSONObject obj = (BSONObject) JSON.parse(msg); this.echo(obj); } catch (JSONParseException e){ this.echo(Echo.MSG, msg); } }
@Override public void echo(String msg) { try{ JSON.parse(msg); this.out.println(msg); } catch (JSONParseException e){ this.echo(Echo.MSG, msg); } }
/** * Parse an unknown type. * * @return Object the next item * @throws JSONParseException * if invalid JSON is found */ protected Object parse(String name) { Object value = null; char current = get(); switch (current) { // null case 'n': read('n'); read('u'); read('l'); read('l'); value = null; break; // NaN case 'N': read('N'); read('a'); read('N'); value = Double.NaN; break; // true case 't': read('t'); read('r'); read('u'); read('e'); value = true; break; // false case 'f': read('f'); read('a'); read('l'); read('s'); read('e'); value = false; break; // string case '\'': case '\"': value = parseString(true); break; // number case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '+': case '-': value = parseNumber(); break; // array case '[': value = parseArray(name); break; // object case '{': value = parseObject(name); break; default: throw new JSONParseException(s, pos); } return value; }
public static Representation getErrorJsonDocument(String href, int code, RequestContext context, String httpStatusText, String message, Throwable t, boolean includeStackTrace) { Representation rep = new Representation(href); rep.addProperty("http status code", new BsonInt32(code)); rep.addProperty("http status description", new BsonString(httpStatusText)); if (message != null) { rep.addProperty( "message", new BsonString(avoidEscapedChars(message))); } Representation nrep = new Representation(); if (t != null) { nrep.addProperty( "exception", new BsonString(t.getClass().getName())); if (t.getMessage() != null) { if (t instanceof JSONParseException) { nrep.addProperty("exception message", new BsonString("invalid json")); } else { nrep.addProperty("exception message", new BsonString( avoidEscapedChars(t.getMessage()))); } } if (includeStackTrace) { BsonArray stackTrace = getStackTraceJson(t); if (stackTrace != null) { nrep.addProperty("stack trace", stackTrace); } } rep.addRepresentation("rh:exception", nrep); } // add warnings if (context != null && context.getWarnings() != null) { context.getWarnings().forEach(w -> rep.addWarning(w)); } return rep; }
@Test(expected = JSONParseException.class) public void parseBadJsonBodyToRow() { final EventParser eventParser = new EventParser(MappingDefinition.load("/simple_body_row_json.json")); eventParser.parse(EventBuilder.withBody("{???? \"foo\": \"bar\" }".getBytes(Charsets.UTF_8))); }
/** * Read the current character, making sure that it is the expected character. * Advances the pointer to the next character. * * @param ch * the character expected * * @throws JSONParseException * if the current character does not match the given character */ public void read(char ch) { if (!check(ch)) { throw new JSONParseException(s, pos); } pos++; }
/** * Returs the FindIterable of the collection applying sorting, filtering and * projection. * * @param collection the mongodb MongoCollection<BsonDocument> object * @param sortBy the Deque collection of fields to use for sorting (prepend * field name with - for descending sorting) * @param filters the filters to apply. it is a Deque collection of mongodb * query conditions. * @param keys * @return * @throws JSONParseException */ FindIterable<BsonDocument> getFindIterable( MongoCollection<BsonDocument> collection, BsonDocument sortBy, BsonDocument filters, BsonDocument keys) throws JSONParseException;