@Override public Window deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException { JsonNode node = jp.getCodec().readTree(jp); Double value = node.get("value").asDouble(); Window window = new Window(value); if (node.has("bounds")) { long lowerBound = node.get("bounds").get(0).asLong(); long upperBound = node.get("bounds").get(1).asLong(); window.withLowerBound(lowerBound).withUpperBound(upperBound); } return window; }
@SuppressWarnings("unchecked") private <T> T parseContent(InputStream content, String string) { Map<String, Object> map = Collections.emptyMap(); try { // create parser manually to lower Jackson requirements JsonParser jsonParser = mapper.getJsonFactory().createJsonParser(content); try { map = mapper.readValue(jsonParser, Map.class); } finally { countStreamStats(content); } } catch (IOException ex) { throw new EsHadoopParsingException(ex); } return (T) (string != null ? map.get(string) : map); }
private void read(DataInput in) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.configure( DeserializationConfig.Feature.CAN_OVERRIDE_ACCESS_MODIFIERS, true); // define a module SimpleModule module = new SimpleModule("State Serializer", new Version(0, 1, 1, "FINAL")); // add the state deserializer module.addDeserializer(StatePair.class, new StateDeserializer()); // register the module with the object-mapper mapper.registerModule(module); JsonParser parser = mapper.getJsonFactory().createJsonParser((DataInputStream)in); StatePool statePool = mapper.readValue(parser, StatePool.class); this.setStates(statePool.getStates()); parser.close(); }
@Override public Directive deserialize(JsonParser jp, DeserializationContext ctx) throws IOException { ObjectReader reader = ObjectMapperUtil.instance().getObjectReader(); ObjectNode obj = (ObjectNode) reader.readTree(jp); Iterator<Map.Entry<String, JsonNode>> elementsIterator = obj.getFields(); String rawMessage = obj.toString(); DialogRequestIdHeader header = null; JsonNode payloadNode = null; ObjectReader headerReader = ObjectMapperUtil.instance().getObjectReader(DialogRequestIdHeader.class); while (elementsIterator.hasNext()) { Map.Entry<String, JsonNode> element = elementsIterator.next(); if (element.getKey().equals("header")) { header = headerReader.readValue(element.getValue()); } if (element.getKey().equals("payload")) { payloadNode = element.getValue(); } } if (header == null) { throw ctx.mappingException("Missing header"); } if (payloadNode == null) { throw ctx.mappingException("Missing payload"); } return createDirective(header, payloadNode, rawMessage); }
private void buildScoreRule(JsonParser jsonParser,JsonNode ruleNode,ScoreRule rule){ rule.setScoringBean(JsonUtils.getJsonValue(ruleNode, "scoringBean")); AssignTargetType assignTargetType=AssignTargetType.valueOf(JsonUtils.getJsonValue(ruleNode, "assignTargetType")); rule.setAssignTargetType(assignTargetType); rule.setVariableCategory(JsonUtils.getJsonValue(ruleNode, "variableCategory")); rule.setVariableName(JsonUtils.getJsonValue(ruleNode, "variableName")); rule.setVariableLabel(JsonUtils.getJsonValue(ruleNode, "variableLabel")); String datatypeStr=JsonUtils.getJsonValue(ruleNode, "datatype"); if(StringUtils.isNotBlank(datatypeStr)){ rule.setDatatype(Datatype.valueOf(datatypeStr)); } try{ JsonNode knowledgePackageWrapperNode=ruleNode.get("knowledgePackageWrapper"); ObjectMapper mapper = (ObjectMapper)jsonParser.getCodec(); KnowledgePackageWrapper wrapper=mapper.readValue(knowledgePackageWrapperNode, KnowledgePackageWrapper.class); wrapper.buildDeserialize(); rule.setKnowledgePackageWrapper(wrapper); }catch(Exception ex){ throw new RuleException(ex); } }
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 SerializationConfig.Feature) { this.objectMapper.configure((SerializationConfig.Feature) feature, enabled); } else if (feature instanceof DeserializationConfig.Feature) { this.objectMapper.configure((DeserializationConfig.Feature) feature, enabled); } else { throw new IllegalArgumentException("Unknown feature class: " + feature.getClass().getName()); } }
@Override public StatePair deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException { ObjectMapper mapper = (ObjectMapper) parser.getCodec(); // set the state-pair object tree ObjectNode statePairObject = (ObjectNode) mapper.readTree(parser); Class<?> stateClass = null; try { stateClass = Class.forName(statePairObject.get("className").getTextValue().trim()); } catch (ClassNotFoundException cnfe) { throw new RuntimeException("Invalid classname!", cnfe); } String stateJsonString = statePairObject.get("state").toString(); State state = (State) mapper.readValue(stateJsonString, stateClass); return new StatePair(state); }
@Override public ProducedEventsResult deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException { JsonNode node = jp.getCodec().readTree(jp); if (node.isArray()) { List<ProducedEventResult> responses = new ArrayList<>(); Iterator<JsonNode> it = node.iterator(); while (it.hasNext()) { JsonNode n = it.next(); responses.add(new ProducedEventResult(n.get("created").asBoolean())); } return new ProducedEventsResult(responses); } else { String reason = node.get("reason").asText(); return new ProducedEventsResult(reason); } }
@Override public TopicRecord deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException { JsonNode node = jp.getCodec().readTree(jp); String topic = node.get("topic").asText(); long partition = node.get("partition").asLong(); long offset = node.get("offset").asLong(); long timestamp = node.get("timestamp").asLong(); String key = null; if (node.has("key")) { key = node.get("key").asText(); } Map<Object, Object> value = new ObjectMapper().readValue(node.get("value").toString(), Map.class); return new TopicRecord(topic, key, partition, offset, timestamp, value); }
@Override public SubscribeToTopicResult deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException { JsonNode node = jp.getCodec().readTree(jp); boolean success = false; String reason = null; if (node.has("subscribed")) { success = node.get("subscribed").asBoolean(); } if (node.has("reason")) { reason = node.get("reason").asText(); } return new SubscribeToTopicResult(success, reason); }
@Override public JsonUpdateWebServer deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException { final ObjectCodec obj = jp.getCodec(); final JsonNode node = obj.readTree(jp).get(0); final Set<String> groupIds = deserializeGroupIdentifiers(node); return new JsonUpdateWebServer(node.get("webserverId").getValueAsText(), node.get("webserverName").getTextValue(), node.get("hostName").getTextValue(), node.get("portNumber").getValueAsText(), node.get("httpsPort").getValueAsText(), groupIds, node.get("statusPath").getTextValue(), node.get("apacheHttpdMediaId").getTextValue()); }
@Override public JsonCreateWebServer deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException { final ObjectCodec obj = jp.getCodec(); final JsonNode node = obj.readTree(jp).get(0); final JsonNode apacheHttpdMediaId = node.get("apacheHttpdMediaId"); final JsonCreateWebServer jcws = new JsonCreateWebServer(node.get("webserverName").getTextValue(), node.get("hostName").getTextValue(), node.get("portNumber").asText(), node.get("httpsPort").asText(), deserializeGroupIdentifiers(node), node.get("statusPath").getTextValue(), apacheHttpdMediaId == null ? null : apacheHttpdMediaId.asText()); return jcws; }
/** * manifest.jsonのバリデート. * @param jp Jsonパーサー * @param mapper ObjectMapper * @return JSONManifestオブジェクト * @throws IOException データの読み込みに失敗した場合 */ protected JSONManifest manifestJsonValidate(JsonParser jp, ObjectMapper mapper) throws IOException { // TODO BARファイルのバージョンチェック JSONManifest manifest = null; try { manifest = mapper.readValue(jp, JSONManifest.class); } catch (UnrecognizedPropertyException ex) { throw PersoniumCoreException.BarInstall.JSON_FILE_FORMAT_ERROR.params( "manifest.json unrecognized property"); } if (manifest.getBarVersion() == null) { throw PersoniumCoreException.BarInstall.JSON_FILE_FORMAT_ERROR.params("manifest.json#barVersion"); } if (manifest.getBoxVersion() == null) { throw PersoniumCoreException.BarInstall.JSON_FILE_FORMAT_ERROR.params("manifest.json#boxVersion"); } if (manifest.getDefaultPath() == null) { throw PersoniumCoreException.BarInstall.JSON_FILE_FORMAT_ERROR.params("manifest.json#DefaultPath"); } return manifest; }
/** * barファイルエントリからJSONファイルを読み込む. * @param <T> JSONMappedObject * @param inStream barファイルエントリのInputStream * @param entryName entryName * @param clazz clazz * @return JSONファイルから読み込んだオブジェクト * @throws IOException JSONファイル読み込みエラー */ public static <T> T readJsonEntry( InputStream inStream, String entryName, Class<T> clazz) throws IOException { JsonParser jp = null; ObjectMapper mapper = new ObjectMapper(); JsonFactory f = new JsonFactory(); jp = f.createJsonParser(inStream); JsonToken token = jp.nextToken(); // JSONルート要素("{") Pattern formatPattern = Pattern.compile(".*/+(.*)"); Matcher formatMatcher = formatPattern.matcher(entryName); String jsonName = formatMatcher.replaceAll("$1"); T json = null; if (token == JsonToken.START_OBJECT) { try { json = mapper.readValue(jp, clazz); } catch (UnrecognizedPropertyException ex) { throw PersoniumCoreException.BarInstall.JSON_FILE_FORMAT_ERROR.params(jsonName); } } else { throw PersoniumCoreException.BarInstall.JSON_FILE_FORMAT_ERROR.params(jsonName); } return json; }
/** * リクエストボディを解析してEventオブジェクトを取得する. * @param reader Http入力ストリーム * @return 解析したEventオブジェクト */ protected JSONEvent getRequestBody(final Reader reader) { JSONEvent event = null; JsonParser jp = null; ObjectMapper mapper = new ObjectMapper(); JsonFactory f = new JsonFactory(); try { jp = f.createJsonParser(reader); JsonToken token = jp.nextToken(); // JSONルート要素("{") if (token == JsonToken.START_OBJECT) { event = mapper.readValue(jp, JSONEvent.class); } else { throw PersoniumCoreException.Event.JSON_PARSE_ERROR; } } catch (IOException e) { throw PersoniumCoreException.Event.JSON_PARSE_ERROR; } return event; }
/** * manifest.jsonのschema値がURL形式である場合trueが返却されること. * @throws IOException IOException */ @SuppressWarnings("unchecked") @Test public void manifest_jsonのschema値がURL形式である場合trueが返却されること() throws IOException { JsonFactory f = new JsonFactory(); JSONObject json = new JSONObject(); json.put("bar_version", "1"); json.put("box_version", "1"); json.put("DefaultPath", "boxName"); json.put("schema", "http://app1.example.com/"); JsonParser jp = f.createJsonParser(json.toJSONString()); ObjectMapper mapper = new ObjectMapper(); jp.nextToken(); JSONManifest manifest = mapper.readValue(jp, JSONManifest.class); assertTrue(manifest.checkSchema()); }
/** * manifest_jsonのschema値がURL形式でない場合falseが返却されること. * @throws IOException IOException */ @SuppressWarnings("unchecked") @Test public void manifest_jsonのschema値がURL形式でない場合falseが返却されること() throws IOException { JsonFactory f = new JsonFactory(); JSONObject json = new JSONObject(); json.put("bar_version", "1"); json.put("box_version", "1"); json.put("DefaultPath", "boxName"); json.put("schema", "test"); JsonParser jp = f.createJsonParser(json.toJSONString()); ObjectMapper mapper = new ObjectMapper(); jp.nextToken(); JSONManifest manifest = mapper.readValue(jp, JSONManifest.class); assertFalse(manifest.checkSchema()); }
/** * manifest_jsonのschema値がnull場合falseが返却されること. * @throws IOException IOException */ @SuppressWarnings("unchecked") @Test public void manifest_jsonのschema値がnull場合falseが返却されること() throws IOException { JsonFactory f = new JsonFactory(); JSONObject json = new JSONObject(); json.put("bar_version", "1"); json.put("box_version", "1"); json.put("DefaultPath", "boxName"); json.put("schema", null); JsonParser jp = f.createJsonParser(json.toJSONString()); ObjectMapper mapper = new ObjectMapper(); jp.nextToken(); JSONManifest manifest = mapper.readValue(jp, JSONManifest.class); assertFalse(manifest.checkSchema()); }
/** * manifest_jsonのschemaの指定がない場合falseが返却されること. * @throws IOException IOException */ @SuppressWarnings("unchecked") @Test public void manifest_jsonのschemaの指定がない場合falseが返却されること() throws IOException { JsonFactory f = new JsonFactory(); JSONObject json = new JSONObject(); json.put("bar_version", "1"); json.put("box_version", "1"); json.put("DefaultPath", "boxName"); JsonParser jp = f.createJsonParser(json.toJSONString()); ObjectMapper mapper = new ObjectMapper(); jp.nextToken(); JSONManifest manifest = mapper.readValue(jp, JSONManifest.class); assertFalse(manifest.checkSchema()); }
/** * bar_versionを指定しない場合に例外がスローされる. */ @Test @SuppressWarnings({"unchecked" }) public void bar_versionを指定しない場合に例外がスローされる() { JsonFactory f = new JsonFactory(); JSONObject json = new JSONObject(); json.put("box_version", "1"); json.put("DefaultPath", "boxName"); json.put("schema", "http://app1.example.com"); try { JsonParser jp = f.createJsonParser(json.toJSONString()); ObjectMapper mapper = new ObjectMapper(); jp.nextToken(); TestBarRunner testBarRunner = new TestBarRunner(); testBarRunner.manifestJsonValidate(jp, mapper); } catch (PersoniumCoreException dce) { assertEquals(400, dce.getStatus()); assertEquals("PR400-BI-0006", dce.getCode()); return; } catch (Exception ex) { fail("Unexpected exception"); } fail("PersoniumCoreExceptionが返却されない"); }
/** * box_versionを指定しない場合に例外がスローされる. */ @Test @SuppressWarnings({"unchecked" }) public void box_versionを指定しない場合に例外がスローされる() { JsonFactory f = new JsonFactory(); JSONObject json = new JSONObject(); json.put("bar_version", "1"); json.put("DefaultPath", "boxName"); json.put("schema", "http://app1.example.com"); try { JsonParser jp = f.createJsonParser(json.toJSONString()); ObjectMapper mapper = new ObjectMapper(); jp.nextToken(); TestBarRunner testBarRunner = new TestBarRunner(); testBarRunner.manifestJsonValidate(jp, mapper); } catch (PersoniumCoreException dce) { assertEquals(400, dce.getStatus()); assertEquals("PR400-BI-0006", dce.getCode()); return; } catch (Exception ex) { fail("Unexpected exception"); } fail("PersoniumCoreExceptionが返却されない"); }
/** * DefaultPathを指定しない場合に例外がスローされる. */ @Test @SuppressWarnings({"unchecked" }) public void DefaultPathを指定しない場合に例外がスローされる() { JsonFactory f = new JsonFactory(); JSONObject json = new JSONObject(); json.put("bar_version", "1"); json.put("box_version", "1"); json.put("schema", "http://app1.example.com"); try { JsonParser jp = f.createJsonParser(json.toJSONString()); ObjectMapper mapper = new ObjectMapper(); jp.nextToken(); TestBarRunner testBarRunner = new TestBarRunner(); testBarRunner.manifestJsonValidate(jp, mapper); } catch (PersoniumCoreException dce) { assertEquals(400, dce.getStatus()); assertEquals("PR400-BI-0006", dce.getCode()); return; } catch (Exception ex) { fail("Unexpected exception"); } fail("PersoniumCoreExceptionが返却されない"); }
private com.esri.core.geometry.Geometry constructGeometry(com.esri.ges.spatial.Geometry geo) throws Exception { try{ String jsonIn = geo.toJson(); JsonFactory jf = new JsonFactory(); JsonParser jp = jf.createJsonParser(jsonIn); MapGeometry mgeo = GeometryEngine.jsonToGeometry(jp); com.esri.core.geometry.Geometry geoIn= mgeo.getGeometry(); return GeometryEngine.project(geoIn, srIn, srBuffer); } catch(Exception e) { LOG.error(e.getMessage()); LOG.error(e.getStackTrace()); throw(e); } }
public void parse(HttpRequest req) throws IOException { final JsonParser parser = jsonFactory.createJsonParser( new ChannelBufferInputStream(req.getContent())); parser.nextToken(); // Skip the wrapper while (parser.nextToken() != JsonToken.END_OBJECT) { final String metric = parser.getCurrentName(); JsonToken currentToken = parser.nextToken(); if (currentToken == JsonToken.START_OBJECT) { parseMetricObject(metric, parser); } else if (currentToken == JsonToken.START_ARRAY) { int illegalTokens = parseMetricArray(metric, parser); if(illegalTokens > 0) { logger.warn("{} illegal tokens encountered", illegalTokens); } } else { logger.warn("Illegal token: expected {} or {}, but was {}: {}",new Object[] { JsonToken.START_OBJECT, JsonToken.START_ARRAY, currentToken, parser.getText()}); } } }
private int parseMetricArray(String metric, JsonParser parser) throws IOException { JsonToken currentToken; int illegalTokens = 0; while ((currentToken = parser.nextToken()) != JsonToken.END_ARRAY) { if(!currentToken.equals(JsonToken.START_OBJECT)) { logger.warn("Illegal token: expected {}, but was {}: {}", new Object[] {JsonToken.START_OBJECT, currentToken, parser.getText()}); illegalTokens++; } else { parseMetricObject(metric, parser); } } return illegalTokens; }
private NumberType convertNumberType(JsonParser.NumberType numberType) { switch (numberType) { case INT: return NumberType.INT; case LONG: return NumberType.LONG; case FLOAT: return NumberType.FLOAT; case DOUBLE: return NumberType.DOUBLE; case BIG_INTEGER: return NumberType.DOUBLE; case BIG_DECIMAL: return NumberType.DOUBLE; } throw new EsHadoopSerializationException("No matching token for number_type [" + numberType + "]"); }
@SuppressWarnings("unchecked") protected BackportedJacksonMappingIterator(JavaType type, JsonParser jp, DeserializationContext ctxt, JsonDeserializer<?> deser) { _type = type; _parser = jp; _context = ctxt; _deserializer = (JsonDeserializer<T>) deser; /* One more thing: if we are at START_ARRAY (but NOT root-level * one!), advance to next token (to allow matching END_ARRAY) */ if (jp != null && jp.getCurrentToken() == JsonToken.START_ARRAY) { JsonStreamContext sc = jp.getParsingContext(); // safest way to skip current token is to clear it (so we'll advance soon) if (!sc.inRoot()) { jp.clearCurrentToken(); } } }
@Test public void testParseItems() throws IOException { ObjectMapper mapper = new ObjectMapper(); InputStream in = getClass().getResourceAsStream("/org/elasticsearch/hadoop/serialization/dto/mapping/bulk-error.json"); JsonParser parser = mapper.getJsonFactory().createJsonParser(in); assertNotNull(ParsingUtils.seek(new JacksonJsonParser(parser), "items")); BackportedObjectReader r = BackportedObjectReader.create(mapper, Map.class); for (Iterator<Map> iterator = r.readValues(parser); iterator.hasNext();) { Map map = mapper.readValue(parser, Map.class); String error = (String) ((Map) map.values().iterator().next()).get("error"); assertNotNull(error); assertTrue(error.contains("document already exists")); } }
@Override public Instant deserialize(final JsonParser parser, final DeserializationContext ctxt) throws IOException, JsonProcessingException { final JsonToken jsonToken = parser.getCurrentToken(); if (jsonToken == JsonToken.VALUE_NUMBER_INT) { return new Instant(parser.getLongValue()); } else if (jsonToken == JsonToken.VALUE_STRING) { final String str = parser.getText().trim(); if (str.length() == 0) { return null; } final DateTimeFormatter formatter = ISODateTimeFormat.dateTimeParser(); final DateTime dateTime = formatter.parseDateTime(str); return new Instant(dateTime.getMillis()); } throw ctxt.mappingException(Instant.class); }
/** * Search for any registered JsonDeserialize instances that have been declared using the * ServiceLoader. Add any found to the given mapper in a 'magic' module. */ private static void addDiscoverableDeserializers(final ObjectMapper mapper) { final ServiceLoader<JsonDeserializer> loader = ServiceLoader.load(JsonDeserializer.class); final Iterator<JsonDeserializer> iterator = loader.iterator(); final SimpleModule magic = new SimpleModule("magic", new Version(1, 0, 0, "")); while (iterator.hasNext()) { final JsonDeserializer<?> deserializer = iterator.next(); try { final Method deserialeMethod = deserializer.getClass() .getDeclaredMethod("deserialize", JsonParser.class, DeserializationContext.class); final Class<?> jsonType = deserialeMethod.getReturnType(); //noinspection unchecked magic.addDeserializer(jsonType, (JsonDeserializer) deserializer); } catch(Exception e) { throw new IllegalStateException(e); } } mapper.registerModule(magic); }
@Override public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { // validate enum class if (enumClass == null) { throw new JsonMappingException("Unable to parse unknown pick-list type"); } final String listValue = jp.getText(); try { // parse the string of the form value1;value2;... final String[] value = listValue.split(";"); final int length = value.length; final Object resultArray = Array.newInstance(enumClass, length); for (int i = 0; i < length; i++) { // use factory method to create object Array.set(resultArray, i, factoryMethod.invoke(null, value[i].trim())); } return resultArray; } catch (Exception e) { throw new JsonParseException("Exception reading multi-select pick list value", jp.getCurrentLocation(), e); } }
private static SlotStatus readSlotStatus(JsonParser jParser) throws IOException { SlotStatus res = new SlotStatus(); while (jParser.nextToken() != JsonToken.END_OBJECT) { switch (jParser.getCurrentName() + "") { case "slotId": nextToken(jParser); res.setSlot(readValue(jParser)); break; default: throw new IOException("Unexpected field " + jParser.getCurrentName()); } } return res; }