Java Code Examples for com.fasterxml.jackson.core.JsonParser

The following are top voted examples for showing how to use com.fasterxml.jackson.core.JsonParser. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: GitHub   File: JacksonConverterFactoryTest.java   View source code 6 votes vote down vote up
@Override public AnInterface deserialize(JsonParser jp, DeserializationContext ctxt)
    throws IOException {
  if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
    throw new AssertionError("Expected start object.");
  }

  String name = null;

  while (jp.nextToken() != JsonToken.END_OBJECT) {
    switch (jp.getCurrentName()) {
      case "name":
        name = jp.getValueAsString();
        break;
    }
  }

  return new AnImplementation(name);
}
 
Example 2
Project: swblocks-decisiontree   File: JsonJacksonParser.java   View source code 6 votes vote down vote up
private void parseInputArrayOfStrings(final JsonParser parser,
                                      final List<String> inputs,
                                      final DriverCache cache,
                                      final Set<ValueGroup> groups) {
    EhSupport.propagate(() -> {
        parser.nextToken();
        while (parser.nextToken() != JsonToken.END_ARRAY) {
            String value = parser.getText();
            if (value.startsWith(GroupDriver.VG_PREFIX) && !cache.contains(value)) {
                final String groupName = value.split(":")[1];
                final Optional<ValueGroup> group =
                        groups.stream().filter(valueGroup -> valueGroup.getName().equals(groupName)).findFirst();
                if (group.isPresent()) {
                    value = GroupDriver.VG_PREFIX + group.get().getId();
                } else {
                    inputs.add(value);
                }
            }
            inputs.add(value);
        }
    });
}
 
Example 3
Project: GitHub   File: TestParserOverrides.java   View source code 6 votes vote down vote up
public void _testTokenAccess(JsonFactory jf, boolean useStream) throws Exception
{
    final String DOC = "[ ]";
    JsonParser jp = useStream ?
            jf.createParser(ObjectReadContext.empty(), new ByteArrayInputStream(DOC.getBytes("UTF-8")))
            : jf.createParser(ObjectReadContext.empty(), DOC);
    assertNull(jp.currentToken());
    jp.clearCurrentToken();
    assertNull(jp.currentToken());
    assertNull(jp.getEmbeddedObject());
    assertToken(JsonToken.START_ARRAY, jp.nextToken());
    assertToken(JsonToken.START_ARRAY, jp.currentToken());
    jp.clearCurrentToken();
    assertNull(jp.currentToken());
    // Also: no codec defined by default
    try {
        jp.readValueAsTree();
        fail("Should get exception without codec");
    } catch (UnsupportedOperationException e) {
        verifyException(e, "Operation not supported");
    }
    jp.close();
}
 
Example 4
Project: wamp2spring   File: RegisterMessage.java   View source code 6 votes vote down vote up
public static RegisterMessage deserialize(JsonParser jp) throws IOException {
	jp.nextToken();
	long request = jp.getLongValue();

	boolean discloseCaller = false;
	jp.nextToken();
	Map<String, Object> options = ParserUtil.readObject(jp);
	if (options != null) {
		discloseCaller = (boolean) options.getOrDefault("disclose_caller", false);
	}

	jp.nextToken();
	String procedure = jp.getValueAsString();

	return new RegisterMessage(request, procedure, discloseCaller);
}
 
Example 5
Project: GitHub   File: JsonParserSequenceTest.java   View source code 6 votes vote down vote up
@Test
public void testSkipChildren() throws IOException {
    JsonParser[] jsonParserArray = new JsonParser[3];
    IOContext ioContext = new IOContext(new BufferRecycler(), jsonParserArray, true);
    byte[] byteArray = new byte[8];
    InputStream byteArrayInputStream = new ByteArrayInputStream(byteArray, 0, (byte) 58);
    UTF8StreamJsonParser uTF8StreamJsonParser = new UTF8StreamJsonParser(ObjectReadContext.empty(),
            ioContext,
            0, byteArrayInputStream, ByteQuadsCanonicalizer.createRoot(),
            byteArray, -1, (byte) 9, true);
    JsonParserDelegate jsonParserDelegate = new JsonParserDelegate(jsonParserArray[0]);
    JsonParserSequence jsonParserSequence = JsonParserSequence.createFlattened(true, uTF8StreamJsonParser, jsonParserDelegate);
    JsonParserSequence jsonParserSequenceTwo = (JsonParserSequence) jsonParserSequence.skipChildren();

    assertEquals(2, jsonParserSequenceTwo.containedParsersCount());
}
 
