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

The following examples show how to use com.fasterxml.jackson.databind.DeserializationContext#handleUnexpectedToken() . 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: UriDeserializer.java    From Partner-Center-Java with MIT License 6 votes vote down vote up
@Override
public URI deserialize(JsonParser parser, DeserializationContext context)
		throws IOException, JsonProcessingException
{
	JsonToken currentToken = parser.getCurrentToken();
	if (currentToken.equals(JsonToken.VALUE_STRING))
	{
		String linkUri = parser.getText().trim();

        try
        {
			return new URI (linkUri);
		}
        catch (URISyntaxException e)
        {
			PartnerLog.getInstance().logError(e.toString());
		}
	}
	else if(currentToken.equals(JsonToken.VALUE_NULL))
	{
		return null;
	}
	
	context.handleUnexpectedToken(URI.class, parser); 
	throw JsonMappingException.from(parser, null);
}
 
Example 2
Source File: TimestampDeserializer.java    From act-platform with ISC License 6 votes vote down vote up
@Override
public Long deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
  // Input is already a long, just return value directly.
  if (p.hasToken(JsonToken.VALUE_NUMBER_INT)) {
    return p.getLongValue();
  }

  // Try to convert input to an Instant, else throw an InvalidFormatException.
  if (p.hasToken(JsonToken.VALUE_STRING)) {
    try {
      return Instant.parse(p.getText()).toEpochMilli();
    } catch (DateTimeParseException ignored) {
      return (Long) ctxt.handleWeirdStringValue(Long.class, p.getText(), "Cannot convert to valid Instant timestamp");
    }
  }

  // Cannot handle input, throw a MismatchedInputException.
  return (Long) ctxt.handleUnexpectedToken(Long.class, p);
}
 
Example 3
Source File: FilterHintListJsonDeserializer.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@Override
public FilterHint deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    if (!jp.getCurrentToken().isStructStart()) {
        ctxt.handleUnexpectedToken(RpcHint.class, jp);
    }
    // skip json start
    final JsonToken jsonToken = jp.nextToken();
    if (jsonToken == JsonToken.END_OBJECT) {
        return new FilterHint(Collections.emptyList());
    }


    List<RpcHint> rpcHintList = new ArrayList<>();
    while (true) {
        final RpcHint rpcHint = jp.readValueAs(RpcHint.class);
        rpcHintList.add(rpcHint);
        if (jp.nextToken() == JsonToken.END_OBJECT) {
            break;
        }
    }
    return new FilterHint(rpcHintList);
}
 
Example 4
Source File: FooJsonComponent.java    From spring-test-examples with Apache License 2.0 6 votes vote down vote up
@Override
public Foo deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
  JsonToken t = p.getCurrentToken();

  if (t == JsonToken.VALUE_STRING) {
    String trim = p.getText().trim();

    String[] split = trim.split(",");
    Foo foo = new Foo();
    foo.setName(split[0].split("=")[1]);
    foo.setAge(Integer.parseInt(split[1].split("=")[1]));
    return foo;
  }

  return (Foo) ctxt.handleUnexpectedToken(handledType(), p);

}
 
Example 5
Source File: RpcHintJsonDeserializer.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@Override
public RpcHint deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    final String applicationName = jp.getText();

    if (jp.nextToken() != JsonToken.START_ARRAY) {
        ctxt.handleUnexpectedToken(RpcHint.class, jp);
    }
    // skip start array
    final JsonToken token = jp.nextToken();
    // [] empty array
    if (token == JsonToken.END_ARRAY) {
        return new RpcHint(applicationName, Collections.emptyList());
    }
    final List<RpcType> rpcHintList = new ArrayList<>();
    while (true) {
        RpcType rpcType =  jp.readValueAs(RpcType.class);
        rpcHintList.add(rpcType);
        if (jp.nextToken() == JsonToken.END_ARRAY) {
            break;
        }
    }
    return new RpcHint(applicationName, rpcHintList);
}
 
Example 6
Source File: NioPathDeserializer.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Path deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    if (!p.hasToken(JsonToken.VALUE_STRING)) {
        return (Path) ctxt.handleUnexpectedToken(Path.class, p);
    }
    final String value = p.getText();
    // If someone gives us an input with no : at all, treat as local path, instead of failing
    // with invalid URI.
    if (value.indexOf(':') < 0) {
        return Paths.get(value);
    }
    try {
        URI uri = new URI(value);
        return Paths.get(uri);
    } catch (URISyntaxException e) {
        return (Path) ctxt.handleInstantiationProblem(handledType(), value, e);
    }
}
 
