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

The following examples show how to use com.fasterxml.jackson.core.JsonParseException. These examples are extracted from open source projects. 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 Project: enmasse   Source File: PortMap.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Integer> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {

    if (p.currentToken() == JsonToken.VALUE_NULL) {
        return null;
    }

    if (p.currentToken() != JsonToken.START_ARRAY) {
        throw new JsonParseException(p, "Expected start of array");
    }

    p.nextToken();

    if (p.currentToken() == JsonToken.END_ARRAY) {
        return new HashMap<> ();
    }

    final Map<String, Integer> result = new HashMap<>();
    final Iterator<Mapping> i = p.readValuesAs(Mapping.class);
    i.forEachRemaining(m -> result.put(m.getName(), m.getPort()));

    return result;
}
 
Example 2
private void checkDefinitions() throws IOException, JsonParseException, JsonMappingException {
  Path yamlFile = getDefinitionPath();

  List<TemplateRecordConfiguration> definitions = readDefinitions(yamlFile);

  TemplateRecordConfiguration record = assertNamedRecord(definitions);
  assertTrue(record.isRepeat());

  assertNull(record.getMinimalRepeat());
  assertEquals(
      ImmutableList.of("Paragraph:nth-of-type(2)", "Paragraph:nth-of-type(3)"),
      record.getCoveredPaths());

  assertDefaultRecord(definitions);

  Files.delete(yamlFile);
}
 
Example 3
Source Project: danyuan-application   Source File: ZhcxController.java    License: Apache License 2.0 6 votes vote down vote up
@RequestMapping(path = "/findAllTableRow", method = { RequestMethod.GET, RequestMethod.POST })
public @JsonIgnore Map<String, Object> findAllTableRow(@RequestBody SysDbmsTabsColsInfoVo vo) throws JsonParseException, JsonMappingException, IOException {
	logger.info("findAllTableRow", ZhcxController.class);
	Map<String, Object> map = new HashMap<>();
	if ("oracle".equals(vo.getDbType()) || "mysql".equals(vo.getDbType())) {
		// if ("单表多条件查询".equals(vo.getType())) {
		// map = zhcxService.findAllSigleTableByMulteityParam(vo);
		// } else if ("一键查询单表多个不同索引拼接".equals(vo.getType()) || "单表多条件更多查询".equals(vo.getType())) {
		// 一键查询单表多个不同索引拼接
		map = zhcxService.findBySingleTableByGroupsAndMulteityParam(vo);
		// }
	} else if ("elastic".equals(vo.getDbType())) {
		// // elasticsearch
		// map = zhcxService.findByElasticsearchByGroupsAndMulteityParam(vo);
	}
	return map;
}
 
Example 4
Source Project: levelup-java-examples   Source File: JsonToGuavaMultimap.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void convert() throws JsonParseException, JsonMappingException,
		JsonProcessingException, IOException {

	ObjectMapper objectMapper = new ObjectMapper();
	objectMapper.registerModule(new GuavaModule());

	Multimap<String, NavItem> navs = objectMapper.readValue(
			objectMapper.treeAsTokens(objectMapper.readTree(jsonString)),
			objectMapper.getTypeFactory().constructMapLikeType(
					Multimap.class, String.class, NavItem.class));

	logger.info(navs);
	
    assertThat(navs.keys(), hasItems("123455", "999999"));
}
 
Example 5
Source Project: ogham   Source File: SendGridHttpTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void simpleEmail() throws MessagingException, JsonParseException, JsonMappingException, IOException {
	// @formatter:off
	server.stubFor(post("/v3/mail/send")
		.willReturn(aResponse().withStatus(202)));
	// @formatter:on
	// @formatter:off
	Email email = new Email()
		.subject(SUBJECT)
		.content(CONTENT_TEXT)
		.from(FROM_ADDRESS)
		.to(TO_ADDRESS_1);
	// @formatter:on
	
	messagingService.send(email);
	
	// @formatter:off
	server.verify(postRequestedFor(urlEqualTo("/v3/mail/send"))
		.withRequestBody(equalToJson(resourceAsString("/expected/requests/simpleEmail.json"), true, true)));
	// @formatter:on
}
 