Example 6
Project: dbsync   File: JSonStringConverter.java   View source code 6 votes vote down vote up
@Override
public Value jsonToColumnValue(JsonParser parser, ValueMetadata metadata) throws IOException {
    JsonToken token;
    Value value;

    // Go to the next token
    token = parser.nextToken();

    if (token != JsonToken.VALUE_STRING && token != JsonToken.VALUE_NULL) {
        throw new IOException("Unable to parse field " + metadata.getName() + " expected string or null at line " + parser.getCurrentLocation().getLineNr());
    }

    // Can be a integer or null
    if (token == JsonToken.VALUE_STRING) {
        value = new Value(parser.getValueAsString(), metadata);
    } else {
        // null
        if (metadata.isNotNull()) {
            throw new IOException("Unable to parse field " + metadata.getName() + " expected string but found null at line " + parser.getCurrentLocation().getLineNr());
        }

        value = new Value(metadata);
    }

    return value;
}
 
Example 7
Project: lams   File: Jackson2ObjectMapperFactoryBean.java   View source code 6 votes vote down vote up
private void configureFeature(Object feature, boolean enabled) {
	if (feature instanceof JsonParser.Feature) {
		this.objectMapper.configure((JsonParser.Feature) feature, enabled);
	}
	else if (feature instanceof JsonGenerator.Feature) {
		this.objectMapper.configure((JsonGenerator.Feature) feature, enabled);
	}
	else if (feature instanceof SerializationFeature) {
		this.objectMapper.configure((SerializationFeature) feature, enabled);
	}
	else if (feature instanceof DeserializationFeature) {
		this.objectMapper.configure((DeserializationFeature) feature, enabled);
	}
	else if (feature instanceof MapperFeature) {
		this.objectMapper.configure((MapperFeature) feature, enabled);
	}
	else {
		throw new FatalBeanException("Unknown feature class: " + feature.getClass().getName());
	}
}
 
Example 8
Project: jigsaw-payment   File: JsonJacksonFormat.java   View source code 6 votes vote down vote up
/**
 * Parse a text-format message from {@code input} and merge the contents into {@code builder}.
 * Extensions will be recognized if they are registered in {@code extensionRegistry}.
 * @throws IOException
 */
public void merge(JsonParser parser,
						 ExtensionRegistry extensionRegistry,
                         Message.Builder builder) throws IOException {

    JsonToken token = parser.nextToken();
    if (token.equals(JsonToken.START_OBJECT)) {
    	token = parser.nextToken();
    }
    while (token != null && !token.equals(JsonToken.END_OBJECT)) {
    	mergeField(parser, extensionRegistry, builder);
    	token = parser.nextToken();
    }

    // Test to make sure the tokenizer has reached the end of the stream.
    if (parser.nextToken() != null) {
        throw new RuntimeException("Expecting the end of the stream, but there seems to be more data!  Check the input for a valid JSON format.");
    }
}
 
Example 9
Project: GitHub   File: NonPrivateFieldsAndAccessorsFieldDetectionPolicyModel$$JsonObjectMapper.java   View source code 6 votes vote down vote up
@Override
public NonPrivateFieldsAndAccessorsFieldDetectionPolicyModel parse(JsonParser jsonParser) throws IOException {
    NonPrivateFieldsAndAccessorsFieldDetectionPolicyModel instance = new NonPrivateFieldsAndAccessorsFieldDetectionPolicyModel();
    if (jsonParser.getCurrentToken() == null) {
        jsonParser.nextToken();
    }
    if (jsonParser.getCurrentToken() != JsonToken.START_OBJECT) {
        jsonParser.skipChildren();
        return null;
    }
    while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
        String fieldName = jsonParser.getCurrentName();
        jsonParser.nextToken();
        parseField(instance, fieldName, jsonParser);
        jsonParser.skipChildren();
    }
    return instance;
}
 
Example 10
Project: GitHub   File: ParentModel$$JsonObjectMapper.java   View source code 6 votes vote down vote up
@Override
public ParentModel parse(JsonParser jsonParser) throws IOException {
    ParentModel instance = new ParentModel();
    if (jsonParser.getCurrentToken() == null) {
        jsonParser.nextToken();
    }
    if (jsonParser.getCurrentToken() != JsonToken.START_OBJECT) {
        jsonParser.skipChildren();
        return null;
    }
    while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
        String fieldName = jsonParser.getCurrentName();
        jsonParser.nextToken();
        parseField(instance, fieldName, jsonParser);
        jsonParser.skipChildren();
    }
    return instance;
}
 
