Example usage for com.fasterxml.jackson.core JsonLocation getLineNr

List of usage examples for com.fasterxml.jackson.core JsonLocation getLineNr

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonLocation getLineNr.

Prototype

public int getLineNr() 

Source Link

Usage

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();

    /*//ww  w .  j a  v a2s.  c om
     * 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.emfjson.jackson.errors.JSONException.java

public JSONException(Exception e, JsonLocation location) {
    super(e);/* w  w  w.  j a v  a 2s  .  c  o  m*/
    this.location = location.toString();
    this.line = location.getLineNr();
    this.column = location.getColumnNr();
}

From source file:com.reprezen.swagedit.model.NodeDeserializer.java

private Location createLocation(JsonLocation json) {
    return new Location(json.getLineNr() - 1, json.getColumnNr() - 1);
}

From source file:org.emfjson.jackson.errors.JSONException.java

public JSONException(String message, JsonLocation location) {
    super(message);
    this.location = location.toString();
    this.line = location.getLineNr();
    this.column = location.getColumnNr();
}

From source file:org.raml.parser.rule.SchemaRule.java

@Override
public List<ValidationResult> doValidateValue(ScalarNode node) {
    String value = node.getValue();
    List<ValidationResult> validationResults = super.doValidateValue(node);

    IncludeInfo globaSchemaIncludeInfo = null;
    ScalarNode schemaNode = getGlobalSchemaNode(value);
    if (schemaNode == null) {
        schemaNode = node;//from   w  w  w . j  a  va 2s. c  o  m
    } else {
        value = schemaNode.getValue();
        if (schemaNode.getTag().startsWith(INCLUDE_APPLIED_TAG)) {
            globaSchemaIncludeInfo = new IncludeInfo(schemaNode.getTag());
        }
    }
    if (value == null || isCustomTag(schemaNode.getTag())) {
        return validationResults;
    }

    String mimeType = ((ScalarNode) getParentTupleRule().getKey()).getValue();
    if (mimeType.contains("json")) {
        try {
            JsonNode jsonNode = JsonLoader.fromString(value);
            ProcessingReport report = VALIDATOR.validateSchema(jsonNode);
            if (!report.isSuccess()) {
                StringBuilder msg = new StringBuilder("invalid JSON schema");
                msg.append(getSourceErrorDetail(node));
                for (ProcessingMessage processingMessage : report) {
                    msg.append("\n").append(processingMessage.toString());
                }
                validationResults
                        .add(getErrorResult(msg.toString(), getLineOffset(schemaNode), globaSchemaIncludeInfo));
            }
        } catch (JsonParseException jpe) {
            String msg = "invalid JSON schema" + getSourceErrorDetail(node) + jpe.getOriginalMessage();
            JsonLocation loc = jpe.getLocation();
            validationResults.add(
                    getErrorResult(msg, getLineOffset(schemaNode) + loc.getLineNr(), globaSchemaIncludeInfo));
        } catch (IOException e) {
            String prefix = "invalid JSON schema" + getSourceErrorDetail(node);
            validationResults.add(getErrorResult(prefix + e.getMessage(), UNKNOWN, globaSchemaIncludeInfo));
        }
    } else if (mimeType.contains("xml")) {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        try {
            factory.newSchema(new StreamSource(new StringReader(value)));
        } catch (SAXParseException e) {
            String msg = "invalid XML schema" + getSourceErrorDetail(node) + e.getMessage();
            validationResults.add(
                    getErrorResult(msg, getLineOffset(schemaNode) + e.getLineNumber(), globaSchemaIncludeInfo));
        } catch (SAXException e) {
            String msg = "invalid XML schema" + getSourceErrorDetail(node);
            validationResults.add(getErrorResult(msg, getLineOffset(schemaNode), globaSchemaIncludeInfo));
        }
    }
    return validationResults;
}

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./*w w w.ja  v a  2 s. c  o 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.quinsoft.zeidon.standardoe.ActivateOisFromJsonStream.java

public List<View> read() {
    try {//from w  w  w.  j av a2s.c  o  m
        JsonFactory jsonFactory = new JsonFactory();
        jp = jsonFactory.createParser(stream);
        jp.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);

        // Read the START_OBJECT
        JsonToken token = jp.nextToken();
        if (token != JsonToken.START_OBJECT)
            throw new ZeidonException("OI JSON stream doesn't start with object.");

        token = jp.nextToken();
        if (token != JsonToken.FIELD_NAME)
            throw new ZeidonException("OI JSON missing OI field name.");

        String fieldName = jp.getCurrentName();
        if (fieldName.equals(".meta")) {
            readFileMeta();

            JsonReader reader = getReaderForVersion();
            reader.process();
        } else {
            if (StringUtils.equalsIgnoreCase(fieldName, "version")) {
                token = jp.nextToken(); // Move to value.
                version = jp.getValueAsString();
                token = jp.nextToken(); // Move to next field name.
                assert token == JsonToken.FIELD_NAME;
                fieldName = jp.getCurrentName();
            } else if (StringUtils.isBlank(options.getVersion())) {
                throw new ZeidonException("First field must be version");
            }

            totalRootCount = null;
            if (StringUtils.equalsIgnoreCase(fieldName, "totalRootCount")) {
                token = jp.nextToken(); // Move to value.
                totalRootCount = jp.getValueAsInt();
                token = jp.nextToken(); // Move to next field name.
                assert token == JsonToken.FIELD_NAME;
                fieldName = jp.getCurrentName();
            }

            if (lodDef == null)
                throw new ZeidonException("JSON stream appears to start with the root entity name (%s)"
                        + " but the LodDef has not been specified.", fieldName);

            String rootName = lodDef.getRoot().getName();
            if (!fieldName.equalsIgnoreCase(rootName))
                throw new ZeidonException("The first field in the JSON stream must be the root entity name"
                        + " (%s) or '.meta' but was %s.", rootName, fieldName);

            view = task.activateEmptyObjectInstance(lodDef);
            returnList.add(view);
            if (totalRootCount != null)
                view.setTotalRootCount(totalRootCount);

            JsonReader reader = getSimpleReaderForVersion();
            reader.process();
        }

        jp.close();
    } catch (Exception e) {
        ZeidonException ze = ZeidonException.wrapException(e);
        JsonLocation loc = jp.getCurrentLocation();
        JsonToken token = jp.getCurrentToken();
        ze.appendMessage("Position line=%d col=%d, token=%s", loc.getLineNr(), loc.getColumnNr(),
                token == null ? "No Token" : token.name());
        throw ze;
    }

    return returnList;
}

From source file:com.addthis.hydra.job.web.resources.JobsResource.java

private Response validateJobConfig(String expandedConfig) throws JSONException {
    String message = null;//from  w  w w  . ja v  a 2 s .  c  o m
    int lineNumber = 1;
    try {
        TaskRunner.makeTask(expandedConfig, validationCodec);
        return Response.ok(new JSONObject().put("result", "valid").toString()).build();
    } catch (ConfigException ex) {
        ConfigOrigin exceptionOrigin = ex.origin();
        message = ex.getMessage();
        if (exceptionOrigin != null) {
            lineNumber = exceptionOrigin.lineNumber();
        }
    } catch (JsonProcessingException ex) {
        JsonLocation jsonLocation = ex.getLocation();
        if (jsonLocation != null) {
            lineNumber = jsonLocation.getLineNr();
            message = "Line: " + lineNumber + " ";
        }
        message += ex.getOriginalMessage();
        if (ex instanceof JsonMappingException) {
            String pathReference = ((JsonMappingException) ex).getPathReference();
            if (pathReference != null) {
                message += " referenced via: " + pathReference;
            }
        }
    } catch (Exception other) {
        message = other.toString();
    }
    JSONArray lineColumns = new JSONArray();
    JSONArray lineErrors = new JSONArray();
    lineColumns.put(1);
    lineErrors.put(lineNumber);
    return validateCreateError(message, lineErrors, lineColumns, "postExpansionError");
}

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
 *///w w  w. j  av a 2 s.  com
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
    }
}