@Override public List<NYTimesMultimedium> deserialize(JsonParser parser, DeserializationContext context) throws IOException { RealmList<NYTimesMultimedium> list = new RealmList<>(); TreeNode treeNode = parser.getCodec().readTree(parser); if (!(treeNode instanceof ArrayNode)) { return list; } ArrayNode arrayNode = (ArrayNode) treeNode; for (JsonNode node : arrayNode) { NYTimesMultimedium nyTimesMultimedium = objectMapper.treeToValue(node, NYTimesMultimedium.class); list.add(nyTimesMultimedium); } return list; }
/** * Десериализатор Gson Map в Map<String, String> значение * * @param parser * Gson строка * @throws IOException * исключение парсера * @return карта */ public static Map<String, String> gsonMap2Map(JsonParser parser) throws IOException { ObjectCodec codec = parser.getCodec(); TreeNode node = codec.readTree(parser); Map<String, String> ret = new HashMap<String, String>(); if (node.isObject()) { for (Iterator<String> iter = node.fieldNames(); iter.hasNext();) { String fieldName = iter.next(); TreeNode field = node.get(fieldName); if (field != null) { ret.put(fieldName, field.toString()); } else { ret.put(fieldName, "null"); } } } return ret; }
/** * Десериализатор TreeNode массива в Map где четный элемент ключ а не четный * значение * * @param <T> * тип ключя карты * @param <V> * тип значения карты * @param node * узел * @param keyClass * класс для ключа карты * @param valueClass * класс для значения карты * @throws IOException * исключение парсера * @return карта */ private static <T, V> Map<T, V> string2Map(TreeNode node, Class<T> keyClass, Class<V> valueClass) throws IOException { ObjectMapper mapper = new ObjectMapper(); Map<T, V> ret = new HashMap<T, V>(); if (node.isArray()) { T key = null; ArrayNode key2value = (ArrayNode) node; for (int i = 0; i < key2value.size(); i++) { if (i % 2 == 0) { key = mapper.treeToValue(key2value.get(i), keyClass); } else { V value = mapper.treeToValue(key2value.get(i), valueClass); ret.put(key, value); } } } return ret; }
private Map<String, List<String>> parse(TreeNode node) { Map<String, List<String>> result = new HashMap<>(); Iterator<String> itKeys = node.fieldNames(); while(itKeys.hasNext()) { String key = itKeys.next(); List<String> values = new ArrayList<>(); // Header has only one value if(node.get(key).isValueNode()) { values.add(((JsonNode)node.get(key)).asText()); } // Header has multiple values else if (node.get(key).isArray()){ for (JsonNode val : (JsonNode) node.get(key)) { values.add(val.asText()); } } result.put(key, values); } return result; }
@Test public void testGetExits(@Mocked ViewResult queryResult, @Mocked ViewResult.Row row, @Mocked JsonNode key) throws Exception { List<ViewResult.Row> rows = Arrays.asList(row); Exits exits = new Exits(); exits.setN(new Exit(site, "n")); site.setExits(exits); final ObjectMapper anyInstance = new ObjectMapper(); new Expectations(ObjectMapper.class) {{ anyInstance.treeToValue((TreeNode) any, Site.class); returns(site); }}; new Expectations() {{ dbc.queryView((ViewQuery) any); returns(queryResult); queryResult.getRows(); returns(rows); row.getKeyAsNode(); returns(key); key.get(2); returns(JsonNodeFactory.instance.textNode("n")); }}; Exits e = docs.getExits(new Coordinates(1,2)); Assert.assertEquals("Site should be bound to the north", site.getId(), e.getN().getId()); }
public static String[] convertToArgs(PipelineOptions options) { try { byte[] opts = MAPPER.writeValueAsBytes(options); JsonParser jsonParser = MAPPER.getFactory().createParser(opts); TreeNode node = jsonParser.readValueAsTree(); ObjectNode optsNode = (ObjectNode) node.get("options"); ArrayList<String> optArrayList = new ArrayList<>(); Iterator<Entry<String, JsonNode>> entries = optsNode.fields(); while (entries.hasNext()) { Entry<String, JsonNode> entry = entries.next(); if (entry.getValue().isNull()) { continue; } else if (entry.getValue().isTextual()) { optArrayList.add("--" + entry.getKey() + "=" + entry.getValue().asText()); } else { optArrayList.add("--" + entry.getKey() + "=" + entry.getValue()); } } return optArrayList.toArray(new String[optArrayList.size()]); } catch (IOException e) { throw new IllegalStateException(e); } }
@Override public HyperLogLogPlus deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException, JsonProcessingException { final TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser); final TreeNode coreHyperLogLogPlusObject = treeNode.get("hyperLogLogPlus"); if (null != coreHyperLogLogPlusObject) { final TextNode jsonNodes = (TextNode) coreHyperLogLogPlusObject.get(HyperLogLogPlusJsonConstants.HYPER_LOG_LOG_PLUS_SKETCH_BYTES_FIELD); final byte[] nodeAsString = jsonNodes.binaryValue(); final HyperLogLogPlus hyperLogLogPlus = HyperLogLogPlus.Builder.build(nodeAsString); return hyperLogLogPlus; } else { throw new IllegalArgumentException("Receieved null or empty HyperLogLogPlus sketch"); } }
/** * Parse command field from the compose yaml file to list command words. * * @param jsonParser json parser * @param ctxt deserialization context * @throws IOException in case I/O error. For example element to parsing contains invalid yaml * field type defined for this field by yaml document model. * @throws JsonProcessingException */ @Override public List<String> deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException { TreeNode tree = jsonParser.readValueAsTree(); if (tree.isArray()) { return toCommand((ArrayNode) tree, ctxt); } if (tree instanceof TextNode) { TextNode textNode = (TextNode) tree; return asList(textNode.asText().trim().split(SPLIT_COMMAND_REGEX)); } throw ctxt.mappingException( (format("Field '%s' must be simple text or string array.", jsonParser.getCurrentName()))); }
@Override public AnnotationResource deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException { AnnotationResource result; ObjectMapper mapper = (ObjectMapper) jp.getCodec(); TreeNode node = mapper.readTree(jp); String format = ((TextNode) node.get("format")).textValue(); String id = null; TextNode idNode = (TextNode) node.get("@id"); if (idNode != null) { id = idNode.textValue(); } String type = ((TextNode) node.get("@type")).textValue(); if (node.get("chars") != null) { result = new AnnotationResourceCharsImpl(type, format); String chars = ((TextNode) node.get("chars")).textValue(); ((AnnotationResourceCharsImpl) result).setChars(chars); } else { result = new AnnotationResourceImpl(type, format); } if (id != null) { result.setId(URI.create(id)); } return result; }
@Override public SeeAlso deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { ObjectMapper mapper = (ObjectMapper) jp.getCodec(); TreeNode node = mapper.readTree(jp); SeeAlso seeAlso = new SeeAlsoImpl(); if (ObjectNode.class.isAssignableFrom(node.getClass())) { String id = ((TextNode) node.get("@id")).textValue(); TextNode formatNode = ((TextNode) node.get("format")); TextNode profileNode = ((TextNode) node.get("profile")); seeAlso.setId(uriFromString(id)); if (formatNode != null) { seeAlso.setFormat(formatNode.textValue()); } if (profileNode != null) { seeAlso.setProfile(uriFromString(profileNode.textValue())); } } else if (TextNode.class.isAssignableFrom(node.getClass())) { seeAlso.setId(uriFromString(((TextNode) node).textValue())); } else { throw new IllegalArgumentException("SeeAlso must be a string or object!"); } return seeAlso; }
@Override public IiifReference deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException { ObjectMapper mapper = (ObjectMapper) jp.getCodec(); TreeNode node = mapper.readTree(jp); String id; if (ObjectNode.class.isAssignableFrom(node.getClass())) { id = ((TextNode) node.get("@id")).textValue(); String type = ((TextNode) node.get("@type")).textValue(); if (!"sc:AnnotationList".equals(type)) { throw new IllegalArgumentException(String.format("Do not know how to handle reference type '%s'", type)); } } else if (TextNode.class.isAssignableFrom(node.getClass())) { id = ((TextNode) node).textValue(); } else { throw new IllegalArgumentException("Reference must be a string or object!"); } return new AnnotationListReferenceImpl(URI.create(id)); }
@Override public ActionSettingsMetadata deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { TreeNode node = jsonParser.getCodec().readTree(jsonParser); //email settings if (node.get(RECIPIENTS).isArray()) { ArrayNode recipientsNode = ((ArrayNode)node.get(RECIPIENTS)); List<String> recipients = new ArrayList<>(recipientsNode.size()); recipientsNode.forEach(recipient -> recipients.add(recipient.asText())); return new ActionSettingsEmailMetadata().recipients(recipients); } return null; }
public <T> T treeToValue(TreeNode paramTreeNode, Class<T> paramClass) { try { Object localObject = readValue(treeAsTokens(paramTreeNode), paramClass); return localObject; } catch (JsonProcessingException localJsonProcessingException) { throw localJsonProcessingException; } catch (IOException localIOException) { throw new IllegalArgumentException(localIOException.getMessage(), localIOException); } }
@Override public Event deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { ObjectCodec codec = jp.getCodec(); TreeNode treeNode = codec.readTree(jp); UUID id = UUID.fromString(((TextNode) treeNode.get("id")).asText()); String typeStr = ((TextNode) treeNode.get("type")).asText(); Type type = Type.byName(typeStr); TreeNode responseNode = treeNode.get("response"); StemResponse result = mapper.treeToValue(responseNode, type.clazz); Event event = Event.create(type, id); event.setResponse(result); return event; }
@Override public Resource deserialize(JsonParser parser, DeserializationContext context) throws IOException { TreeNode tree = parser.readValueAsTree(); Assert.isTrue(tree.path("rClass") != MissingNode.getInstance(), "No 'rClass' field found. Cannot deserialize Resource JSON."); RClass rClass = modelService.resolveRType(((TextNode) tree.path("rClass")).textValue()); if (rClass.isAbstract()) { throw new AbstractRClassException(rClass); } Resource resource = factory.createResource(rClass); TreeNode properties = tree.path("properties"); if (properties instanceof ObjectNode) { populateProperties((ObjectNode) properties, resource); } return resource; }
public String lookup(Locale locale, String path) { TreeNode bundle = lookupBundle(locale); if (bundle == null && !"en".equals(locale.getLanguage())) { // unsupported language. Fall back to English. bundle = lookupBundle(Locale.ENGLISH); } if (bundle == null) { throw new IllegalStateException("No bundle found for " + locale.getLanguage() + " with path '" + path + "'"); } TreeNode cursor = bundle; String[] parts = path.split("\\."); for (String pathPart : parts) { cursor = cursor.path(pathPart); } return ((TextNode)cursor).textValue(); }
public void handleCallMessage(CallMessage cm) { RpcHandler rpcHandler = wampServer.getHandler(cm.procURI); if (rpcHandler == null) rpcHandler = wampServer.getHandler(resolveCURI(cm.procURI)); if (rpcHandler == null) { ctx.write(new CallErrorMessage(cm.callId, "http:/wamp.ws/error#nosuchproc", "Such procedure does not exist")); return; } TreeNode callResult; try { callResult = rpcHandler.call(cm.args, handlerContext); } catch (CallErrorException cex) { ctx.write(new CallErrorMessage(cm.callId, cex)); return; } ctx.write(new CallResultMessage(cm.callId, callResult)); }
@Override public TreeNode call(final List<TreeNode> args, final HandlerContext ctx) throws CallErrorException { if (ctx.getSession().isAuthRequested()) throw new CallErrorException("Already authenticated"); final String authKey = ((TextNode) args.get(0)).textValue(); if (!ctx.wampServer.authSecretProvider.keyExists(authKey)) throw new CallErrorException("Authentication key does not exist"); String extra = null; if (args.get(1) != null && !(args.get(1) instanceof NullNode)) { extra = ((TextNode) args.get(1)).textValue(); } try { final String challenge = HmacSHA256.generate(ctx.getSession().id + System.currentTimeMillis(), authKey); ctx.getSession().authKey = authKey; ctx.getSession().challenge = challenge; return new TextNode(challenge); } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new CallErrorException("Internal server error"); } }
@Override public TreeNode call(final List<TreeNode> args, final HandlerContext ctx) throws CallErrorException { if (!ctx.getSession().isAuthRequested()) throw new CallErrorException("No authentication previously requested"); if (ctx.wampServer.authSecretProvider == null) throw new CallErrorException("Internal server error"); final String clientSignature = ((TextNode) args.get(0)).textValue(); final String correctSignature; try { final String secret = ctx.wampServer.authSecretProvider.getSecret(ctx.getSession().authKey); if (secret == null || secret.isEmpty()) throw new CallErrorException("Authentication secret does not exist"); correctSignature = HmacSHA256.generate(ctx.getSession().challenge, secret); } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new CallErrorException("Internal sever error"); } if (clientSignature.equals(correctSignature)) { ctx.getSession().signature = clientSignature; return ctx.mapper.createObjectNode(); } else { ctx.getSession().authKey = null; ctx.getSession().challenge = null; ctx.getSession().signature = null; throw new CallErrorException("Signature for authentication request is invalid"); } }
@Override public String toJson() { String jsonStr = null; try ( StringWriter sw = new StringWriter(); JsonGenerator jg = MessageMapper.jsonFactory.createGenerator(sw) ) { jg.writeStartArray(); jg.writeNumber(getMessageCode()); jg.writeString(callId); jg.writeString(procURI); if (args != null && !args.isEmpty()) for (TreeNode tn : args) jg.writeTree(tn); jg.writeEndArray(); jg.close(); jsonStr = sw.toString(); } catch (IOException e) { e.printStackTrace(); } return jsonStr; }
@Override public CompoundOperation deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { // Add mapper if (jp.getCodec() == null) jp.setCodec(new ObjectMapper()); jp.nextToken(); // Read whole tree TreeNode tree = jp.readValueAsTree(); Operation[] operations = new Operation[tree.size() - 1]; // tree.get(0) is always zero // Read operations for (int i = 1; i < tree.size(); i++) { JsonParser ojp = tree.get(i).traverse(); ojp.setCodec(new ObjectMapper()); operations[i - 1] = ojp.readValueAs(Operation.class); } return new CompoundOperation(operations); }
public void testSimpleMixed() throws Exception { final String INPUT = "{\"a\":[1,2,{\"b\":true},3],\"c\":3}"; TreeNode node = TREE_CODEC.readTree(_factory.createParser(READ_CONTEXT, INPUT)); assertTrue(node instanceof JrsObject); assertEquals(2, node.size()); TreeNode list = node.get("a"); assertTrue(list instanceof JrsArray); // actually, verify with write... final StringWriter writer = new StringWriter(); final JsonGenerator g = _factory.createGenerator(WRITE_CONTEXT, writer); TREE_CODEC.writeTree(g, node); g.close(); assertEquals(INPUT, writer.toString()); }
@Test public void simple() throws Exception { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ChromeTraceWriter writer = new ChromeTraceWriter(byteArrayOutputStream); writer.writeStart(); writer.writeEvent( new ChromeTraceEvent("aa", "bb", Phase.BEGIN, 11, 12, 13, 14, ImmutableMap.of())); writer.writeEvent( new ChromeTraceEvent("cc", "dd", Phase.END, 11, 12, 13, 14, ImmutableMap.of())); writer.writeEnd(); writer.close(); JsonParser parser = ObjectMappers.createParser(byteArrayOutputStream.toByteArray()); TreeNode node = parser.readValueAsTree(); Assert.assertNotNull(node); Assert.assertTrue(node.getClass().getName(), node instanceof ArrayNode); }
@Override public UserVideo deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { TreeNode tree = defaultMapper.readTree(jp); ObjectNode root = (ObjectNode) tree; Iterator<String> keys = root.fieldNames(); while (keys.hasNext()) { String key = keys.next(); if ("video".equals(key)) { JsonNode value = root.get(key); if (value.isObject()) { root.set(key, value.get("readable_id")); } } } UserVideo video = defaultMapper.treeToValue(tree, UserVideo.class); return video; }
@Override public MetadataDto deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException { ObjectCodec codec = p.getCodec(); TreeNode node = codec.readTree(p); try { return Util.node2String2Object(node, MetadataDto.class); } catch (Exception e) { LOG.error("Unable deserialize asset: " + e.getMessage(), e); } return new MetadataDto(); }
@Override public Asset deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException { ObjectCodec codec = p.getCodec(); TreeNode node = codec.readTree(p); try { String str = Util.node2String(node); return new Asset(str); } catch (BusinessException e) { LOG.error("Unable deserialize asset: " + e.getMessage(), e); } return new Asset(0, AssetSymbolType.GBG); }
@Override public JSONOptions deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonLocation l = jp.getTokenLocation(); // logger.debug("Reading tree."); TreeNode n = jp.readValueAsTree(); // logger.debug("Tree {}", n); if (n instanceof JsonNode) { return new JSONOptions( (JsonNode) n, l); } else { throw new IllegalArgumentException(String.format("Received something other than a JsonNode %s", n)); } }
@Override public RTimeSeriesData deserialize(JsonParser jp, DeserializationContext ctx) throws IOException { final TreeNode node = jp.getCodec().readTree(jp); final HashMap<RMeasure, Double> data = new HashMap<>(); node.fieldNames().forEachRemaining(field -> { if (!field.equals("date")) { final RMeasure key = RMeasure.fromId(field); final double value = ((NumericNode) node.get(field)).doubleValue(); data.put(key, value); } }); return new RTimeSeriesData(ctx.parseDate(((TextNode) node.get("date")).textValue()), data); }
@Override public TimeSeriesItem deserialize(JsonParser jp, DeserializationContext ctx) throws IOException { final TreeNode node = jp.getCodec().readTree(jp); final Measure[] measure = new Measure[1]; final Double[] value = new Double[1]; node.fieldNames().forEachRemaining(field -> { if (!field.equals("date")) { measure[0] = Measure.fromId(field); value[0] = ((NumericNode) node.get(field)).doubleValue(); } }); return new TimeSeriesItem(ctx.parseDate(((TextNode) node.get("date")).textValue()), measure[0], value[0]); }
private List<String> parseNodeAsStringList(final TreeNode node) { try { return Arrays.asList(objectMapper.treeToValue(node, String[].class)); } catch(final JsonProcessingException e) { throw new IllegalStateException("Failed to parse JSON array", e); } }
@Override public List<Button> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { ObjectMapper mapper = (ObjectMapper) p.getCodec(); TreeNode treeNode = mapper.readTree(p); Button[] buttons; if (treeNode.asToken() == JsonToken.VALUE_STRING) { String rawJson = ((JsonNode) treeNode).asText(); buttons = mapper.readValue(rawJson, Button[].class); } else { buttons = mapper.readValue(p, Button[].class); } return buttons == null ? Collections.<Button>emptyList() : Arrays.asList(buttons); }
@SuppressWarnings("unchecked") private Bindings decodeTreeUsingHints(TreeNode decodedJsonTree, DecodingHints hints) { return hints.getModelType().map(modelType -> { try { return Bindings.hierarchy((Class<? super Object>) modelType, getObjectMapper().treeToValue(decodedJsonTree, modelType)); } catch (JsonProcessingException ignored) { return null; } }).orElse(new Bindings()); }
@Test public void treeNodeResponseView() throws Exception { ModelResponse<? extends Sushi> response = Bastion.request(FileRequest.post("http://localhost:9876/sushi", "classpath:/json/create_sushi_request.json")) .bind(Sushi.class) .call() .getResponse(); Optional<TreeNode> node = response.getView(TreeNode.class); assertThat(node).isNotEmpty(); }
@Test public void treeNodeResponseView_afterCall() throws Exception { Optional<TreeNode> responseNode = Bastion.request(FileRequest.post("http://localhost:9876/sushi", "classpath:/json/create_sushi_request.json")) .bind(Sushi.class) .call() .getView(TreeNode.class); assertThat(responseNode).isNotNull(); }
private void renderFieldContents(Object field) throws IOException { if (field == null) { generator.writeNull(); } else if (field instanceof Number) { renderNumberField((Number) field); } else if (field instanceof TreeNode) { generator.writeTree((TreeNode) field); } else if (field instanceof Tensor) { renderTensor(Optional.of((Tensor)field)); } else if (field instanceof JsonProducer) { generator.writeRawValue(((JsonProducer) field).toJson()); } else if (field instanceof Inspectable) { StringBuilder intermediate = new StringBuilder(); JsonRender.render((Inspectable) field, intermediate, true); generator.writeRawValue(intermediate.toString()); } else if (field instanceof StringFieldValue) { // This needs special casing as JsonWriter hides empty strings now generator.writeString(((StringFieldValue)field).getString()); } else if (field instanceof TensorFieldValue) { renderTensor(((TensorFieldValue)field).getTensor()); } else if (field instanceof FieldValue) { // the null below is the field which has already been written ((FieldValue) field).serialize(null, new JsonWriter(generator)); } else if (field instanceof JSONArray || field instanceof JSONObject) { // org.json returns null if the object would not result in // syntactically correct JSON String s = field.toString(); if (s == null) { generator.writeNull(); } else { generator.writeRawValue(s); } } else { generator.writeString(field.toString()); } }
@Override public GameMoveResult performAction(PlayerInGame playerInGame, String actionType, TreeNode data) { GroovyGames.GroovyAction action = actions.get(actionType); Object actionData = new ObjectMapper().convertValue(data, action.parameter); action.perform.call(new Action(null, playerInGame, actionData)); return new GameMoveResult("ok"); }
public <T> T treeToValue(TreeNode n, Class<T> valueType){ try { return mapper.treeToValue(n, valueType); } catch (JsonProcessingException e) { throw Throwables.propagate(e); } }