Example 11
Project: QDrill   File: JacksonHelper.java   View source code 6 votes vote down vote up
public static Object getValueFromFieldType(JsonParser parser, MinorType fieldType) throws IOException {
  switch (fieldType) {
    case BIGINT:
      return parser.getLongValue();
    case VARCHAR:
      return parser.getValueAsString();
    case FLOAT4:
      return parser.getFloatValue();
    case BIT:
      return parser.getBooleanValue();
    case LATE:
    case NULL:
      return null;
    default:
      throw new RuntimeException("Unexpected Field type to return value: " + fieldType.toString());
  }
}
 
Example 12
Project: optashift-employee-rostering   File: LocalDateTimeDeserializer.java   View source code 6 votes vote down vote up
@Override
public LocalDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException
{
    if (parser.hasTokenId(JsonTokenId.ID_STRING)) {
        String string = parser.getText().trim();
        if (string.length() == 0) {
            return null;
        }
        
        try {
            return LocalDateTime.parse(string, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
        } catch (DateTimeException e) {
            throw new IOException(e);
        }
    }
    if (parser.hasTokenId(JsonTokenId.ID_EMBEDDED_OBJECT)) {
        return (LocalDateTime) parser.getEmbeddedObject();
    }
    throw context.wrongTokenException(parser, JsonToken.VALUE_STRING, "Expected string.");
}
 
Example 13
Project: GitHub   File: PrivateFieldModel$$JsonObjectMapper.java   View source code 6 votes vote down vote up
@Override
public PrivateFieldModel parse(JsonParser jsonParser) throws IOException {
    PrivateFieldModel instance = new PrivateFieldModel();
    if (jsonParser.getCurrentToken() == null) {
        jsonParser.nextToken();
    }
    if (jsonParser.getCurrentToken() != JsonToken.START_OBJECT) {
        jsonParser.skipChildren();
        return null;
    }
    while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
        String fieldName = jsonParser.getCurrentName();
        jsonParser.nextToken();
        parseField(instance, fieldName, jsonParser);
        jsonParser.skipChildren();
    }
    return instance;
}
 
Example 14
Project: wamp2spring   File: UnsubscribedMessage.java   View source code 6 votes vote down vote up
public static UnsubscribedMessage deserialize(JsonParser jp) throws IOException {
	jp.nextToken();
	long request = jp.getLongValue();

	Long subscriptionId = null;
	String reason = null;

	JsonToken token = jp.nextToken();
	if (token == JsonToken.START_OBJECT) {
		Map<String, Object> details = ParserUtil.readObject(jp);
		reason = (String) details.get("reason");

		Object subscriptionObj = details.get("subscription");
		if (subscriptionObj != null) {
			subscriptionId = ((Number) subscriptionObj).longValue();
		}
	}

	return new UnsubscribedMessage(request, subscriptionId, reason);
}
 
Example 15
Project: nan   File: FDateJsonDeserializer.java   View source code 6 votes vote down vote up
@Override
public Date deserialize(JsonParser gen, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    String date = gen.getText();

    if (StringUtils.isEmpty(date)) {
        return null;
    }

    if (StringUtils.isNumeric(date)) {
        return new Date(Long.valueOf(date));
    }
    try {
        DateTime dt = fmt.parseDateTime(date);
        return dt.toDate();
    } catch (Exception e) {
        throw new IOException(e);
    }
}
 
Example 16
Project: pyplyn   File: RawJsonCollectionDeserializer.java   View source code 6 votes vote down vote up
private Collection<Object> deserializeWithRetry(JsonParser p, DeserializationContext ctxt, JavaType contentType) throws IOException {
    final CollectionType collectionType = ctxt.getTypeFactory().constructCollectionType(Collection.class, contentType);

    try {
        return p.getCodec().readValue(p, collectionType);

    } catch (JsonMappingException e) {
        // attempt to read the value as string
        final String escapedString = p.getValueAsString();

        // stop here if value could not be read
        if (isNull(escapedString)) {
            throw ctxt.instantiationException(Collection.class, "Read null value when attempting to deserialize " + collectionType.toString());
        }

        // un-escape double quotes
        String unescapedString = escapedString.replaceAll("\"", "\"");

        // and attempt to parse again
        return new ObjectMapper().readValue(unescapedString, collectionType);
    }
}
 
