@Override public <T> T config(TypeRef<? extends T> type, String prefix) { JsonNode child = findChild(prefix); JavaType jacksonType = typeFactory.constructType(type.getType()); try { return mapper.readValue(new TreeTraversingParser(child, mapper), jacksonType); } // TODO: implement better exception handling. See ConfigurationFactory // in Dropwizard for inspiration catch (IOException e) { throw new RuntimeException("Error creating config", e); } }
private Filter deserializeObject(final JsonParser p, final DeserializationContext c) throws IOException { final ObjectNode object = (ObjectNode) p.readValueAs(JsonNode.class); final JsonNode typeNode = object.remove("type"); if (typeNode == null) { throw c.mappingException("Expected 'type' field"); } if (!typeNode.isTextual()) { throw c.mappingException("Expected 'type' to be string"); } final String type = typeNode.asText(); final Class<? extends Filter> cls = typeNameMapping.get(type); if (cls == null) { throw c.mappingException("No such type: " + type); } // use tree traversing parser to operate on the node (without 'type') again. final TreeTraversingParser parser = new TreeTraversingParser(object, p.getCodec()); return parser.readValueAs(cls); }
@Override public Object deserializeTypedFromObject(final JsonParser jp, final DeserializationContext ctxt) throws IOException { JsonNode node = jp.readValueAsTree(); NamedDefinition res = NamedProviders.get((Class<NamedDefinition>) _baseType.getRawClass(), node.get("type").asText()); if (res == null) { return null; } JavaType type = SimpleType.construct(res.getClass()); JsonParser jsonParser = new TreeTraversingParser(node, jp.getCodec()); if (jsonParser.getCurrentToken() == null) { jsonParser.nextToken(); } JsonDeserializer<Object> deser = ctxt.findContextualValueDeserializer(type, _property); return deser.deserialize(jsonParser, ctxt); }
@Override public HashMap<String, ModelUser> getMembersRecursive() { String requestUrl = new StringBuilder(dlManagerConfig.getServiceUrl()).append(GET_MEMBERS_RECURSIVE_URI). append(dlManagerConfig.getTargetDl()).append("/").append(dlManagerConfig.getExecutor()).append("/"). append(dlManagerConfig.getToken()).toString(); //ignore self signed SSL certificates TrustAllCertificates.install(); try { URL url = new URL(requestUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); BufferedReader buf = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder response = new StringBuilder(); String line; while ((line = buf.readLine()) != null) { response.append(line); } logger.debug("Github API Response status: {}", response); HashMap<String, ModelUser> userMap = new HashMap<String, ModelUser>(); ArrayNode responseArray = (ArrayNode) new ObjectMapper().readTree(response.toString()); for (JsonNode record : responseArray) { ModelUser user = new ObjectMapper().readValue(new TreeTraversingParser(record), ModelUser.class); userMap.put(user.getSamAccountName(), user); } connection.disconnect(); logger.info("Success: DL Manager API for recursively getting members"); return userMap; } catch (IOException e) { // TODO Auto-generated catch block logger.info("Fail: DL Manager API for recursively getting members"); e.printStackTrace(); } return null; }
private ConfigT readConfig() { final Collection<String> configs = yamlConfigReader.readConfigs(); final JsonNode mergedJsonNode = configs.stream() .filter(s -> !Strings.isNullOrEmpty(s)) .map(configSubstitutor::substitute) .map(s -> wrapChecked(() -> objectMapper.readValue(s, JsonNode.class))) .reduce(YamlConfigContext::mergeJsonNodes) .orElse(objectMapper.createObjectNode()); return wrapChecked(() -> objectMapper.readValue(new TreeTraversingParser(mergedJsonNode), configClass())); }
@Override public <T> T config(Class<T> type, String prefix) { JsonNode child = findChild(prefix); try { return mapper.readValue(new TreeTraversingParser(child, mapper), type); } // TODO: implement better exception handling. See ConfigurationFactory // in Dropwizard for inspiration catch (IOException e) { throw new RuntimeException("Error creating config", e); } }
protected <T> T readValue(Class<T> type, ObjectMapper mapper, String yml) throws IOException { YAMLParser parser = new YAMLFactory().createParser(yml); JsonNode node = mapper.readTree(parser); assertNotNull(node); return mapper.readValue(new TreeTraversingParser(node), type); }
protected <T> T readValue(Class<T> type, ObjectMapper mapper, String json) throws IOException { JsonParser parser = new JsonFactory().createParser(json); JsonNode node = mapper.readTree(parser); assertNotNull(node); return mapper.readValue(new TreeTraversingParser(node), type); }
private ErrorListDto createExcelParsingError(InvalidFormatException invalidFormatException) { TreeTraversingParser processor = (TreeTraversingParser) invalidFormatException.getProcessor(); //Create Excel Parsing Error. Just the first will be returned String domainObject = ((Class<?>) invalidFormatException.getPath().get(0).getFrom()) .getSimpleName(); String property = processor.getCurrentName(); if (property == null) { property = invalidFormatException.getPath().get(0).getFieldName(); } String invalidValue = (String)invalidFormatException.getValue(); String messageKey = "global.error.import.excel-parsing-error"; return new ErrorListDto(new ErrorDto(domainObject, messageKey,invalidValue, property)); }
private ManagedDataSourceFactory createDataSourceFactory(Injector injector) { Class<? extends ManagedDataSourceFactory> factoryType = delegateFactoryType(injector); JavaType jacksonType = TypeFactory.defaultInstance().constructType(factoryType); ObjectMapper mapper = createObjectMapper(injector); JsonNode nodeWithType = jsonNodeWithType(getTypeLabel(factoryType)); try { return mapper.readValue(new TreeTraversingParser(nodeWithType, mapper), jacksonType); } catch (IOException e) { throw new BootiqueException(1, "Deserialization of JDBC DataSource configuration failed.", e); } }
/** * This method should be used only in tests because it processes json data * stored in memory as a tree rather than as token stream that could be processed * directly from a file. */ public static JsonNode extract(SubsetSelection objpaths, JsonNode input) throws IOException, TypedObjectExtractionException { TokenSequenceProvider tsp = createTokenSequenceProvider(new TreeTraversingParser(input)); JsonTreeGenerator jgen = new JsonTreeGenerator(mapper); extractFields(objpaths, tsp, jgen); tsp.close(); jgen.close(); return jgen.getTree(); }
@Override public IndexerConfiguration loadConfiguration() throws IOException { FileReader reader = new FileReader(configFile); final JsonNode node = mapper.readTree(yamlFactory.createParser(reader)); final IndexerConfiguration config = mapper.readValue(new TreeTraversingParser(node), IndexerConfiguration.class); // Close the file reader reader.close(); return config; }
@Override public void setSource(JsonNode node) { this.parser = new TreeTraversingParser(node); }
public JsonParser asParser(){ Preconditions.checkArgument(this.root != null, "Attempted to grab JSONOptions as Parser when no root node was stored. You can only convert non-opaque JSONOptions values to parsers."); return new TreeTraversingParser(root); }
private AsyncFuture<Void> handleVersion1(final JsonNode tree) throws ConsumerSchemaValidationException { final JsonMetric metric; try { metric = new TreeTraversingParser(tree, mapper).readValueAs(JsonMetric.class); } catch (IOException e) { throw new ConsumerSchemaValidationException("Invalid metric", e); } if (metric.getValue() == null) { throw new ConsumerSchemaValidationException( "Metric must have a value but this metric has a null value: " + metric); } if (metric.getTime() == null) { throw new ConsumerSchemaValidationException("time: field must be defined: " + tree); } if (metric.getTime() <= 0) { throw new ConsumerSchemaValidationException( "time: field must be a positive number: " + tree); } if (metric.getKey() == null) { throw new ConsumerSchemaValidationException("key: field must be defined: " + tree); } final Map<String, String> tags = new HashMap<>(metric.getAttributes()); if (metric.getHost() != null) { tags.put(HOST_TAG, metric.getHost()); } final Map<String, String> resource = new HashMap<>(metric.getResource()); final Series series = Series.of(metric.getKey(), tags, resource); final Point p = new Point(metric.getTime(), metric.getValue()); final List<Point> points = ImmutableList.of(p); reporter.reportMessageDrift(clock.currentTimeMillis() - p.getTimestamp()); AsyncFuture<Ingestion> ingestionFuture = ingestion.write(new Ingestion.Request(series, MetricCollection.points(points))); // Return Void future, to not leak unnecessary information from the backend but just // allow monitoring of when the consumption is done. return ingestionFuture.directTransform(future -> (Void) null); }
public JsonParser treeAsTokens(TreeNode paramTreeNode) { return new TreeTraversingParser((JsonNode)paramTreeNode, this); }
private T build(JsonNode node, String filename) throws IOException, ConfigurationException { T config = mapper.readValue(new TreeTraversingParser(node), configType); validate(filename, config); return config; }
@Override public JsonParser treeAsTokens(TreeNode n) { return new TreeTraversingParser((JsonNode) n, this); }