List of usage examples for com.fasterxml.jackson.core JsonLocation getCharOffset
public long getCharOffset()
From source file:com.github.fge.jsonschema.servlets.SyntaxValidateServlet.java
private static JsonNode buildParsingError(final JsonProcessingException e, final boolean crlf) { final JsonLocation location = e.getLocation(); final ObjectNode ret = JsonNodeFactory.instance.objectNode(); /*/*from w ww . j a va2s. co m*/ * Unfortunately, for some reason, Jackson botches the column number in * its JsonPosition -- I cannot figure out why exactly. However, it does * have a correct offset into the buffer. * * The problem is that if the input has CR/LF line terminators, its * offset will be "off" by the number of lines minus 1 with regards to * what JavaScript sees as positions in text areas. Make the necessary * adjustments so that the caret jumps at the correct position in this * case. */ final int lineNr = location.getLineNr(); int offset = (int) location.getCharOffset(); if (crlf) offset = offset - lineNr + 1; ret.put(ParseError.LINE, lineNr); ret.put(ParseError.OFFSET, offset); // Finally, put the message ret.put(ParseError.MESSAGE, e.getOriginalMessage()); return ret; }
From source file:org.seedstack.seed.core.internal.data.DataManagerImpl.java
private void throwParsingError(JsonLocation jsonLocation, String message) { throw SeedException.createNew(DataErrorCode.FAILED_TO_PARSE_DATA_STREAM).put("parsingError", message) .put("line", jsonLocation.getLineNr()).put("col", jsonLocation.getColumnNr()) .put("offset", jsonLocation.getCharOffset()); }
From source file:com.github.jknack.handlebars.server.HbsServlet.java
/** * Deal with a {@link HandlebarsException}. * * @param ex The handlebars exception.//from w ww . ja v a2s . co m * @param request The http request. * @param response The http response. * @throws IOException If something goes wrong. */ private void jsonError(final JsonParseException ex, final HttpServletRequest request, final HttpServletResponse response) throws IOException { Map<String, Object> root = new HashMap<String, Object>(); Map<String, Object> error = new HashMap<String, Object>(); String filename = jsonFilename(request); JsonLocation location = ex.getLocation(); String reason = ex.getMessage(); int atIdx = reason.lastIndexOf(" at "); if (atIdx > 0) { reason = reason.substring(0, atIdx); } error.put("filename", filename); error.put("line", location.getLineNr()); error.put("column", location.getColumnNr()); error.put("reason", reason); error.put("type", "JSON error"); String json = read(filename); StringBuilder evidence = new StringBuilder(); int i = (int) location.getCharOffset(); int nl = 0; while (i >= 0 && nl < 2) { char ch = json.charAt(i); if (ch == '\n') { nl++; } evidence.insert(0, ch); i--; } i = (int) location.getCharOffset() + 1; nl = 0; while (i < json.length() && nl < 2) { char ch = json.charAt(i); if (ch == '\n') { nl++; } evidence.append(ch); i++; } error.put("evidence", evidence); root.put("error", error); int firstLine = Math.max(1, ex.getLocation().getLineNr() - 1); fancyError(root, firstLine, "JScript", response); }
From source file:com.google.openrtb.json.AbstractOpenRtbJsonReader.java
/** * Read any extensions that may exist in a message. * * @param msg Builder of a message that may contain extensions * @param par The JSON parser, positioned at the "ext" field * @param <EB> Type of message builder being constructed * @throws IOException any parsing error *//*from w w w . j a v a 2s . c o m*/ protected final <EB extends ExtendableBuilder<?, EB>> void readExtensions(EB msg, JsonParser par) throws IOException { @SuppressWarnings("unchecked") Set<OpenRtbJsonExtReader<EB>> extReaders = factory.getReaders((Class<EB>) msg.getClass()); if (extReaders.isEmpty()) { par.skipChildren(); return; } startObject(par); JsonToken tokLast = par.getCurrentToken(); JsonLocation locLast = par.getCurrentLocation(); while (true) { boolean extRead = false; for (OpenRtbJsonExtReader<EB> extReader : extReaders) { if (extReader.filter(par)) { extReader.read(msg, par); JsonToken tokNew = par.getCurrentToken(); JsonLocation locNew = par.getCurrentLocation(); boolean advanced = tokNew != tokLast || !locNew.equals(locLast); extRead |= advanced; if (!endObject(par)) { return; } else if (advanced && par.getCurrentToken() != JsonToken.FIELD_NAME) { tokLast = par.nextToken(); locLast = par.getCurrentLocation(); } else { tokLast = tokNew; locLast = locNew; } } } if (!endObject(par)) { // Can't rely on this exit condition inside the for loop because no readers may filter. return; } if (!extRead) { // No field was consumed by any reader, so we need to skip the field to make progress. if (logger.isDebugEnabled()) { logger.debug("Extension field not consumed by any reader, skipping: {} @{}:{}", par.getCurrentName(), locLast.getLineNr(), locLast.getCharOffset()); } par.nextToken(); par.skipChildren(); tokLast = par.nextToken(); locLast = par.getCurrentLocation(); } // Else loop, try all readers again } }
From source file:org.apache.openaz.xacml.std.json.JSONRequest.java
/** * Read characters from the given <code>InputStream</code> and parse them into an XACML * {@link org.apache.openaz.xacml.api.Request} object. * * @param is//from w ww . jav a 2 s .co m * @return * @throws JSONStructureException */ public static Request load(InputStream is) throws JSONStructureException { // TODO - ASSUME that order of members within an object does not matter (Different from XML, in JSON // everything is handled as Maps so order does not matter) // ensure shorthand map is set up if (shorthandMap == null) { initShorthandMap(); } // ensure that we have an instance of the DataTypeFactory for generating AttributeValues by DataType if (dataTypeFactory == null) { try { dataTypeFactory = DataTypeFactory.newInstance(); if (dataTypeFactory == null) { throw new NullPointerException("No DataTypeFactory found"); } } catch (FactoryException e) { throw new JSONStructureException("Unable to find DataTypeFactory, e=" + e); } } // create a new Request object to be filled in StdMutableRequest stdMutableRequest = null; String json = null; ObjectMapper mapper = null; try { // read the inputStream into a buffer (trick found online scans entire input looking for // end-of-file) java.util.Scanner scanner = new java.util.Scanner(is); scanner.useDelimiter("\\A"); json = scanner.hasNext() ? scanner.next() : ""; scanner.close(); mapper = new ObjectMapper().setVisibility(PropertyAccessor.FIELD, Visibility.ANY); // TODO - ASSUME that any duplicated component is a bad thing (probably indicating an error in the // incoming JSON) mapper.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true); Map<?, ?> root = mapper.readValue(json, Map.class); // // Does the request exist? // Map<?, ?> jsonRequestMap = (Map<?, ?>) root.remove("Request"); if (jsonRequestMap == null) { throw new JSONStructureException("No \"Request\" property found."); } checkUnknown("Top-level message", root); stdMutableRequest = new StdMutableRequest(); // // Is there a Category? // Object categoryList = jsonRequestMap.remove("Category"); if (categoryList != null && !(categoryList instanceof List)) { throw new JSONStructureException( "Category must contain list of objects, not '" + categoryList.getClass() + "'"); } if (categoryList != null) { // // Iterate each Category // Iterator<?> iter = ((List<?>) categoryList).iterator(); while (iter.hasNext()) { Object category = iter.next(); if (!(category instanceof Map)) { throw new JSONStructureException( "Category list must contain objects contained within curly braces ({})"); } parseCategory((Map<?, ?>) category, "Category", null, stdMutableRequest); } } // The following may be either a single instance or an array. This allows multiple decisions to // work with the Default Category objects. // Example: // "AccessSubject" : [ {attributes group one}, // {attributes group two} // ] // // Look for default Shorthand AccessSubject // parseDefaultCategory(jsonRequestMap, "AccessSubject", "urn:oasis:names:tc:xacml:1.0:subject-category:access-subject", stdMutableRequest); // // Provide backward compatibility for our PEP's // parseDefaultCategory(jsonRequestMap, "Subject", "urn:oasis:names:tc:xacml:1.0:subject-category:access-subject", stdMutableRequest); // // Look for default Shorthand Action // parseDefaultCategory(jsonRequestMap, "Action", "urn:oasis:names:tc:xacml:3.0:attribute-category:action", stdMutableRequest); // // Look for default Shorthand Resource // parseDefaultCategory(jsonRequestMap, "Resource", "urn:oasis:names:tc:xacml:3.0:attribute-category:resource", stdMutableRequest); // // Look for default Shorthand Environment // parseDefaultCategory(jsonRequestMap, "Environment", "urn:oasis:names:tc:xacml:3.0:attribute-category:environment", stdMutableRequest); // // Look for default Shorthand RecipientSubject // parseDefaultCategory(jsonRequestMap, "RecipientSubject", "urn:oasis:names:tc:xacml:1.0:subject-category:recipient-subject", stdMutableRequest); // // Look for default Shorthand IntermediarySubject // parseDefaultCategory(jsonRequestMap, "IntermediarySubject", "urn:oasis:names:tc:xacml:1.0:subject-category:intermediary-subject", stdMutableRequest); // // Look for default Shorthand Codebase // parseDefaultCategory(jsonRequestMap, "Codebase", "urn:oasis:names:tc:xacml:1.0:subject-category:codebase", stdMutableRequest); // // Look for default Shorthand RequestingMachine // parseDefaultCategory(jsonRequestMap, "RequestingMachine", "urn:oasis:names:tc:xacml:1.0:subject-category:requesting-machine", stdMutableRequest); // // MultiRequest // Map<?, ?> multiRequests = (Map<?, ?>) jsonRequestMap.remove("MultiRequests"); if (multiRequests != null) { if (!(multiRequests instanceof Map)) { throw new JSONStructureException("MultiRequests must be object structure, not single value"); } List<?> requestReferenceList = (List<?>) multiRequests.remove("RequestReference"); if (requestReferenceList == null) { throw new JSONStructureException("MultiRequest must contain a RequestReference element"); } if (requestReferenceList.size() < 1) { throw new JSONStructureException( "MultiRequest must contain at least one element in the RequestReference list"); } checkUnknown("MultiRequest", multiRequests); for (Object requestReferenceMapObject : requestReferenceList) { if (!(requestReferenceMapObject instanceof Map)) { throw new JSONStructureException("MultiRequest RequestReference must be object"); } Map<?, ?> requestReferenceMap = (Map<?, ?>) requestReferenceMapObject; // each object within the list must contain a ReferenceId and only a ReferenceId Object referenceIdListObject = requestReferenceMap.remove("ReferenceId"); if (referenceIdListObject == null) { throw new JSONStructureException( "MultiRequest RequestReference list element must contain ReferenceId"); } List<?> referenceIdList = (List<?>) referenceIdListObject; if (referenceIdList.size() == 0) { // the spec does not disallow empty list RequestReference objects continue; } checkUnknown("RequestReference", requestReferenceMap); // create reference corresponding to RequestReference list element StdMutableRequestReference requestReference = new StdMutableRequestReference(); for (Object referenceId : referenceIdList) { // add attributes to the reference // Since the order of the JSON is not constrained, we could process this section // before the section containing attribute being referenced, // so we cannot do a cross-check here to verify that the attribute reference exists. // That will happen later when the PDP attempts to find the attribute. StdRequestAttributesReference requestAttributesReference = new StdRequestAttributesReference( (String) referenceId); requestReference.add(requestAttributesReference); } stdMutableRequest.add(requestReference); } } // // ReturnPolicyIdList // // If omitted this is set to a default of false by the StdMutableRequest constructor. // Object returnPolicyIdList = jsonRequestMap.remove("ReturnPolicyIdList"); Boolean returnPolicyIdListBoolean = makeBoolean(returnPolicyIdList, "ReturnPolicyIdList"); if (returnPolicyIdList != null) { stdMutableRequest.setReturnPolicyIdList(returnPolicyIdListBoolean); } // // CombinedDecision // // If omitted this is set to a default of false by the StdMutableRequest constructor. // Object combinedDecision = jsonRequestMap.remove("CombinedDecision"); Boolean combinedDecisionBoolean = makeBoolean(combinedDecision, "CombinedDecision"); if (combinedDecision != null) { stdMutableRequest.setCombinedDecision(combinedDecisionBoolean); } // // XPath // // The JSON spec says that this has a default value, implying that if it is missing in the Request // we should fill it in. // However the XML (DOM) version does not do that. If the value is missing it leaves the // requestDefaults object blank. // We are following the XML approach and ignoring the Default value for this field in the spec. // TODO - Assume that no value for XPathVersion means "leave as null", not "fill in the default // value from spec. This violates the JSON spec Object xPath = jsonRequestMap.remove("XPathVersion"); if (xPath != null) { // XPath is given in the JSON input if (!(xPath instanceof String)) { throw new JSONStructureException("XPathVersion not a URI passed as a String"); } URI xPathUri = null; try { xPathUri = new URI(xPath.toString()); } catch (Exception e) { throw new JSONStructureException("XPathVersion not a valid URI: '" + xPath + "'", e); } StdRequestDefaults requestDefaults = new StdRequestDefaults(xPathUri); stdMutableRequest.setRequestDefaults(requestDefaults); } checkUnknown("Request", jsonRequestMap); } catch (JsonParseException e) { // try to point to problem area in JSON input, if possible JsonLocation location = e.getLocation(); String locationOfError = "(unavailable)"; if (location != null && location != JsonLocation.NA) { String jsonText = json; if (location.getLineNr() > 1) { String[] jsonArray = jsonText.split("\\r?\\n|\\r"); jsonText = jsonArray[location.getLineNr()]; } if (location.getCharOffset() < jsonText.length()) { if (location.getCharOffset() > 0) { locationOfError = jsonText.substring((int) location.getCharOffset() - 1); } if (locationOfError.length() > 30) { locationOfError = locationOfError.substring(0, 30); } } } throw new JSONStructureException("Unable to parse JSON starting at text'" + locationOfError + "', input was '" + json + "', exception: " + e, e); } catch (JsonMappingException e) { throw new JSONStructureException("Unable to map JSON '" + json + "', exception: " + e, e); } catch (IOException e) { throw new JSONStructureException("Unable to read JSON input, exception: " + e, e); } // all done return new StdRequest(stdMutableRequest); }