Example 17
Project: powsybl-core   File: PostContingencyResultDeserializer.java   View source code 6 votes vote down vote up
@Override
public PostContingencyResult deserialize(JsonParser parser, DeserializationContext deserializationContext) throws IOException {
    Contingency contingency = null;
    LimitViolationsResult limitViolationsResult = null;

    while (parser.nextToken() != JsonToken.END_OBJECT) {
        switch (parser.getCurrentName()) {
            case "contingency":
                parser.nextToken();
                contingency = parser.readValueAs(Contingency.class);
                break;

            case "limitViolationsResult":
                parser.nextToken();
                limitViolationsResult = parser.readValueAs(LimitViolationsResult.class);
                break;

            default:
                throw new AssertionError("Unexpected field: " + parser.getCurrentName());
        }
    }

    return new PostContingencyResult(contingency, limitViolationsResult);
}
 
Example 18
Project: kowalski   File: SolrQueryDeserializer.java   View source code 5 votes vote down vote up
@Override
public SolrQuery deserialize(JsonParser parser, DeserializationContext context)
		throws IOException, JsonProcessingException {
	JsonNode node = parser.getCodec().readTree(parser);
	String serialization = node.get(SERIALIZATION).textValue();
	return SerializationUtils.deserialize(Base64.decodeBase64(serialization.getBytes()));
}
 
Example 19
Project: SugarOnRest   File: CustomDateDeserializer.java   View source code 5 votes vote down vote up
/**
 *  Deserialize date.
 *
 * @param jsonparser
 * @param context
 * @return
 * @throws IOException
 * @throws JsonProcessingException
 */
@Override
public Date deserialize(JsonParser jsonparser, DeserializationContext context)
        throws IOException, JsonProcessingException {

    String date = jsonparser.getText();
    try {
        return formatter.parse(date);
    } catch (Exception e) {
    }

    return null;
}
 
Example 20
Project: echo   File: AppManager.java   View source code 5 votes vote down vote up
public boolean stopDAG() {
	
	ObjectMapper mapper = new ObjectMapper();
       mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
       deployer.stopDag();
       // TODO remove the entry from the RD
       return true;
}
 
Example 21
Project: GitHub   File: DateTypeConverter.java   View source code 5 votes vote down vote up
@Override
public Date parse(JsonParser jsonParser) throws IOException {
    String dateString = jsonParser.getValueAsString(null);
    if (dateString != null) {
        try {
            return mDateFormat.get().parse(dateString);
        } catch (ParseException e) {
            return null;
        }
    } else {
        return null;
    }
}
 
Example 22
Project: ibm-cos-sdk-java   File: SimpleTypeCborUnmarshallers.java   View source code 5 votes vote down vote up
public BigDecimal unmarshall(JsonUnmarshallerContext unmarshallerContext) throws Exception {
    JsonParser parser = unmarshallerContext.getJsonParser();
    Unmarshaller<BigInteger, JsonUnmarshallerContext> bigIntegerUnmarshaller = unmarshallerContext.getUnmarshaller(BigInteger.class);

    JsonToken current = parser.getCurrentToken();
    if (current != JsonToken.START_ARRAY) {
        throw new SdkClientException("Invalid BigDecimal Format.");
    }
    parser.nextToken();
    int exponent = parser.getIntValue();
    parser.nextToken();
    BigInteger mantissa = bigIntegerUnmarshaller.unmarshall(unmarshallerContext);
    return new BigDecimal(mantissa, exponent);
}
 
Example 23
Project: powsybl-core   File: TimeSeriesJsonDeserializer.java   View source code 5 votes vote down vote up
@Override
public TimeSeries deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) {
    List<TimeSeries> timeSeriesList = TimeSeries.parseJson(jsonParser, true);
    if (timeSeriesList.size() != 1) {
        throw new TimeSeriesException("Time series JSON deserialization error");
    }
    return timeSeriesList.get(0);
}
 
Example 24
Project: act-platform   File: AbstractRequestTest.java   View source code 5 votes vote down vote up
@BeforeClass
public static void setUp() {
  // Initialize object mapper for testing.
  mapper = new ObjectMapper();
  // With this configuration we save a lot of quotes and escaping when creating JSON strings.
  mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
  mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
  // Initialize validator for testing including custom mappings.
  validator = Validation.byDefaultProvider()
          .configure()
          .addMapping(AbstractRequestTest.class.getClassLoader().getResourceAsStream(VALIDATION_MAPPINGS))
          .buildValidatorFactory()
          .getValidator();
}
 