Example 7
Source File: ECKeyDeserializer.java    From consensusj with Apache License 2.0 5 votes vote down vote up
@Override
public ECKey deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    JsonToken token = p.getCurrentToken();
    switch (token) {
        case VALUE_STRING:
            try {
                return DumpedPrivateKey.fromBase58(null, p.getValueAsString()).getKey();
            } catch (AddressFormatException e) {
                throw new InvalidFormatException(p, "Invalid Key", p.getValueAsString(), ECKey.class);
            }
        default:
            return (ECKey) ctxt.handleUnexpectedToken(ECKey.class, p);
    }
}
 
Example 8
Source File: BaseCollectionDeserializer.java    From jackson-datatypes-collections with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public T deserialize(JsonParser p, DeserializationContext ctxt)
        throws IOException {
    // Should usually point to START_ARRAY
    if (p.isExpectedStartArrayToken()) {
        return _deserializeContents(p, ctxt);
    }
    // But may support implicit arrays from single values?
    if (ctxt.isEnabled(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)) {
        return _deserializeFromSingleValue(p, ctxt);
    }
    return (T) ctxt.handleUnexpectedToken(getValueType(ctxt), p);
}
 
Example 9
Source File: BlockHexDeserializer.java    From consensusj with Apache License 2.0 5 votes vote down vote up
@Override
public Block deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    JsonToken token = p.getCurrentToken();
    switch (token) {
        case VALUE_STRING:
            try {
                byte[] payload = HexUtil.hexStringToByteArray(p.getValueAsString()); // convert  to hex
                return context.getParams().getDefaultSerializer().makeBlock(payload);
            } catch (ProtocolException e) {
                throw new InvalidFormatException(p, "Invalid Block", p.getValueAsString(), Block.class);
            }
        default:
            return (Block) ctxt.handleUnexpectedToken(Block.class, p);
    }
}
 
Example 10
Source File: BaseCollectionDeserializer.java    From jackson-datatypes-collections with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public T deserialize(JsonParser p, DeserializationContext ctxt)
        throws IOException {
    // Should usually point to START_ARRAY
    if (p.isExpectedStartArrayToken()) {
        return _deserializeContents(p, ctxt);
    }
    // But may support implicit arrays from single values?
    if (ctxt.isEnabled(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)) {
        return _deserializeFromSingleValue(p, ctxt);
    }
    return (T) ctxt.handleUnexpectedToken(getValueType(ctxt), p);
}
 
Example 11
Source File: CustomCollectionDeserializer.java    From caravan with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method called when current token is no START_ARRAY. Will either
 * throw an exception, or try to handle value as if member of implicit
 * array, depending on configuration.
 */
@SuppressWarnings("unchecked")
protected final Collection<Object> handleNonArray(JsonParser p, DeserializationContext ctxt,
    Collection<Object> result)
    throws IOException {
  // Implicit arrays from single values?
  boolean canWrap = (_unwrapSingle == Boolean.TRUE) ||
      ((_unwrapSingle == null) &&
          ctxt.isEnabled(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY));
  if (!canWrap) {
    return (Collection<Object>) ctxt.handleUnexpectedToken(_containerType.getRawClass(), p);
  }
  JsonDeserializer<Object> valueDes = _valueDeserializer;
  final TypeDeserializer typeDeser = _valueTypeDeserializer;
  JsonToken t = p.getCurrentToken();

  Object value;

  try {
    if (t == JsonToken.VALUE_NULL) {
      // 03-Feb-2017, tatu: Hmmh. I wonder... let's try skipping here, too
      if (_skipNullValues) {
        return result;
      }
      value = _nullProvider.getNullValue(ctxt);
    } else if (typeDeser == null) {
      value = valueDes.deserialize(p, ctxt);
    } else {
      value = valueDes.deserializeWithType(p, ctxt, typeDeser);
    }
  } catch (Exception e) {
    // note: pass Object.class, not Object[].class, as we need element type for error info
    throw JsonMappingException.wrapWithPath(e, Object.class, result.size());
  }
  result.add(value);
  return result;
}
 