Example 6
Source Project: sailfish-core   Source File: JsonMessageConverterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFullFormatRejected() throws JsonParseException, IOException, SailfishURIException {
    IMessage message = generate();

    message.getMetaData().setRejectReason("Test reject");

    String json = JsonMessageConverter.toJson(message, false);
    IMessage actual = JsonMessageConverter.fromJson(json, false);
    compare(message, actual, 43, 0, 0);

    Assert.assertEquals("Test reject", actual.getMetaData().getRejectReason());
    Assert.assertTrue(actual.getMetaData().isRejected());

    json = JsonMessageConverter.toJson(message, dictionary, false);
    actual = JsonMessageConverter.fromJson(json, manager, false);
    compare(message, actual, 43, 0, 0);

    Assert.assertEquals("Test reject", actual.getMetaData().getRejectReason());
    Assert.assertTrue(actual.getMetaData().isRejected());
}
 
Example 7
Source Project: java-client-api   Source File: JacksonStreamTest.java    License: Apache License 2.0 6 votes vote down vote up
private OrderItem getOrderItem(JsonParser parser) throws JsonParseException, IOException {
  OrderItem item = new OrderItem();
  if ( parser.getCurrentToken() != JsonToken.START_OBJECT ) {
    throw new IllegalStateException("nextValue should have been START_OBJECT but is:[" + parser.getCurrentToken() + "]");
  }
  while ( parser.nextValue() != null ) {
    if ( "productId".equals(parser.getCurrentName()) ) {
      item.setProductId( parser.getText() );
    } else if ( "quantity".equals(parser.getCurrentName()) ) {
      item.setQuantity( parser.getIntValue() );
    } else if ( "itemCostUSD".equals(parser.getCurrentName()) ) {
      item.setItemCostUSD( parser.getFloatValue() );
    }
    if ( parser.getCurrentToken() == JsonToken.END_OBJECT ) {
      return item;
    }
  }
  return null;
}
 
Example 8
Source Project: milkman   Source File: DiffTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldMergeCorrectlyRenameCollection() throws JsonParseException, JsonMappingException, IOException {
	String colId = UUID.randomUUID().toString();
	
	List<Collection> base = new LinkedList<Collection>();
	base.add(new Collection(colId, "collection1", false, new LinkedList<>(), Collections.emptyList()));
	
	List<Collection> working = new LinkedList<Collection>();
	working.add(new Collection(colId, "collection2", false, new LinkedList<>(), Collections.emptyList()));
	
	CollectionDiffer collectionDiffer = new CollectionDiffer();
	DiffNode diffNode = collectionDiffer.compare(working, base);
	
	collectionDiffer.mergeDiffs(working, base, diffNode);
	
	assertThat(base.size()).isEqualTo(1);
	assertThat(base.get(0).getId()).isEqualTo(colId);
	assertThat(base.get(0).getName()).isEqualTo("collection2");
	
}
 
Example 9
Source Project: RedReader   Source File: JsonBufferedObject.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void buildBuffered(final JsonParser jp) throws IOException {

	JsonToken jt;

	while((jt = jp.nextToken()) != JsonToken.END_OBJECT) {

		if(jt != JsonToken.FIELD_NAME)
			throw new JsonParseException(jp, "Expecting field name, got " + jt.name(),
					jp.getCurrentLocation());

		final String fieldName = jp.getCurrentName();
		final JsonValue value = new JsonValue(jp);

		synchronized(this) {
			properties.put(fieldName, value);
			notifyAll();
		}

		value.buildInThisThread();
	}
}
 
Example 10
Source Project: blynk-server   Source File: BodyParam.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public Object get(ChannelHandlerContext ctx, URIDecoder uriDecoder) {
    if (uriDecoder.contentType == null || !uriDecoder.contentType.contains(expectedContentType)) {
        throw new RuntimeException("Unexpected content type. Expecting " + expectedContentType + ".");
    }

    switch (expectedContentType) {
        case MediaType.APPLICATION_JSON :
            String data = "";
            try {
                data = uriDecoder.getContentAsString();
                return JsonParser.MAPPER.readValue(data, type);
            } catch (JsonParseException | JsonMappingException jsonParseError) {
                log.debug("Error parsing body param : '{}'.", data);
                throw new RuntimeException("Error parsing body param. " + data);
            } catch (Exception e) {
                log.error("Unexpected error during parsing body param.", e);
                throw new RuntimeException("Unexpected error during parsing body param.", e);
            }
        default :
            return uriDecoder.getContentAsString();
    }
}
 