Example 25
Project: aws-sdk-java-v2   File: Choice.java   View source code 5 votes vote down vote up
@Override
public Choice.Builder deserialize(JsonParser jsonParser,
                                  DeserializationContext deserializationContext) throws IOException {
    final JsonNode node = jsonParser.getCodec().readTree(jsonParser);
    return Choice.builder()
                 .nextStateName(node.get(PropertyNames.NEXT).asText())
                 .condition(conditionDeserializer.deserializeCondition(node));
}
 
Example 26
Project: OperatieBRP   File: DienstbundelDeserializer.java   View source code 5 votes vote down vote up
@Override
public final Dienstbundel deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException {
    final ObjectCodec oc = jp.getCodec();
    final JsonNode node = oc.readTree(jp);

    final Leveringsautorisatie leveringsautorisatie =
            entityManager.getReference(Leveringsautorisatie.class, JsonUtils.getAsInteger(node, DienstbundelModule.LEVERINGSAUTORISATIE));

    final Dienstbundel dienstbundel = new Dienstbundel(leveringsautorisatie);
    dienstbundel.setLeveringsautorisatie(leveringsautorisatie);
    dienstbundel.setId(JsonUtils.getAsInteger(node, DienstbundelModule.ID));
    dienstbundel.setNaam(JsonUtils.getAsString(node, DienstbundelModule.NAAM));
    dienstbundel.setDatumIngang(JsonUtils.getAsInteger(node, DienstbundelModule.DATUM_INGANG));
    dienstbundel.setDatumEinde(JsonUtils.getAsInteger(node, DienstbundelModule.DATUM_EINDE));
    dienstbundel.setNaderePopulatiebeperking(JsonUtils.getAsString(node, DienstbundelModule.NADERE_POPULATIE_BEPERKING));
    dienstbundel.setIndicatieNaderePopulatiebeperkingVolledigGeconverteerd(
        JsonUtils.getAsBoolean(
            node,
            DienstbundelModule.INDICATIE_NADERE_POPULATIE_BEPERKING_GECONVERTEERD,
            DienstbundelModule.WAARDE_NEE,
            Boolean.FALSE,
            null));
    dienstbundel.setToelichting(JsonUtils.getAsString(node, DienstbundelModule.TOELICHTING));
    dienstbundel.setIndicatieGeblokkeerd(
        JsonUtils.getAsBoolean(node, DienstbundelModule.INDICATIE_GEBLOKKEERD, DienstbundelModule.WAARDE_JA, Boolean.TRUE, null));

    return dienstbundel;
}
 
Example 27
Project: CryptoPayAPI   File: AddressOverviewDeserializer.java   View source code 5 votes vote down vote up
@Override
public AddressOverview deserialize(JsonParser parser, DeserializationContext context)	
		throws IOException, JsonProcessingException {
	List<Object> propertyList = context.readValue(parser, context.getTypeFactory()
			.constructCollectionType(ArrayList.class, Object.class));
	return toAddressOverview(propertyList);
}
 
