Java Code Examples for com.fasterxml.jackson.databind.DeserializationContext#mappingException()

The following examples show how to use com.fasterxml.jackson.databind.DeserializationContext#mappingException() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CustomLocalDateTimeDeserializer.java    From mall with Apache License 2.0 6 votes vote down vote up
@Override
public LocalDateTime deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException {
    JsonToken t = jp.getCurrentToken();
    if (t == JsonToken.VALUE_STRING) {
        String str = jp.getText().trim();
        if (DATE_TIME_FORMATTER_PATTERN.length() == str.length()) {
            return LocalDateTime.parse(str, DATE_TIME_FORMATTER);
        } else if (DATE_TIME_FORMATTER_MILLI_PATTERN.length() == str.length()) {
            return LocalDateTime.parse(str, DATE_TIME_FORMATTER_MILLI);
        }
    }
    if (t == JsonToken.VALUE_NUMBER_INT) {
        return new Timestamp(jp.getLongValue()).toLocalDateTime();
    }
    throw ctxt.mappingException(handledType());
}
 
Example 2
Source File: OpenSkyStatesDeserializer.java    From opensky-api with GNU General Public License v3.0 6 votes vote down vote up
@Override
public OpenSkyStates deserialize(JsonParser jp, DeserializationContext dc) throws IOException {
	if (jp.getCurrentToken() != null && jp.getCurrentToken() != JsonToken.START_OBJECT) {
		throw dc.mappingException(OpenSkyStates.class);
	}
	try {
		OpenSkyStates res = new OpenSkyStates();
		for (jp.nextToken(); jp.getCurrentToken() != null && jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) {
			if (jp.getCurrentToken() == JsonToken.FIELD_NAME) {
				if ("time".equalsIgnoreCase(jp.getCurrentName())) {
					int t = jp.nextIntValue(0);
					res.setTime(t);
				} else if ("states".equalsIgnoreCase(jp.getCurrentName())) {
					jp.nextToken();
					res.setStates(deserializeStates(jp));
				} else {
					// ignore other fields, but consume value
					jp.nextToken();
				}
			} // ignore others
		}
		return res;
	} catch (JsonParseException jpe) {
		throw dc.mappingException(OpenSkyStates.class);
	}
}
 
Example 3
Source File: MetricTypeSerialization.java    From heroic with Apache License 2.0 6 votes vote down vote up
@Override
public MetricType deserialize(JsonParser p, DeserializationContext c) throws IOException {
    if (p.getCurrentToken() != JsonToken.VALUE_STRING) {
        throw c.wrongTokenException(p, JsonToken.VALUE_STRING, null);
    }

    final String identifier = p.getValueAsString();

    if (identifier == null) {
        throw c.mappingException("No identifier specified");
    }

    return MetricType
        .fromIdentifier(identifier)
        .orElseThrow(() -> c.mappingException("Not a valid metric source: " + identifier));
}
 
Example 4
Source File: FilterRegistry.java    From heroic with Apache License 2.0 6 votes vote down vote up
private Filter deserializeObject(final JsonParser p, final DeserializationContext c)
    throws IOException {
    final ObjectNode object = (ObjectNode) p.readValueAs(JsonNode.class);

    final JsonNode typeNode = object.remove("type");

    if (typeNode == null) {
        throw c.mappingException("Expected 'type' field");
    }

    if (!typeNode.isTextual()) {
        throw c.mappingException("Expected 'type' to be string");
    }

    final String type = typeNode.asText();

    final Class<? extends Filter> cls = typeNameMapping.get(type);

    if (cls == null) {
        throw c.mappingException("No such type: " + type);
    }

    // use tree traversing parser to operate on the node (without 'type') again.
    final TreeTraversingParser parser = new TreeTraversingParser(object, p.getCodec());
    return parser.readValueAs(cls);
}
 