Example 11
Source Project: nifi   Source File: SiteToSiteRestApiClient.java    License: Apache License 2.0 6 votes vote down vote up
private TransactionResultEntity readResponse(final InputStream inputStream) throws IOException {
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();

    StreamUtils.copy(inputStream, bos);
    String responseMessage = null;

    try {
        responseMessage = new String(bos.toByteArray(), StandardCharsets.UTF_8);
        logger.debug("readResponse responseMessage={}", responseMessage);

        final ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(responseMessage, TransactionResultEntity.class);
    } catch (JsonParseException | JsonMappingException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Failed to parse JSON.", e);
        }

        final TransactionResultEntity entity = new TransactionResultEntity();
        entity.setResponseCode(ResponseCode.ABORT.getCode());
        entity.setMessage(responseMessage);
        return entity;
    }
}
 
Example 12
Source Project: kylin   Source File: AclTableMigrationTool.java    License: Apache License 2.0 6 votes vote down vote up
private ManagedUser hbaseRowToUser(Result result) throws JsonParseException, JsonMappingException, IOException {
    if (null == result || result.isEmpty())
        return null;

    String username = Bytes.toString(result.getRow());

    byte[] valueBytes = result.getValue(Bytes.toBytes(AclConstant.USER_AUTHORITY_FAMILY),
            Bytes.toBytes(AclConstant.USER_AUTHORITY_COLUMN));
    UserGrantedAuthority[] deserialized = ugaSerializer.deserialize(valueBytes);

    String password = "";
    List<UserGrantedAuthority> authorities = Collections.emptyList();

    // password is stored at [0] of authorities for backward compatibility
    if (deserialized != null) {
        if (deserialized.length > 0 && deserialized[0].getAuthority().startsWith(AclConstant.PWD_PREFIX)) {
            password = deserialized[0].getAuthority().substring(AclConstant.PWD_PREFIX.length());
            authorities = Arrays.asList(deserialized).subList(1, deserialized.length);
        } else {
            authorities = Arrays.asList(deserialized);
        }
    }
    return new ManagedUser(username, password, false, authorities);
}
 
Example 13
public static int fromJsonToWkid(JsonParser parser)
		throws JsonParseException, IOException {
	int wkid = 0;
	if (parser.getCurrentToken() != JsonToken.START_OBJECT) {
		return 0;
	}

	while (parser.nextToken() != JsonToken.END_OBJECT) {
		String fieldName = parser.getCurrentName();

		if ("wkid".equals(fieldName)) {
			parser.nextToken();
			wkid = parser.getIntValue();
		}
	}
	return wkid;
}
 
Example 14
public JType generatePojoFromSchema(JCodeModel codeModel, String className, String packageName, String json, String url, SourceType sourceType) throws IOException {
    try {
        SchemaMapper schemaMapper = new SchemaMapper(getRuleFactory(sourceType, codeGenConfig), new SchemaGenerator());
        if (SourceType.JSON == sourceType) {
            return schemaMapper.generate(codeModel, className, packageName, json);
        } else {
            URI uri;
            if (url == null) {
                File tmpFile = File.createTempFile("tmp", "json");
                try (FileWriter writer = new FileWriter(tmpFile)) {
                    writer.write(json);
                }
                uri = tmpFile.toURI();
            } else {
                uri = URI.create(url);
            }

            return schemaMapper.generate(codeModel, className, packageName, json, uri);
        }
    } catch (JsonParseException e) {
        logger.info("Can not generate  " + className + " from schema since : " + e.getMessage());
        return codeModel.ref(String.class);
    }
}
 
Example 15
@Test
public void accessProtectedResourceByJwtToken() throws JsonParseException, JsonMappingException, IOException, InvalidJwtException {
    ResponseEntity<String> response = new TestRestTemplate().getForEntity("http://localhost:" + port + "/resources/client", String.class);
    assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());

    response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?client_id=trusted-app&grant_type=client_credentials", null, String.class);
    String responseText = response.getBody();
    assertEquals(HttpStatus.OK, response.getStatusCode());
    HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class);
    String accessToken = (String) jwtMap.get("access_token");

    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", "Bearer " + accessToken);

    JwtContext jwtContext = jwtConsumer.process(accessToken);
    logJWTClaims(jwtContext);

    response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/principal", HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    assertEquals("trusted-app", response.getBody());

    response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/trusted_client", HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());

    response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/roles", HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    assertEquals("[{\"authority\":\"ROLE_TRUSTED_CLIENT\"}]", response.getBody());

}
 