Example 12
Source File: UntypedObjectDeserializer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object deserializeWithType(JsonParser p, DeserializationContext ctxt, TypeDeserializer typeDeserializer) throws IOException
{
    switch (p.getCurrentTokenId()) {
    case JsonTokenId.ID_START_ARRAY:
    case JsonTokenId.ID_START_OBJECT:
    case JsonTokenId.ID_FIELD_NAME:
        return typeDeserializer.deserializeTypedFromAny(p, ctxt);

    case JsonTokenId.ID_STRING:
        return p.getText();

    case JsonTokenId.ID_NUMBER_INT:
        if (ctxt.isEnabled(DeserializationFeature.USE_BIG_INTEGER_FOR_INTS)) {
            return p.getBigIntegerValue();
        }
        return p.getNumberValue();

    case JsonTokenId.ID_NUMBER_FLOAT:
        if (ctxt.isEnabled(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)) {
            return p.getDecimalValue();
        }
        return p.getNumberValue();

    case JsonTokenId.ID_TRUE:
        return Boolean.TRUE;
    case JsonTokenId.ID_FALSE:
        return Boolean.FALSE;
    case JsonTokenId.ID_EMBEDDED_OBJECT:
        return p.getEmbeddedObject();

    case JsonTokenId.ID_NULL: // should not get this far really but...
        return null;
    default:
    }
    return ctxt.handleUnexpectedToken(Object.class, p);
}
 
Example 13
Source File: AddressDeserializer.java    From consensusj with Apache License 2.0 5 votes vote down vote up
@Override
public Address deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    JsonToken token = p.getCurrentToken();
    switch (token) {
        case VALUE_STRING:
            try {
                return Address.fromString(netParams, p.getValueAsString());
            } catch (AddressFormatException e) {
                throw new InvalidFormatException(p, "Invalid Address", p.getValueAsString(), Address.class);
            }
        default:
            return (Address) ctxt.handleUnexpectedToken(Address.class, p);
    }
}
 
Example 14
Source File: RoundingFloatDeserializer.java    From act-platform with ISC License 5 votes vote down vote up
@Override
public Float deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
  if (p.hasToken(JsonToken.VALUE_NUMBER_FLOAT)) {
    return BigDecimal.valueOf(p.getFloatValue())
            .setScale(DECIMAL_POINTS, RoundingMode.HALF_UP)
            .floatValue();
  }

  // Cannot handle input, throw a MismatchedInputException.
  return (Float) ctxt.handleUnexpectedToken(Float.class, p);
}
 
Example 15
Source File: SCPParametersDeserializer.java    From openjavacard-tools with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public SCPParameters deserialize(JsonParser p, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    if (p.hasToken(JsonToken.VALUE_STRING)) {
        return SCPParameters.fromString(p.getText());
    }
    return (SCPParameters) ctxt.handleUnexpectedToken(_valueClass, p);
}
 
Example 16
Source File: HexBytesDeserializer.java    From openjavacard-tools with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public byte[] deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    if (p.hasToken(JsonToken.VALUE_STRING)) {
        return HexUtil.hexToBytes(p.getText());
    }
    return (byte[]) ctxt.handleUnexpectedToken(_valueClass, p);
}
 
Example 17
Source File: AIDDeserializer.java    From openjavacard-tools with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public AID deserialize(JsonParser p, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    if (p.hasToken(JsonToken.VALUE_STRING)) {
        return new AID(p.getText());
    }
    return (AID) ctxt.handleUnexpectedToken(_valueClass, p);
}
 
Example 18
Source File: BaseCollectionDeserializer.java    From jackson-datatypes-collections with Apache License 2.0 4 votes vote down vote up
@Override
public T deserialize(JsonParser p, DeserializationContext ctxt)
        throws IOException {
    Intermediate intermediate = createIntermediate();

    if (p.isExpectedStartArrayToken()) {
        JsonToken t;
        while ((t = p.nextToken()) != JsonToken.END_ARRAY) {
            String str;
            if (t == JsonToken.VALUE_STRING) {
                str = p.getText();
            } else {
                CharSequence cs = (CharSequence) ctxt.handleUnexpectedToken(getValueType(ctxt), p);
                str = cs.toString();
            }
            if (str.length() != 1) {
                ctxt.reportInputMismatch(this,
                                         "Cannot convert a JSON String of length %d into a char element of " +
                                         "char array",
                                         str.length());
            }
            intermediate.add(str.charAt(0));
        }
        return finish(intermediate);
    }

    char[] chars = p.getTextCharacters();
    if (p.getTextOffset() == 0 && p.getTextLength() == chars.length) {
        intermediate.addAll(chars);
    } else {
        int i = 0;
        // first, copy in batches of BATCH_COPY_SIZE
        if ((p.getTextLength() - i) >= BATCH_COPY_SIZE) {
            char[] buf = new char[BATCH_COPY_SIZE];
            do {
                System.arraycopy(chars, p.getTextOffset() + i, buf, 0, BATCH_COPY_SIZE);
                intermediate.addAll(buf);
                i += BATCH_COPY_SIZE;
            } while ((p.getTextLength() - i) >= BATCH_COPY_SIZE);
        }
        // and finally, copy the remainder.
        if (p.getTextLength() > i) {
            char[] tail = Arrays.copyOfRange(
                    chars, p.getTextOffset() + i, p.getTextOffset() + p.getTextLength());
            intermediate.addAll(tail);
        }
    }
    return finish(intermediate);
}
 