Example 5
Source File: ZonedDateTimeDeserializer.java    From mongo-jackson-codec with Apache License 2.0 6 votes vote down vote up
@Override
public ZonedDateTime deserialize(BsonParser bsonParser, DeserializationContext ctxt) throws IOException,
    JsonProcessingException {
    if (bsonParser.getCurrentToken() != JsonToken.VALUE_EMBEDDED_OBJECT ||
        bsonParser.getCurrentBsonType() != BsonConstants.TYPE_DATETIME) {
        throw ctxt.mappingException(Date.class);
    }

    Object obj = bsonParser.getEmbeddedObject();
    if (obj == null) {
        return null;
    }

    Date dt = (Date) obj;
    return Instant.ofEpochMilli(dt.getTime()).atZone(ZoneId.of("UTC"));
}
 
Example 6
Source File: LngLatAltDeserializer.java    From geojson-jackson with Apache License 2.0 6 votes vote down vote up
private double extractDouble(JsonParser jp, DeserializationContext ctxt, boolean optional) throws IOException {
    JsonToken token = jp.nextToken();
    if (token == null) {
        if (optional)
            return Double.NaN;
        else
            throw ctxt.mappingException("Unexpected end-of-input when binding data into LngLatAlt");
    } else {
        switch (token) {
            case END_ARRAY:
                if (optional)
                    return Double.NaN;
                else
                    throw ctxt.mappingException("Unexpected end-of-input when binding data into LngLatAlt");
            case VALUE_NUMBER_FLOAT:
                return jp.getDoubleValue();
            case VALUE_NUMBER_INT:
                return jp.getLongValue();
            case VALUE_STRING:
                return jp.getValueAsDouble();
            default:
                throw ctxt.mappingException(
                        "Unexpected token (" + token.name() + ") when binding data into LngLatAlt");
        }
    }
}
 
Example 7
Source File: InstantDeserializer.java    From mongo-jackson-codec with Apache License 2.0 6 votes vote down vote up
@Override
public Instant deserialize(BsonParser bsonParser, DeserializationContext ctxt) throws IOException,
    JsonProcessingException {
    if (bsonParser.getCurrentToken() != JsonToken.VALUE_EMBEDDED_OBJECT ||
        bsonParser.getCurrentBsonType() != BsonConstants.TYPE_DATETIME) {
        ctxt.mappingException(Date.class);
    }

    Object obj = bsonParser.getEmbeddedObject();
    if (obj == null) {
        return null;
    }

    Date dt = (Date) obj;
    return Instant.ofEpochMilli(dt.getTime());
}
 
Example 8
Source File: JacksonActorRefDeserializer.java    From elasticactors with Apache License 2.0 5 votes vote down vote up
@Override
public ActorRef deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    JsonToken curr = jp.getCurrentToken();
    // Usually should just get string value:
    if (curr == JsonToken.VALUE_STRING) {
        return actorRefFactory.create(jp.getText());
    }
    throw ctxt.mappingException(_valueClass, curr);
}
 
Example 9
Source File: MetricGroupSerialization.java    From heroic with Apache License 2.0 5 votes vote down vote up
@Override
public MetricGroup deserialize(JsonParser p, DeserializationContext c) throws IOException {

    if (p.getCurrentToken() != JsonToken.START_ARRAY) {
        throw c.mappingException("Expected start of array");
    }

    final Long timestamp;

    {
        if (p.nextToken() != JsonToken.VALUE_NUMBER_INT) {
            throw c.mappingException("Expected number (timestamp)");
        }

        timestamp = p.readValueAs(Long.class);
    }

    if (p.nextToken() != JsonToken.START_ARRAY) {
        throw c.mappingException("Expected start of array");
    }

    final ImmutableList.Builder<MetricCollection> groups = ImmutableList.builder();

    while (p.nextToken() == JsonToken.START_OBJECT) {
        groups.add(p.readValueAs(MetricCollection.class));
    }

    if (p.getCurrentToken() != JsonToken.END_ARRAY) {
        throw c.mappingException("Expected end of array");
    }

    return new MetricGroup(timestamp, groups.build());
}
 