Example 16
@Test
public void unformedFileAgainstSchema() throws Exception {
    GenerateConnectorInspectionsMojo mojo = new GenerateConnectorInspectionsMojo();

    String unformedConnectorFile = "my-unformed-connector.json";
    assertThatExceptionOfType(MojoExecutionException.class)
        .isThrownBy(() -> {
            mojo.validateWithSchema(getFile("/" + unformedConnectorFile));
        })
        .withCauseInstanceOf(JsonParseException.class)
        .withStackTraceContaining("line: 9, column: 12");
}
 
Example 17
Source Project: depan   Source File: PushDownJsonHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testIntegerFieldDoc() throws JsonParseException, IOException {
  JsonParser parser = new JsonFactory().createParser(
      "{ \"blix\" : 1234 }");
  PushDownJsonHandler handler = new PushDownJsonHandler(parser);
  TestDocumentHandler docHandler = new TestDocumentHandler();

  handler.parseDocument(docHandler);

  docHandler.child.assertNesting();
  docHandler.child.assertField("blix");
  assertEquals(new BigInteger("1234"), docHandler.child.bigIntegerValue);
}
 
Example 18
Source Project: tutorials   Source File: StringToJsonNodeUnitTest.java    License: MIT License 5 votes vote down vote up
@Test
public final void givenTheJsonNode_whenRetrievingDataFromId_thenCorrect() throws JsonParseException, IOException {
    final String jsonString = "{\"k1\":\"v1\",\"k2\":\"v2\"}";
    final ObjectMapper mapper = new ObjectMapper();
    final JsonNode actualObj = mapper.readTree(jsonString);

    // When
    final JsonNode jsonNode1 = actualObj.get("k1");
    assertThat(jsonNode1.textValue(), equalTo("v1"));
}
 
Example 19
@Test
public void testRecordDefinition()
    throws AnalysisEngineProcessException, ResourceInitializationException, JsonParseException,
        JsonMappingException, IOException {
  processJCas(
      TemplateRecordConfigurationCreatingConsumer.PARAM_OUTPUT_DIRECTORY,
      tempDirectory.toString());
  checkDefinitions();
}
 
Example 20
Source Project: WeBASE-Front   Source File: PrecompiledUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Map string2Map(String str)
        throws JsonParseException, IOException{
    Map<String, Object> resMap;
    ObjectMapper mapper = new ObjectMapper();
    resMap = mapper.readValue(str, Map.class);
    return resMap;
}
 
Example 21
Source Project: cf-butler   Source File: ApplicationReporterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testReportGeneration() throws JsonParseException, JsonMappingException, IOException {
    File file = new File(System.getProperty("user.home") + "/app-reporting-config.json");
    if (file.exists()) {
        ReportRequestSpec spec = mapper.readValue(file, ReportRequestSpec.class);
        reporter.createReport(spec.getOutput(), spec.getInput());
        Assertions.assertThat(new File(spec.getOutput()).exists()).isTrue();
    }
}
 
Example 22
Source Project: open-Autoscaler   Source File: TransferedPolicy.java    License: Apache License 2.0 5 votes vote down vote up
public static String packServiceInfo(String current_json, Map<String, String> service_info) throws JsonParseException, JsonMappingException, IOException {

		JsonNode new_top = BeanValidation.new_mapper.readTree(current_json);

		String appType = service_info.get("appType");
		if (appType != null) {
			((ObjectNode)new_top).put("appType", appType);
		}
		return BeanValidation.new_mapper.writeValueAsString(new_top);
	}
 
Example 23
Source Project: kylin   Source File: Serializer.java    License: Apache License 2.0 5 votes vote down vote up
public T deserialize(byte[] value) throws JsonParseException, JsonMappingException, IOException {
    if (null == value) {
        return null;
    }

    return JsonUtil.readValue(value, type);
}
 
Example 24
@Override
public Sha256Hash deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
   ObjectCodec oc = jp.getCodec();
   JsonNode node = oc.readTree(jp);
   Sha256Hash hash = Sha256Hash.fromString(node.asText());
   if (hash == null) {
      throw new JsonParseException("Failed to convert string '" + node.asText() + "' into a Sha256 hash",
            JsonLocation.NA);
   }
   return hash;
}
 
