Java Code Examples for com.fasterxml.jackson.core.JsonFactory#createParser()
The following examples show how to use
com.fasterxml.jackson.core.JsonFactory#createParser() .
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: ClientRPCStoreTest.java From seldon-server with Apache License 2.0 | 6 votes |
@Test public void testDefaultRequestToJSON() throws JsonParseException, IOException, NoSuchMethodException, SecurityException { mockClientConfigHandler.addListener((ClientConfigUpdateListener) EasyMock.anyObject()); EasyMock.expectLastCall().once(); replay(mockClientConfigHandler); final String client = "test"; ClientRpcStore store = new ClientRpcStore(mockClientConfigHandler); DefaultCustomPredictRequest customRequest = DefaultCustomPredictRequest.newBuilder().addValues(1.0f).build(); Any anyMsg = Any.pack(customRequest); ClassificationRequestMeta meta = ClassificationRequestMeta.newBuilder().setPuid("1234").build(); ClassificationRequest request = ClassificationRequest.newBuilder().setMeta(meta).setData(anyMsg).build(); System.out.println(request); JsonNode json = store.getJSONForRequest(client, request); Assert.assertNotNull(json); System.out.println(json); ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); JsonParser parser = factory.createParser(json.toString()); JsonNode actualObj = mapper.readTree(parser); ClassificationRequest req = store.getPredictRequestFromJson(client, actualObj); Assert.assertNotNull(req); System.out.println(req); }
Example 2
Source File: SnowflakeGCSClient.java From snowflake-jdbc with Apache License 2.0 | 6 votes |
private AbstractMap.SimpleEntry<String, String> parseEncryptionData(String jsonEncryptionData) throws SnowflakeSQLException { ObjectMapper mapper = ObjectMapperFactory.getObjectMapper(); JsonFactory factory = mapper.getFactory(); try { JsonParser parser = factory.createParser(jsonEncryptionData); JsonNode encryptionDataNode = mapper.readTree(parser); String iv = encryptionDataNode.get("ContentEncryptionIV").asText(); String key = encryptionDataNode.get("WrappedContentKey").get("EncryptedKey").asText(); return new AbstractMap.SimpleEntry<>(key, iv); } catch (Exception ex) { throw new SnowflakeSQLException(ex, SqlState.SYSTEM_ERROR, ErrorCode.IO_ERROR.getMessageCode(), "Error parsing encryption data as json" + ": " + ex.getMessage()); } }
Example 3
Source File: JsonSchemaGenerator.java From kafka-connect-spooldir with Apache License 2.0 | 6 votes |
@Override protected Map<String, Schema.Type> determineFieldTypes(InputStream inputStream) throws IOException { Map<String, Schema.Type> typeMap = new LinkedHashMap<>(); JsonFactory factory = new JsonFactory(); try (JsonParser parser = factory.createParser(inputStream)) { Iterator<JsonNode> iterator = ObjectMapperFactory.INSTANCE.readValues(parser, JsonNode.class); while (iterator.hasNext()) { JsonNode node = iterator.next(); if (node.isObject()) { Iterator<String> fieldNames = node.fieldNames(); while (fieldNames.hasNext()) { typeMap.put(fieldNames.next(), Schema.Type.STRING); } break; } } } return typeMap; }
Example 4
Source File: JsonSmileMigrationService.java From JavaBase with MIT License | 6 votes |
public static byte[] convertToSmile(byte[] json, JsonFactory jsonFactory, SmileFactory smileFactory) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try // try-with-resources ( JsonGenerator jg = smileFactory.createGenerator(bos); JsonParser jp = jsonFactory.createParser(json) ) { while (jp.nextToken() != null) { jg.copyCurrentEvent(jp); } } catch (Exception e) { log.error("Error while converting json to smile", e); } return bos.toByteArray(); }
Example 5
Source File: ClientRPCStoreTest.java From seldon-server with Apache License 2.0 | 6 votes |
@Test public void testRequestToJSON() throws JsonParseException, IOException, NoSuchMethodException, SecurityException { mockClientConfigHandler.addListener((ClientConfigUpdateListener) EasyMock.anyObject()); EasyMock.expectLastCall().once(); replay(mockClientConfigHandler); final String client = "test"; ClientRpcStore store = new ClientRpcStore(mockClientConfigHandler); CustomPredictRequest customRequest = CustomPredictRequest.newBuilder().addData(1.0f).build(); store.add(client, customRequest.getClass(), null,customRequest.getClass().getMethod("newBuilder"),null); Any anyMsg = Any.pack(customRequest); ClassificationRequestMeta meta = ClassificationRequestMeta.newBuilder().setPuid("1234").build(); ClassificationRequest request = ClassificationRequest.newBuilder().setMeta(meta).setData(anyMsg).build(); JsonNode json = store.getJSONForRequest(client, request); Assert.assertNotNull(json); System.out.println(json); ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); JsonParser parser = factory.createParser(json.toString()); JsonNode actualObj = mapper.readTree(parser); ClassificationRequest req = store.getPredictRequestFromJson(client, actualObj); Assert.assertNotNull(req); }
Example 6
Source File: MLWorker.java From sailfish-core with Apache License 2.0 | 6 votes |
private MachineLearnMessageAlias getMachineLearnMessageAlias(Message message) { Map<String, Object> sfMessage = (Map<String, Object>) parseMessageFromContent(message.getContent()); JsonFactory factory = new JsonFactory(); try { JsonParser parser = factory.createParser(message.getContent()); com.exactpro.sf.embedded.machinelearning.entities.Message parseMessage = JsonEntityParser.parseMessage(SFLocalContext.getDefault().getDictionaryManager(), parser, sfMessage.entrySet() .stream() .filter(o -> !(o instanceof Map)) .collect(Collectors.toMap(Map.Entry::getKey, entry -> Objects.toString(entry.getValue()))), true, true); parseMessage.setId(message.getId()); return MachineLearnMessageAlias.wrap(parseMessage); } catch (IOException e) { throw new EPSCommonException("Message from json report can't be parsed", e); } }
Example 7
Source File: HistoDbClientImpl.java From ipst with Mozilla Public License 2.0 | 6 votes |
@Override public List<HistoDbAttributeId> listAttributes() throws IOException { List<HistoDbAttributeId> attrs = new ArrayList<>(); try (InputStream is = httpClient.getHttpRequest(new HistoDbUrl(config, "metadata.json", ImmutableMap.of("colRange", "*")))) { JsonFactory jfactory = new JsonFactory(); try (JsonParser jParser = jfactory.createParser(is)) { while (jParser.nextToken() != null) { String fieldname = jParser.getCurrentName(); if ("name".equals(fieldname)) { jParser.nextToken(); attrs.add(HistoDbAttributeIdParser.parse(jParser.getText())); } } } } return attrs; }
Example 8
Source File: ClientRpcStore.java From seldon-server with Apache License 2.0 | 6 votes |
private JsonNode getDefaultRequestJSON(Message msg) throws JsonParseException, IOException { Message.Builder o2 = DefaultCustomPredictRequest.newBuilder(); TypeRegistry registry = TypeRegistry.newBuilder().add(o2.getDescriptorForType()).build(); JsonFormat.Printer jPrinter = JsonFormat.printer(); String result = jPrinter.usingTypeRegistry(registry).print(msg); ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); JsonParser parser = factory.createParser(result); JsonNode jNode = mapper.readTree(parser); if (jNode.has(PredictionBusinessServiceImpl.REQUEST_CUSTOM_DATA_FIELD)) { JsonNode values = jNode.get(PredictionBusinessServiceImpl.REQUEST_CUSTOM_DATA_FIELD).get("values"); ((ObjectNode) jNode).set(PredictionBusinessServiceImpl.REQUEST_CUSTOM_DATA_FIELD, values); } return jNode; }
Example 9
Source File: JsonMessageDecoder.java From sailfish-core with Apache License 2.0 | 5 votes |
/** * Parse JSON to IMessage * @param json - JSON * @return */ public T decode(String json, boolean compact) { try { JsonFactory factory = new JsonFactory(); JsonParser parser = factory.createParser(json); parser.nextToken(); return parse(parser, compact); } catch (RuntimeException | IOException | SailfishURIException e) { throw new EPSCommonException(e); } }
Example 10
Source File: RequestTest.java From seldon-server with Apache License 2.0 | 5 votes |
@Test public void testActionPatterns3() throws JsonParseException, IOException { String json = "{\"consumer\":\"dailyrecord\",\"httpmethod\":\"GET\",\"path\":\"/users/22/actions/33\",\"exectime\":\"34\",\"time\":123456789}"; ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); JsonParser parser = factory.createParser(json); JsonNode jNode = mapper.readTree(parser); Request r = new Request(jNode); Assert.assertNotNull(r); Assert.assertEquals("/users/{userid}/actions/{itemid}", r.path); }
Example 11
Source File: RequestTest.java From seldon-server with Apache License 2.0 | 5 votes |
@Test public void testActionPatterns() throws JsonParseException, IOException { String json = "{\"consumer\":\"dailyrecord\",\"httpmethod\":\"GET\",\"path\":\"/users/22/actions\",\"exectime\":\"34\",\"time\":123456789}"; ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); JsonParser parser = factory.createParser(json); JsonNode jNode = mapper.readTree(parser); Request r = new Request(jNode); Assert.assertNotNull(r); Assert.assertEquals("/users/{userid}/actions", r.path); }
Example 12
Source File: RequestTest.java From seldon-server with Apache License 2.0 | 5 votes |
@Test public void testRecommendationPattern() throws JsonParseException, IOException { String json = "{\"consumer\":\"dailyrecord\",\"httpmethod\":\"GET\",\"path\":\"/users/22/recommendations\",\"exectime\":\"34\",\"time\":123456789}"; ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); JsonParser parser = factory.createParser(json); JsonNode jNode = mapper.readTree(parser); Request r = new Request(jNode); Assert.assertNotNull(r); Assert.assertEquals("/users/{userid}/recommendations", r.path); }
Example 13
Source File: GelfMessageJsonEncoderTest.java From gelfclient with Apache License 2.0 | 4 votes |
@Test public void testOptionalFullMessage() throws Exception { final EmbeddedChannel channel = new EmbeddedChannel(new GelfMessageJsonEncoder()); final GelfMessage message = new GelfMessageBuilder("test").build(); assertTrue(channel.writeOutbound(message)); assertTrue(channel.finish()); final ByteBuf byteBuf = (ByteBuf) channel.readOutbound(); final byte[] bytes = new byte[byteBuf.readableBytes()]; byteBuf.getBytes(0, bytes).release(); final JsonFactory json = new JsonFactory(); final JsonParser parser = json.createParser(bytes); String version = null; Number timestamp = null; String host = null; String short_message = null; String full_message = null; Number level = null; while (parser.nextToken() != JsonToken.END_OBJECT) { String key = parser.getCurrentName(); if (key == null) { continue; } parser.nextToken(); switch (key) { case "version": version = parser.getText(); break; case "timestamp": timestamp = parser.getNumberValue(); break; case "host": host = parser.getText(); break; case "short_message": short_message = parser.getText(); break; case "full_message": full_message = parser.getText(); break; case "level": level = parser.getNumberValue(); break; default: throw new Exception("Found unexpected field in JSON payload: " + key); } } assertEquals(message.getVersion().toString(), version); assertEquals(message.getTimestamp(), timestamp); assertEquals(message.getHost(), host); assertEquals(message.getMessage(), short_message); assertNull(full_message); assertEquals(message.getLevel().getNumericLevel(), level); }
Example 14
Source File: GelfMessageJsonEncoderTest.java From gelfclient with Apache License 2.0 | 4 votes |
@Test public void testEncode() throws Exception { byte[] bytes = readBytes(); JsonFactory json = new JsonFactory(); JsonParser parser = json.createParser(bytes); String version = null; Number timestamp = null; String host = null; String short_message = null; String full_message = null; Number level = null; Number _foo = null; Number _bar = null; String _baz = null; while (parser.nextToken() != JsonToken.END_OBJECT) { String key = parser.getCurrentName(); if (key == null) { continue; } parser.nextToken(); switch (key) { case "version": version = parser.getText(); break; case "timestamp": timestamp = parser.getNumberValue(); break; case "host": host = parser.getText(); break; case "short_message": short_message = parser.getText(); break; case "full_message": full_message = parser.getText(); break; case "level": level = parser.getNumberValue(); break; case "_foo": _foo = parser.getNumberValue(); break; case "_bar": _bar = parser.getNumberValue(); break; case "_baz": _baz = parser.getText(); break; default: throw new Exception("Found unexpected field in JSON payload: " + key); } } assertEquals(message.getVersion().toString(), version); assertEquals(message.getTimestamp(), timestamp); assertEquals(message.getHost(), host); assertEquals(message.getMessage(), short_message); assertEquals(message.getFullMessage(), full_message); assertEquals(message.getLevel().getNumericLevel(), level); assertEquals(1.0, _foo); assertEquals(128, _bar); assertEquals("a value", _baz); }
Example 15
Source File: EventIterator.java From kafka-connect-splunk with Apache License 2.0 | 4 votes |
public static EventIterator create(JsonFactory jsonFactory, BufferedReader bufferedReader) throws IOException { JsonParser jsonParser = jsonFactory.createParser(bufferedReader); return create(jsonFactory, jsonParser); }
Example 16
Source File: EventIterator.java From kafka-connect-splunk with Apache License 2.0 | 4 votes |
public static EventIterator create(JsonFactory jsonFactory, InputStream inputStream) throws IOException { JsonParser jsonParser = jsonFactory.createParser(inputStream); return create(jsonFactory, jsonParser); }
Example 17
Source File: TableStorageErrorDeserializer.java From azure-storage-android with Apache License 2.0 | 4 votes |
/** * Gets the Extended Error information. * * @return the Extended Error information. * * @param reader * the input stream to read error details from. * @param format * The {@link TablePayloadFormat} to use for parsing * @throws IOException * if an error occurs while accessing the stream with Json. */ public static StorageExtendedErrorInformation getExtendedErrorInformation(final Reader reader, final TablePayloadFormat format) throws JsonParseException, IOException { JsonFactory jsonFactory = new JsonFactory(); JsonParser parser = jsonFactory.createParser(reader); try { final StorageExtendedErrorInformation errorInfo = new StorageExtendedErrorInformation(); if (!parser.hasCurrentToken()) { parser.nextToken(); } JsonUtilities.assertIsStartObjectJsonToken(parser); parser.nextToken(); JsonUtilities.assertIsFieldNameJsonToken(parser); JsonUtilities.assertIsExpectedFieldName(parser, "odata.error"); // start getting extended error information parser.nextToken(); JsonUtilities.assertIsStartObjectJsonToken(parser); // get code parser.nextValue(); JsonUtilities.assertIsExpectedFieldName(parser, TableConstants.ErrorConstants.ERROR_CODE); errorInfo.setErrorCode(parser.getValueAsString()); // get message parser.nextToken(); JsonUtilities.assertIsFieldNameJsonToken(parser); JsonUtilities.assertIsExpectedFieldName(parser, TableConstants.ErrorConstants.ERROR_MESSAGE); parser.nextToken(); JsonUtilities.assertIsStartObjectJsonToken(parser); parser.nextValue(); JsonUtilities.assertIsExpectedFieldName(parser, "lang"); parser.nextValue(); JsonUtilities.assertIsExpectedFieldName(parser, "value"); errorInfo.setErrorMessage(parser.getValueAsString()); parser.nextToken(); JsonUtilities.assertIsEndObjectJsonToken(parser); parser.nextToken(); // get innererror if it exists if (parser.getCurrentToken() == JsonToken.FIELD_NAME) { JsonUtilities.assertIsExpectedFieldName(parser, TableConstants.ErrorConstants.INNER_ERROR); errorInfo.getAdditionalDetails().putAll(parseJsonErrorException(parser)); parser.nextToken(); } // end code object JsonUtilities.assertIsEndObjectJsonToken(parser); // end odata.error object parser.nextToken(); JsonUtilities.assertIsEndObjectJsonToken(parser); return errorInfo; } finally { parser.close(); } }
Example 18
Source File: JCalRawReader.java From biweekly with BSD 2-Clause "Simplified" License | 4 votes |
/** * Reads the next iCalendar object from the jCal data stream. * @param listener handles the iCalendar data as it is read off the wire * @throws JCalParseException if the jCal syntax is incorrect (the JSON * syntax may be valid, but it is not in the correct jCal format). * @throws JsonParseException if the JSON syntax is incorrect * @throws IOException if there is a problem reading from the data stream */ public void readNext(JCalDataStreamListener listener) throws IOException { if (parser == null) { JsonFactory factory = new JsonFactory(); parser = factory.createParser(reader); } if (parser.isClosed()) { return; } this.listener = listener; //find the next iCalendar object JsonToken prev = parser.getCurrentToken(); JsonToken cur; while ((cur = parser.nextToken()) != null) { if (prev == JsonToken.START_ARRAY && cur == JsonToken.VALUE_STRING && VCALENDAR_COMPONENT_NAME.equals(parser.getValueAsString())) { //found break; } if (strict) { //the parser was expecting the jCal to be there if (prev != JsonToken.START_ARRAY) { throw new JCalParseException(JsonToken.START_ARRAY, prev); } if (cur != JsonToken.VALUE_STRING) { throw new JCalParseException(JsonToken.VALUE_STRING, cur); } throw new JCalParseException("Invalid value for first token: expected \"vcalendar\" , was \"" + parser.getValueAsString() + "\"", JsonToken.VALUE_STRING, cur); } prev = cur; } if (cur == null) { //EOF eof = true; return; } parseComponent(new ArrayList<String>()); }
Example 19
Source File: JSONImporter.java From robe with GNU Lesser General Public License v3.0 | 4 votes |
@Override public void importStream(InputStream inputStream, OnItemHandler handler, String charSetName) throws Exception { JsonFactory factory = new MappingJsonFactory(); JsonParser parser = factory.createParser(new InputStreamReader(inputStream, charSetName)); JsonToken current; current = parser.nextToken(); if (current != JsonToken.START_ARRAY) { throw new RuntimeException("Error: root should be object or array."); } while (parser.nextToken() != JsonToken.END_ARRAY) { if (parser.getCurrentName() == null) continue; T item = (T) parser.readValueAs(getDataClass()); handler.onItem(item); } }
Example 20
Source File: GelfMessageJsonEncoderTest.java From gelfclient with Apache License 2.0 | 4 votes |
@Test public void testNullLevel() throws Exception { final EmbeddedChannel channel = new EmbeddedChannel(new GelfMessageJsonEncoder()); final GelfMessage message = new GelfMessageBuilder("test").build(); message.setLevel(null); assertTrue(channel.writeOutbound(message)); assertTrue(channel.finish()); final ByteBuf byteBuf = (ByteBuf) channel.readOutbound(); final byte[] bytes = new byte[byteBuf.readableBytes()]; byteBuf.getBytes(0, bytes).release(); final JsonFactory json = new JsonFactory(); final JsonParser parser = json.createParser(bytes); String version = null; Number timestamp = null; String host = null; String short_message = null; String full_message = null; Number level = null; while (parser.nextToken() != JsonToken.END_OBJECT) { String key = parser.getCurrentName(); if (key == null) { continue; } parser.nextToken(); switch (key) { case "version": version = parser.getText(); break; case "timestamp": timestamp = parser.getNumberValue(); break; case "host": host = parser.getText(); break; case "short_message": short_message = parser.getText(); break; case "full_message": full_message = parser.getText(); break; case "level": level = parser.getNumberValue(); break; default: throw new Exception("Found unexpected field in JSON payload: " + key); } } assertEquals(message.getVersion().toString(), version); assertEquals(message.getTimestamp(), timestamp); assertEquals(message.getHost(), host); assertEquals(message.getMessage(), short_message); assertNull(full_message); assertNull(level); }