Example 10
Source File: Offsets.java    From webanno with Apache License 2.0 5 votes vote down vote up
@Override
public Offsets deserialize(JsonParser aJp, DeserializationContext aCtxt)
    throws IOException
{
    Offsets offsets = new Offsets();

    if (aJp.getCurrentToken() != JsonToken.START_ARRAY) {
        aCtxt.mappingException("Expecting array begin");
    }

    if (aJp.nextToken() == JsonToken.VALUE_NUMBER_INT) {
        offsets.begin = aJp.getIntValue();
    }
    else {
        aCtxt.mappingException("Expecting begin offset as integer");
    }

    if (aJp.nextToken() == JsonToken.VALUE_NUMBER_INT) {
        offsets.end = aJp.getIntValue();
    }
    else {
        aCtxt.mappingException("Expecting end offset as integer");
    }

    if (aJp.getCurrentToken() != JsonToken.END_ARRAY) {
        aCtxt.mappingException("Expecting array end");
    }

    return offsets;
}
 
Example 11
Source File: CustomDateTimeDeserializer.java    From ServiceCutter with Apache License 2.0 5 votes vote down vote up
@Override
public DateTime deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException {
    JsonToken t = jp.getCurrentToken();
    if (t == JsonToken.VALUE_STRING) {
        String str = jp.getText().trim();
        return ISODateTimeFormat.dateTimeParser().parseDateTime(str);
    }
    if (t == JsonToken.VALUE_NUMBER_INT) {
        return new DateTime(jp.getLongValue());
    }
    throw ctxt.mappingException(handledType());
}
 
Example 12
Source File: ISO8601LocalDateDeserializer.java    From ServiceCutter with Apache License 2.0 5 votes vote down vote up
@Override
public LocalDate deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException {
    JsonToken t = jp.getCurrentToken();
    if (t == JsonToken.VALUE_STRING) {
        String str = jp.getText().trim();
        return ISODateTimeFormat.dateTimeParser().parseDateTime(str).toLocalDate();
    }
    if (t == JsonToken.VALUE_NUMBER_INT) {
        return new LocalDate(jp.getLongValue());
    }
    throw ctxt.mappingException(handledType());
}
 
Example 13
Source File: Log4jStackTraceElementDeserializer.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public StackTraceElement deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException,
        JsonProcessingException {
    JsonToken t = jp.getCurrentToken();
    // Must get an Object
    if (t == JsonToken.START_OBJECT) {
        String className = null, methodName = null, fileName = null;
        int lineNumber = -1;

        while ((t = jp.nextValue()) != JsonToken.END_OBJECT) {
            final String propName = jp.getCurrentName();
            if ("class".equals(propName)) {
                className = jp.getText();
            } else if ("file".equals(propName)) {
                fileName = jp.getText();
            } else if ("line".equals(propName)) {
                if (t.isNumeric()) {
                    lineNumber = jp.getIntValue();
                } else {
                    // An XML number always comes in a string since there is no syntax help as with JSON.
                    try {
                        lineNumber = Integer.parseInt(jp.getText().trim());
                    } catch (final NumberFormatException e) {
                        throw JsonMappingException.from(jp, "Non-numeric token (" + t + ") for property 'line'", e);
                    }
                }
            } else if ("method".equals(propName)) {
                methodName = jp.getText();
            } else if ("nativeMethod".equals(propName)) {
                // no setter, not passed via constructor: ignore
            } else {
                this.handleUnknownProperty(jp, ctxt, this._valueClass, propName);
            }
        }
        return new StackTraceElement(className, methodName, fileName, lineNumber);
    }
    throw ctxt.mappingException(this._valueClass, t);
}
 
Example 14
Source File: FilterRegistry.java    From heroic with Apache License 2.0 5 votes vote down vote up
@Override
public Filter deserialize(JsonParser p, DeserializationContext c) throws IOException {
    if (p.getCurrentToken() == JsonToken.START_ARRAY) {
        return deserializeArray(p, c);
    }

    if (p.getCurrentToken() == JsonToken.START_OBJECT) {
        return deserializeObject(p, c);
    }

    throw c.mappingException("Expected start of array or object");
}
 