Example 25
Source Project: buck   Source File: BuildFilePythonResultDeserializer.java    License: Apache License 2.0 5 votes vote down vote up
private static Map<String, Object> deserializeObject(JsonParser jp) throws IOException {
  ImmutableMapWithNullValues.Builder<String, Object> builder =
      ImmutableMapWithNullValues.Builder.insertionOrder();
  String fieldName;
  while ((fieldName = jp.nextFieldName()) != null) {
    builder.put(STRING_INTERNER.intern(fieldName), deserializeRecursive(jp, jp.nextToken()));
  }
  if (jp.getCurrentToken() != JsonToken.END_OBJECT) {
    throw new JsonParseException(jp, "Missing expected END_OBJECT");
  }
  return builder.build();
}
 
Example 26
Source Project: postman-runner   Source File: PostmanReader.java    License: Apache License 2.0 5 votes vote down vote up
public PostmanEnvironment readEnvironmentFileClasspath(String fileOnClasspath) throws JsonParseException, JsonMappingException, IOException {
	String fileName = fileOnClasspath.substring(fileOnClasspath.indexOf(":")+1);
	InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
	
	PostmanEnvironment env = om.readValue(stream, PostmanEnvironment.class);
	stream.close();
	return env;
}
 
Example 27
Source Project: Cardshifter   Source File: TestClient.java    License: Apache License 2.0 5 votes vote down vote up
public <T> List<T> awaitMany(int count, Class<T> class1) throws JsonParseException, JsonProcessingException, IOException, InterruptedException {
	List<T> result = new ArrayList<>();
	for (int i = 0; i < count; i++) {
		result.add(await(class1));
	}
	assertEquals(count, result.size());
	return result;
}
 
Example 28
Source Project: nexus-public   Source File: NpmPublishParserTest.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void throwExceptionOnInvalidUtf8Content() throws Exception {
  exception.expectMessage("Invalid UTF-8");
  exception.expect(JsonParseException.class);
  try (InputStream in = new ByteArrayInputStream("{\"name\":\"foo\",\"author\":\"bé\"}".getBytes(ISO_8859_1))) {
    try (JsonParser jsonParser = jsonFactory.createParser(in)) {
      NpmPublishParser underTest = new NpmPublishParser(jsonParser, storageFacet, HASH_ALGORITHMS);
      underTest.parse(NO_USER);
      fail(); // exception should be thrown on parse
    }
  }
}
 
Example 29
Source Project: dropbox-sdk-java   Source File: JsonReader.java    License: MIT License 5 votes vote down vote up
public static boolean readBoolean(JsonParser parser)
    throws IOException, JsonReadException
{
    try {
        boolean b = parser.getBooleanValue();
        parser.nextToken();
        return b;
    }
    catch (JsonParseException ex) {
        throw JsonReadException.fromJackson(ex);
    }
}
 
Example 30
private void setLocationInformation(
    BulkUploadProcessTask task,
    LocationClient locationClient,
    Map<String, Location> locationCache,
    ActorRef locationActor,
    List<String> locationCodes)
    throws IOException, JsonParseException, JsonMappingException {
  ObjectMapper mapper = new ObjectMapper();
  if (ProjectUtil.BulkProcessStatus.COMPLETED.getValue() == task.getStatus()) {
    List<String> locationNames = new ArrayList<>();
    for (String locationCode : locationCodes) {
      if (locationCache.containsKey(locationCode)) {
        locationNames.add(locationCache.get(locationCode).getName());
      } else {
        Location location = locationClient.getLocationByCode(locationActor, locationCode);
        locationNames.add(location.getName());
      }
    }
    Map<String, Object> row = mapper.readValue(task.getSuccessResult(), Map.class);
    if (locationNames.size() == 1) {
      row.put(JsonKey.LOCATION_NAME, locationNames.get(0));
      row.put(JsonKey.LOCATION_CODE, locationCodes.get(0));
    } else {
      row.put(JsonKey.LOCATION_NAME, locationNames);
      row.put(JsonKey.LOCATION_CODE, locationCodes);
    }
    task.setSuccessResult(mapper.writeValueAsString(row));
  }
}