Example 19
Source File: AbstractJobParametersDeserializer.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Nonnull
protected JsonNode createJsonNode( @Nonnull JsonParser p, @Nonnull DeserializationContext ctxt ) throws IOException
{
    JsonToken t = p.getCurrentToken();

    if ( t == null )
    {
        t = p.nextToken();

        if ( t == null )
        {
            ctxt.handleUnexpectedToken( _valueClass, p );
        }
    }

    if ( t != JsonToken.START_OBJECT )
    {
        ctxt.handleUnexpectedToken( _valueClass, p );
    }

    t = p.nextToken();

    ObjectNode result = JsonNodeFactory.instance.objectNode();

    do
    {
        if ( t != JsonToken.FIELD_NAME )
        {
            ctxt.handleUnexpectedToken( _valueClass, p );
        }

        final String fieldName = p.getValueAsString();

        t = p.nextToken();

        if ( t == JsonToken.VALUE_STRING )
        {
            if ( arrayFieldNames.contains( fieldName ) )
            {
                result.set( fieldName, JsonNodeFactory.instance.arrayNode() );
            }
            else
            {
                result.put( fieldName, p.getValueAsString() );
            }
        }
        else if ( t == JsonToken.START_OBJECT )
        {
            result.set( fieldName, createArrayNode( p, ctxt ) );
        }
        else
        {
            ctxt.handleUnexpectedToken( _valueClass, p );
        }

        t = p.nextToken();
    }
    while ( t != null && t != JsonToken.END_OBJECT );

    return result;
}
 
Example 20
Source File: IterableXDeserializer.java    From cyclops with Apache License 2.0 4 votes vote down vote up
@Override
public IterableX<?> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {


    if (!p.isExpectedStartArrayToken()) {
        return (IterableX)ctxt.handleUnexpectedToken(handledType(),p);
    }

  List multi = new ArrayList();

    JsonToken t;
    while ((t = p.nextToken()) != JsonToken.END_ARRAY) {
        Object value;

        if (t == JsonToken.VALUE_NULL) {
            value = null;
        } else if (typeDeserializerForValue == null) {
            value = valueDeserializer.deserialize(p, ctxt);
        } else {
            value = valueDeserializer.deserializeWithType(p, ctxt, typeDeserializerForValue);
        }
        multi.add(value);
    }

  if(Vector.class.isAssignableFrom(elementType))
    return Vector.fromIterable(multi);

  if(Seq.class.isAssignableFrom(elementType))
    return Seq.fromIterable(multi);
  if(LazySeq.class.isAssignableFrom(elementType))
    return LazySeq.fromIterable(multi);
  if(LazyString.class.isAssignableFrom(elementType))
    return LazyString.fromLazySeq((LazySeq)LazySeq.fromIterable(multi));
  if(IntMap.class.isAssignableFrom(elementType))
    return IntMap.fromIterable(multi);
  if(ReactiveSeq.class.isAssignableFrom(elementType))
    return ReactiveSeq.fromIterable(multi);
  if(Streamable.class.isAssignableFrom(elementType))
    return Streamable.fromIterable(multi);
  if(BankersQueue.class.isAssignableFrom(elementType))
    return BankersQueue.fromIterable(multi);
  if(Bag.class.isAssignableFrom(elementType))
    return Bag.fromIterable(multi);
  if(cyclops.data.HashSet.class.isAssignableFrom(elementType))
    return HashSet.fromIterable(multi);
  if(cyclops.data.TrieSet.class.isAssignableFrom(elementType))
    return TrieSet.fromIterable(multi);
  if(cyclops.data.TreeSet.class.isAssignableFrom(elementType))
    return TreeSet.fromIterable(multi,(Comparator)Comparator.naturalOrder());

  Optional<Method> m = streamMethod.computeIfAbsent(elementType, c->Stream.of(c.getMethods())
                                                                    .filter(method -> "fromIterable".equals(method.getName()))
                                                                    .filter(method -> method.getParameterCount()==1)
                                                                      .findFirst()
                                                                    .map(m2->{ m2.setAccessible(true); return m2;}));
  IterableX x = m.map(mt -> (IterableX) new Invoker().executeMethod(multi, mt, itX)).orElse(null);

  return x;

}