Example 28
Project: verify-service-provider   File: PrivateKeyDeserializer.java   View source code 5 votes vote down vote up
@Override
public PrivateKey deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException {
    jsonParser.setCodec(OBJECT_MAPPER);
    JsonNode node = jsonParser.getCodec().readTree(jsonParser);

    try {
        return createPrivateKey(Base64.getDecoder().decode(node.asText()));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 29
Project: OperatieBRP   File: LeveringsautorisatieDeserializer.java   View source code 5 votes vote down vote up
@Override
public final Leveringsautorisatie deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException {
    final ObjectCodec oc = jp.getCodec();
    final JsonNode node = oc.readTree(jp);

    final Stelsel stelsel = EnumUtils.getAsEnum(Stelsel.class, JsonUtils.getAsInteger(node, LeveringsautorisatieModule.STELSEL));
    final Boolean indicatieModelautorisatie =
            JsonUtils.getAsBoolean(
                node,
                LeveringsautorisatieModule.INDICATIE_MODEL_AUTORISATIE,
                LeveringsautorisatieModule.WAARDE_JA,
                Boolean.TRUE,
                Boolean.FALSE);
    final Leveringsautorisatie leveringsautorisatie = new Leveringsautorisatie(stelsel, indicatieModelautorisatie);
    leveringsautorisatie.setId(JsonUtils.getAsInteger(node, LeveringsautorisatieModule.ID));
    leveringsautorisatie.setNaam(JsonUtils.getAsString(node, LeveringsautorisatieModule.NAAM));
    leveringsautorisatie.setProtocolleringsniveau(
        EnumUtils.getAsEnum(Protocolleringsniveau.class, JsonUtils.getAsInteger(node, LeveringsautorisatieModule.PROTOCOLLERINGSNIVEAU)));
    leveringsautorisatie.setIndicatieAliasSoortAdministratieveHandelingLeveren(
        JsonUtils.getAsBoolean(
            node,
            LeveringsautorisatieModule.INDICATIE_ALIAS_LEVEREN,
            LeveringsautorisatieModule.WAARDE_JA,
            Boolean.TRUE,
            Boolean.FALSE));
    leveringsautorisatie.setDatumIngang(JsonUtils.getAsInteger(node, LeveringsautorisatieModule.DATUM_INGANG));
    leveringsautorisatie.setDatumEinde(JsonUtils.getAsInteger(node, LeveringsautorisatieModule.DATUM_EINDE));
    leveringsautorisatie.setPopulatiebeperking(JsonUtils.getAsString(node, LeveringsautorisatieModule.POPULATIE_BEPERKING));
    leveringsautorisatie.setToelichting(JsonUtils.getAsString(node, LeveringsautorisatieModule.TOELICHTING));
    leveringsautorisatie.setIndicatieGeblokkeerd(
        JsonUtils.getAsBoolean(node, LeveringsautorisatieModule.INDICATIE_GEBLOKKEERD, LeveringsautorisatieModule.WAARDE_JA, Boolean.TRUE, null));

    return leveringsautorisatie;
}
 
Example 30
Project: gitplex-mit   File: ManyToOneDeserializer.java   View source code 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
   public AbstractEntity deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException,
           JsonProcessingException {
       Long entityId = jp.getLongValue();
       Class<? extends AbstractEntity> valueClass = (Class<? extends AbstractEntity>) handledType();
       return (AbstractEntity) AppLoader.getInstance(Dao.class).load(valueClass, entityId);
   }
 
Example 31
Project: GitHub   File: AsyncMissingValuesInObjectTest.java   View source code 5 votes vote down vote up
public AsyncMissingValuesInObjectTest(Collection<JsonParser.Feature> features) {
    this.factory = new JsonFactory();
    this.features = new HashSet<JsonParser.Feature>(features);

    for (JsonParser.Feature feature : features) {
        factory.enable(feature);
    }
}
 
Example 32
Project: taboola-cronyx   File: TriggerDefinitionJsonDeserializer.java   View source code 5 votes vote down vote up
@Override
public TriggerDefinition deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    JsonNode root = p.getCodec().readTree(p);
    JsonNode triggerKey = root.get("triggerKey");
    JsonNode description = root.get("description");
    JsonNode jobKey = root.get("jobKey");
    JsonNode triggerData = root.get("triggerData");
    JsonNode misfireInstruction = root.get("misfireInstruction");
    JsonNode cron = root.get("cronExpression");

    if (triggerKey == null || jobKey == null) {
        throw new IOException("JSON is missing a triggerKey and jobKey");
    }

    if (cron == null) {
        return TriggerDefinitionBuilder.immediate()
                                       .identifiedAs(mapper.convertValue(triggerKey, NameAndGroup.class))
                                       .forJob(mapper.convertValue(jobKey, NameAndGroup.class))
                                       .withDescription(description != null ? description.textValue() : null)
                                       .withData(triggerData != null ? mapper.convertValue(triggerData, Map.class) : emptyMap())
                                       .withMisfireInstruction(misfireInstruction != null ? mapper.convertValue(misfireInstruction, Immediate.MisfireInstruction.class) : null)
                                       .build();
    } else {
        return TriggerDefinitionBuilder.cron()
                                .identifiedAs(mapper.convertValue(triggerKey, NameAndGroup.class))
                                .forJob(mapper.convertValue(jobKey, NameAndGroup.class))
                                .withCronExpression(cron.textValue())
                                .withDescription(description != null ? description.textValue() : null)
                                .withData(triggerData != null ? mapper.convertValue(triggerData, Map.class) : emptyMap())
                                .withMisfireInstruction(misfireInstruction != null ? mapper.convertValue(misfireInstruction, Cron.MisfireInstruction.class) : null)
                                .build();
    }
}
 
Example 33
Project: OperatieBRP   File: VrijBerichtDeserializer.java   View source code 5 votes vote down vote up
@Override
public VrijBericht deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException {
    final ObjectCodec oc = jp.getCodec();
    final JsonNode node = oc.readTree(jp);

    final Integer id = JsonUtils.getAsInteger(node, "id");
    VrijBericht vrijBericht;
    if (id != null) {
        // Bij een bestaand vrij bericht alleen indicatieGelezen aanpassen.
        vrijBericht = entityManager.find(VrijBericht.class, id);
        final String ongelezen = JsonUtils.getAsString(node, "ongelezen");
        boolean gelezen;
        switch (ongelezen) {
            case "Nee":
                gelezen = true;
                break;
            case "Ja":
            default:
                gelezen = false;
        }
        vrijBericht.setIndicatieGelezen(gelezen);
    } else {
        final Short soortvrijberId = JsonUtils.getAsShort(node, "soortvrijber");
        final String data = JsonUtils.getAsString(node, "data");
        final SoortVrijBericht soortVrijBericht = entityManager.getReference(SoortVrijBericht.class, soortvrijberId);
        vrijBericht =
                new VrijBericht(SoortBerichtVrijBericht.STUUR_VRIJ_BERICHT, soortVrijBericht,
                        Timestamp.from(DatumUtil.nuAlsZonedDateTimeInNederland().toInstant()), data, null);
        final ArrayNode partijen = (ArrayNode) node.get("partijen");
        for (JsonNode partijNode : partijen) {
            final Short partijId = Short.valueOf(partijNode.asText());
            final VrijBerichtPartij vrijBerichtPartij = new VrijBerichtPartij(vrijBericht, partijRepository.findOne(partijId));
            vrijBericht.getVrijBerichtPartijen().add(vrijBerichtPartij);
        }
    }
    return vrijBericht;
}
 
Example 34
Project: klask-io   File: JSR310LocalDateDeserializer.java   View source code 5 votes vote down vote up
@Override
public LocalDate deserialize(JsonParser parser, DeserializationContext context) throws IOException {
    switch(parser.getCurrentToken()) {
        case START_ARRAY:
            if(parser.nextToken() == JsonToken.END_ARRAY) {
                return null;
            }
            int year = parser.getIntValue();

            parser.nextToken();
            int month = parser.getIntValue();

            parser.nextToken();
            int day = parser.getIntValue();

            if(parser.nextToken() != JsonToken.END_ARRAY) {
                throw context.wrongTokenException(parser, JsonToken.END_ARRAY, "Expected array to end.");
            }
            return LocalDate.of(year, month, day);

        case VALUE_STRING:
            String string = parser.getText().trim();
            if(string.length() == 0) {
                return null;
            }
            return LocalDate.parse(string, ISO_DATE_OPTIONAL_TIME);
        default:
            throw context.wrongTokenException(parser, JsonToken.START_ARRAY, "Expected array or string.");
    }
}
 
Example 35
Project: javaOIDCMsg   File: JsonNodeClaimTest.java   View source code 5 votes vote down vote up
@Test
public void shouldThrowIfAnExtraordinaryExceptionHappensWhenParsingAsGenericMap() throws Exception {
    JsonNode value = mock(ObjectNode.class);
    when(value.getNodeType()).thenReturn(JsonNodeType.OBJECT);

    JsonNodeClaim claim = (JsonNodeClaim) claimFromNode(value);
    JsonNodeClaim spiedClaim = spy(claim);
    ObjectMapper mockedMapper = mock(ObjectMapper.class);
    when(spiedClaim.getObjectMapper()).thenReturn(mockedMapper);
    JsonParser mockedParser = mock(JsonParser.class);
    when(mockedMapper.treeAsTokens(value)).thenReturn(mockedParser);
    when(mockedParser.readValueAs(ArgumentMatchers.any(TypeReference.class))).thenThrow(IOException.class);

    exception.expect(JWTDecodeException.class);
    spiedClaim.asMap();
}
 
Example 36
Project: graphium   File: GenericQueuingJacksonSegmentInputFormat.java   View source code 5 votes vote down vote up
@Override
public void deserialize(InputStream stream, BlockingQueue<T> outputQueue)
		throws WaySegmentDeserializationException {
	try {
       	JsonParser jp = jsonFactory.createParser(stream);    	
   		JsonToken token = jp.nextToken();
   		long count = 0;
   		
   		ISegmentAdapter<IBaseSegmentDTO, T> adapter = null;
   		while(!jp.isClosed()){
   			token = jp.nextToken();
   			// extract type of segments. its encoded as the name of the array field holding the segments
   			if (jp.getCurrentToken() == JsonToken.FIELD_NAME) {    			
   				String segmentType = jp.getCurrentName();
				adapter = this.getAndRegisterDeserializers(segmentType);
   			}
   			else if(token != null && token != JsonToken.END_ARRAY && token != JsonToken.END_OBJECT) {
   				enqueue(outputQueue, processSegment(jp, adapter));
   				count++;
   			}
   		}
   		
   		log.info("parsed and enqueued: " + count + " segments");
       } catch (Exception e) {
           throw new WaySegmentDeserializationException(e.getMessage(),e);
       }		
}
 
Example 37
Project: dremio-oss   File: WriteHolders.java   View source code 5 votes vote down vote up
private void write(BitWriter writer, JsonToken token, JsonParser parser) throws IOException {
  // TODO JASON - finish other cases
  if (token == JsonToken.VALUE_NUMBER_INT) {
    writer.writeBit(parser.getIntValue() == 1 ? 1 : 0);
  } else if (token == JsonToken.VALUE_TRUE || token == JsonToken.VALUE_FALSE){
    writer.writeBit(parser.getBooleanValue() ? 1 : 0);
  } else if (token == JsonToken.VALUE_STRING) {
    writer.writeBit(ElasticsearchJsonReader.parseElasticBoolean(parser.getValueAsString()) ? 1 : 0);
  } else {
    throw UserException.dataReadError()
        .message("While reading from elasticsearch, unexpected data type in a boolean column: " + token).build(logger);
  }

}
 
Example 38
Project: GitHub   File: ValueConversionsTest.java   View source code 5 votes vote down vote up
private void _testAsDouble(int mode) throws Exception
{
    final String input = "[ 1, -3, 4.98, true, false, null, \"-17.25\", \"foo\" ]";
    JsonParser p = createParser(mode, input);

    assertToken(JsonToken.START_ARRAY, p.nextToken());
    assertEquals(0.0, p.getValueAsDouble());
    assertEquals(9.0, p.getValueAsDouble(9.0));

    assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
    assertEquals(1., p.getValueAsDouble());
    assertEquals(1., p.getValueAsDouble(-99.0));
    assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
    assertEquals(-3., p.getValueAsDouble());
    assertToken(JsonToken.VALUE_NUMBER_FLOAT, p.nextToken());
    assertEquals(4.98, p.getValueAsDouble());
    assertEquals(4.98, p.getValueAsDouble(12.5));
    assertToken(JsonToken.VALUE_TRUE, p.nextToken());
    assertEquals(1.0, p.getValueAsDouble());
    assertToken(JsonToken.VALUE_FALSE, p.nextToken());
    assertEquals(0.0, p.getValueAsDouble());
    assertToken(JsonToken.VALUE_NULL, p.nextToken());
    assertEquals(0.0, p.getValueAsDouble());
    assertEquals(0.0, p.getValueAsDouble(27.8));
    assertToken(JsonToken.VALUE_STRING, p.nextToken());
    assertEquals(-17.25, p.getValueAsDouble());
    assertEquals(-17.25, p.getValueAsDouble(1.9));
    assertToken(JsonToken.VALUE_STRING, p.nextToken());
    assertEquals(0.0, p.getValueAsDouble());
    assertEquals(1.25, p.getValueAsDouble(1.25));
    
    assertToken(JsonToken.END_ARRAY, p.nextToken());
    assertEquals(0.0, p.getValueAsDouble());
    assertEquals(7.5, p.getValueAsDouble(7.5));

    p.close();
}
 
Example 39
Project: ItemStore   File: ItemJson.java   View source code 5 votes vote down vote up
@Override
protected Item deserializeObject(JsonParser jsonParser, DeserializationContext context, ObjectCodec codec, JsonNode tree) throws IOException {
    System.out.println("deserializeObject");
    String description = tree.get("description").asText();
    String location = tree.get("location").asText();
    return new Item(1l,description, location, null);
}
 
Example 40
Project: iextrading4j   File: SystemEventTypeDeserializerTest.java   View source code 5 votes vote down vote up
@Test
public void shouldReturnUnknownTypeIfValueIsNull() throws IOException {
    final JsonParser parserMock = mock(JsonParser.class);
    final DeserializationContext contextMock = mock(DeserializationContext.class);

    when(parserMock.getValueAsString()).thenReturn(null);

    final SystemEventType result = systemEventTypeDeserializer.deserialize(parserMock, contextMock);

    assertThat(result).isEqualTo(SystemEventType.UNKNOWN);
}