Example 15
Source File: JacksonScheduledMessageRefDeserializer.java    From elasticactors with Apache License 2.0 5 votes vote down vote up
@Override
public ScheduledMessageRef deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    JsonToken curr = jp.getCurrentToken();
    // Usually should just get string value:
    if (curr == JsonToken.VALUE_STRING) {
        return scheduledMessageRefFactory.create(jp.getText());
    }
    throw ctxt.mappingException(_valueClass, curr);
}
 
Example 16
Source File: JSONBindingFactory.java    From cougar with Apache License 2.0 5 votes vote down vote up
@Override
protected Byte _parseByte(JsonParser jp, DeserializationContext ctxt) throws IOException {
    JsonToken t = jp.getCurrentToken();
    Integer value = null;
    if (t == JsonToken.VALUE_NUMBER_INT || t == JsonToken.VALUE_NUMBER_FLOAT) { // coercing should work too
        value = jp.getIntValue();
    }
    else if (t == JsonToken.VALUE_STRING) { // let's do implicit re-parse
        String text = jp.getText().trim();
        try {
            int len = text.length();
            if (len == 0) {
                return getEmptyValue();
            }
            value = NumberInput.parseInt(text);
        } catch (IllegalArgumentException iae) {
            throw ctxt.weirdStringException(_valueClass, "not a valid Byte value");//NOSONAR
        }
    }
    if (value != null) {
        // So far so good: but does it fit?
        if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) {
            throw ctxt.weirdStringException(_valueClass, "overflow, value can not be represented as 8-bit value");
        }
        return (byte) (int) value;
    }
    if (t == JsonToken.VALUE_NULL) {
        return getNullValue();
    }
    throw ctxt.mappingException(_valueClass, t);
}
 
Example 17
Source File: JacksonIssue429MyNamesTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public StackTraceElement deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException,
        JsonProcessingException {
    JsonToken t = jp.getCurrentToken();
    // Must get an Object
    if (t == JsonToken.START_OBJECT) {
        String className = Strings.EMPTY, methodName = Strings.EMPTY, fileName = Strings.EMPTY;
        int lineNumber = -1;

        while ((t = jp.nextValue()) != JsonToken.END_OBJECT) {
            final String propName = jp.getCurrentName();
            if ("class".equals(propName)) {
                className = jp.getText();
            } else if ("file".equals(propName)) {
                fileName = jp.getText();
            } else if ("line".equals(propName)) {
                if (t.isNumeric()) {
                    lineNumber = jp.getIntValue();
                } else {
                    throw JsonMappingException.from(jp, "Non-numeric token (" + t
                            + ") for property 'lineNumber'");
                }
            } else if ("method".equals(propName)) {
                methodName = jp.getText();
            } else if ("nativeMethod".equals(propName)) {
                // no setter, not passed via constructor: ignore
            } else {
                handleUnknownProperty(jp, ctxt, _valueClass, propName);
            }
        }
        return new StackTraceElement(className, methodName, fileName, lineNumber);
    }
    throw ctxt.mappingException(_valueClass, t);
}
 
Example 18
Source File: FunktionDeserializer.java    From funktion-connectors with Apache License 2.0 5 votes vote down vote up
@Override
public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    ObjectNode node = jp.readValueAsTree();
    JsonNode kind = node.get("kind");
    if (kind == null) {
        throw new JsonParseException(jp, "No `kind` property!");
    }

    Class kindClass = kinds.get(kind.asText());
    if (kindClass == null) {
        throw ctxt.mappingException("Unknown kind: " + kind);
    } else {
        return (Step) jp.getCodec().treeToValue(node, kindClass);
    }
}
 
Example 19
Source File: DataBinderDeserializer.java    From gvnix with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Deserializes JSON property into Map<String, String> format to use it in a
 * Spring {@link DataBinder}.
 * <p/>
 * Check token's type to perform an action:
 * <ul>
 * <li>If it's a property, stores it in map</li>
 * <li>If it's an object, calls to
 * {@link #readObject(JsonParser, DeserializationContext, String)}</li>
 * <li>If it's an array, calls to
 * {@link #readArray(JsonParser, DeserializationContext, String)}</li>
 * </ul>
 * 
 * @param parser
 * @param ctxt
 * @param token current token
 * @param prefix property dataBinder path
 * @return
 * @throws IOException
 * @throws JsonProcessingException
 */
protected Map<String, String> readField(JsonParser parser,
        DeserializationContext ctxt, JsonToken token, String prefix)
        throws IOException, JsonProcessingException {

    String fieldName = null;
    String fieldValue = null;

    // Read the field name
    fieldName = parser.getCurrentName();

    // If current token contains a field name
    if (!isEmptyString(fieldName)) {

        // Append the prefix if given
        if (isEmptyString(prefix)) {
            fieldName = parser.getCurrentName();
        }
        else {
            fieldName = prefix.concat(parser.getCurrentName());
        }
    }
    // If current token contains mark array or object start markers.
    // Note it cannot be a field value because it will be read below and
    // then the token is advanced to the next
    else {

        // Use the prefix in recursive calls
        if (!isEmptyString(prefix)) {
            fieldName = prefix;
        }
    }

    // If current token has been used to read the field name, advance
    // stream to the next token that contains the field value
    if (token == JsonToken.FIELD_NAME) {
        token = parser.nextToken();
    }

    // Field value
    switch (token) {
    case VALUE_STRING:
    case VALUE_NUMBER_INT:
    case VALUE_NUMBER_FLOAT:
    case VALUE_EMBEDDED_OBJECT:
    case VALUE_TRUE:
    case VALUE_FALSE:
        // Plain field: Store value
        Map<String, String> field = new HashMap<String, String>();
        fieldValue = parser.getText();
        field.put(fieldName, fieldValue);
        return field;
    case START_ARRAY:
        // Read array items
        return readArray(parser, ctxt, fieldName);
    case START_OBJECT:
        // Read object properties
        return readObject(parser, ctxt, fieldName);
    case END_ARRAY:
    case END_OBJECT:
        // Skip array and object end markers
        parser.nextToken();
        break;
    default:
        throw ctxt.mappingException(getBeanClass());
    }
    return Collections.emptyMap();
}
 
Example 20
Source File: SpreadSerialization.java    From heroic with Apache License 2.0 4 votes vote down vote up
@Override
public Spread deserialize(JsonParser p, DeserializationContext c)
    throws IOException, JsonProcessingException {

    if (p.getCurrentToken() != JsonToken.START_ARRAY) {
        throw c.mappingException(
            String.format("Expected start of array, not %s", p.getCurrentToken()));
    }

    final long timestamp;

    {
        if (!p.nextToken().isNumeric()) {
            throw c.mappingException(
                String.format("Expected timestamp (number), not %s", p.getCurrentToken()));
        }

        timestamp = p.getLongValue();
    }

    if (p.nextToken() != JsonToken.START_OBJECT) {
        throw c.mappingException("Expected start of object");
    }

    long count = 0;
    double sum = Double.NaN;
    double sumx2 = Double.NaN;
    double min = Double.NaN;
    double max = Double.NaN;

    while (p.nextToken() == JsonToken.FIELD_NAME) {
        final String name = p.getCurrentName();

        if (name == null) {
            throw c.mappingException("Expected field name");
        }

        if (COUNT.equals(name)) {
            count = nextLong(p, c);
            continue;
        }

        if (MIN.equals(name)) {
            min = nextDouble(p, c);
            continue;
        }

        if (MAX.equals(name)) {
            max = nextDouble(p, c);
            continue;
        }

        if (SUM.equals(name)) {
            sum = nextDouble(p, c);
            continue;
        }

        if (SUM2.equals(name)) {
            sumx2 = nextDouble(p, c);
            continue;
        }
    }

    if (p.getCurrentToken() != JsonToken.END_OBJECT) {
        throw c.mappingException(
            String.format("Expected end of object, not %s", p.getCurrentToken()));
    }

    if (p.nextToken() != JsonToken.END_ARRAY) {
        throw c.mappingException(
            String.format("Expected end of array, not %s", p.getCurrentToken()));
    }

    return new Spread(timestamp, count, sum, sumx2, min, max);
}