Java Code Examples for com.fasterxml.jackson.databind.JsonNode#toString()

The following examples show how to use com.fasterxml.jackson.databind.JsonNode#toString() . 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: JsonDiffer.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
public DiffResult checkNodes(JsonNode actual, JsonNode expected) {
  if (expected == null) {
    return new MisMatchDiffResult("null", actual.toString());
  }
  Function<JsonNode, DiffResult> expectedFunc = getExpectedFuncFor(expected);
  if (expectedFunc != null) {
    return expectedFunc.apply(actual);
  } else if (actual.isArray() && handlers.containsKey(handleArraysWith)) {
    ObjectNode config = arrayMatcherConfigAdapter.apply(expected.deepCopy());
    config.set("custom-matcher", jsn(handleArraysWith));
    return handlers.get(handleArraysWith).match(actual, config, this::checkNodes);
  } else if (expected.getNodeType() == actual.getNodeType()) {
    if (actual.isObject()) {
      return checkObject((ObjectNode) actual, (ObjectNode) expected);
    } else {
      return checkValue(actual, expected);
    }
  } else {
    return new MisMatchDiffResult(expected.toString(), actual.toString());
  }
}
 
Example 2
Source File: SubtypeResolutionIntegrationTest.java    From jsonschema-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void testIntegration() throws Exception {
    JacksonModule module = new JacksonModule(JacksonOption.FLATTENED_ENUMS_FROM_JSONVALUE);
    SchemaGeneratorConfig config = new SchemaGeneratorConfigBuilder(new ObjectMapper(), SchemaVersion.DRAFT_2019_09, OptionPreset.PLAIN_JSON)
            .with(Option.DEFINITIONS_FOR_ALL_OBJECTS, Option.NULLABLE_FIELDS_BY_DEFAULT)
            .with(module)
            .build();
    SchemaGenerator generator = new SchemaGenerator(config);
    JsonNode result = generator.generateSchema(TestClassForSubtypeResolution.class);

    String rawJsonSchema = result.toString();
    JSONAssert.assertEquals('\n' + rawJsonSchema + '\n',
            loadResource("subtype-integration-test-result.json"), rawJsonSchema, JSONCompareMode.STRICT);

    JsonSchema schemaForValidation = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V201909).getSchema(result);
    String jsonInstance = config.getObjectMapper().writeValueAsString(new TestClassForSubtypeResolution());

    Set<ValidationMessage> validationResult = schemaForValidation.validate(config.getObjectMapper().readTree(jsonInstance));
    if (!validationResult.isEmpty()) {
        Assert.fail("\n" + jsonInstance + "\n  " + validationResult.stream()
                .map(ValidationMessage::getMessage)
                .collect(Collectors.joining("\n  ")));
    }
}
 
Example 3
Source File: IntegrationTest.java    From jsonschema-generator with Apache License 2.0 6 votes vote down vote up
@Test
@Parameters
public void testIntegration(Class<?> rawTargetType) throws Exception {
    Swagger2Module module = new Swagger2Module();
    SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2019_09, OptionPreset.PLAIN_JSON)
            .with(Option.DEFINITIONS_FOR_ALL_OBJECTS)
            .with(Option.NONSTATIC_NONVOID_NONGETTER_METHODS, Option.FIELDS_DERIVED_FROM_ARGUMENTFREE_METHODS)
            .with(module);
    SchemaGenerator generator = new SchemaGenerator(configBuilder.build());
    JsonNode result = generator.generateSchema(rawTargetType);

    String rawJsonSchema = result.toString();
    JSONAssert.assertEquals('\n' + rawJsonSchema + '\n',
            loadResource("integration-test-result-" + rawTargetType.getSimpleName() + ".json"), rawJsonSchema,
            JSONCompareMode.STRICT);
}
 
Example 4
Source File: SparkTransformServer.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
protected String getJsonText(Http.Request request) {
    JsonNode tryJson = request.body().asJson();
    if (tryJson != null)
        return tryJson.toString();
    else
        return request.body().asText();
}
 
Example 5
Source File: JSONImportFileParser.java    From constellation with Apache License 2.0 5 votes vote down vote up
/**
 * Private function which constructs a line of data (based on column names)
 * starting at the selected node. The line of data will include all values
 * at the level of the supplied node as well as any nested values, using a 
 * prefix notation to identify the column name to use - as generated by the
 * function extractAllColNames. Both this function and the column extraction
 * functions need to stay in synch in relation to how column names are
 * constructed.
 * @param node Node to start line extraction from.
 * @param columnMap A map listing names of all available columns and
 * containing an index to the column number that should contain this info.
 * This map is built up from the list of extracted columns and allows data
 * at a given JSON path to be correctly matched with the column it belongs
 * in in the extracted line.
 * @param prefix Prefix string identifying the JSON path to the node from
 * the parent node of the list.
 * @param line The line to add content to, if null setup the line with
 * enough slots to cover all columns.
 * @return line of data. This is effectively an array of strings, one per
 * column.
 */
private String[] getLineContent(JsonNode node, Map<String, Integer> columnMap, String prefix, String[] line) {

    // Ensure the line is created if it wasn't already.
    if (line == null) {
        line = new String[columnMap.size()];
    }
    
    if (node.isArray()) {
        // The list is a list of lists, validation ensures lists are all of
        // equal size so just loop through and populate line with entries.
        int colNo = 0;
        for (final JsonNode listEntry : node) {
            line[colNo++] = listEntry.toString();
        }
    } else if (node.isObject()) {
        // Iterate over all child fields of the parewnt noode, for each one
        // determine if its a container Object node, if so recursively continue
        // to extract its values, if not, extract the value. Note that nested
        // lists will be converted to text, so if a list contains another list,
        // that second list is treated as a single object.
        for (Iterator<Entry<String, JsonNode>> it = node.fields(); it.hasNext();) {
            Map.Entry<String, JsonNode> entry = (Map.Entry<String, JsonNode>) it.next();

            if (entry.getValue().isObject()) {
                line = getLineContent(entry.getValue(), columnMap, (prefix + entry.getKey() + "."), line);
            }
            else {
                line[columnMap.get(prefix + entry.getKey())] = entry.getValue().toString().replaceAll("^\"|\"$", "");
            }
        }
    }
    return line;
}
 
Example 6
Source File: QueryResultWithKeysParser.java    From icure-backend with GNU General Public License v2.0 5 votes vote down vote up
private void parseResult(JsonParser jp) throws IOException {
	if (jp.nextToken() != JsonToken.START_OBJECT) {
		throw new DbAccessException("Expected data to start with an Object");
	}

	Map<String, String> errorFields = new HashMap<String, String>();
	// Issue #98: Can't assume order of JSON fields.
	while (jp.nextValue() != JsonToken.END_OBJECT) {
		String currentName = jp.getCurrentName();
		if (OFFSET_FIELD_NAME.equals(currentName)) {
			offset = jp.getIntValue();
		} else if (TOTAL_ROWS_FIELD_NAME.equals(currentName)) {
			totalRows = jp.getIntValue();
		} else if (ROWS_FIELD_NAME.equals(currentName)) {
			rows = new ArrayList<T>();
			ids = new ArrayList<>();
			keys = new ArrayList<>();
			parseRows(jp);
		} else if (UPDATE_SEQUENCE_NAME.equals(currentName)) {
			updateSequence = jp.getLongValue();
		} else {
			// Handle cloudant errors.
			errorFields.put(jp.getCurrentName(), jp.getText());
		}
	}

	if (!errorFields.isEmpty()) {
		JsonNode error = mapper.convertValue(errorFields, JsonNode.class);
		throw new DbAccessException(error.toString());
	}
}
 
Example 7
Source File: ExamplesTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
private void validateTemplate(JsonNode rootNode) throws JsonProcessingException {
    JsonNode parameters = rootNode.get("parameters");
    Map<String, Object> params = new HashMap<>();
    for (JsonNode parameter : parameters) {
        String name = parameter.get("name").asText();
        Object value;
        JsonNode valueNode = parameter.get("value");
        switch (valueNode.getNodeType()) {
            case NULL:
                value = null;
                break;
            case NUMBER:
            case BOOLEAN:
                value = valueNode.toString();
                break;
            case STRING:
                value = valueNode.asText();
                break;
            default:
                throw new RuntimeException("Unsupported JSON type " + valueNode.getNodeType());
        }
        params.put(name, value);
    }
    for (JsonNode object : rootNode.get("objects")) {
        String s = new YAMLMapper().enable(YAMLGenerator.Feature.MINIMIZE_QUOTES).enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(object);
        Matcher matcher = PARAMETER_PATTERN.matcher(s);
        StringBuilder sb = new StringBuilder();
        int last = 0;
        while (matcher.find()) {
            sb.append(s, last, matcher.start());
            String paramName = matcher.group(1);
            sb.append(params.get(paramName));
            last = matcher.end();
        }
        sb.append(s.substring(last));
        String yamlContent = sb.toString();
        validate(yamlContent);
    }
}
 
Example 8
Source File: TextFieldTransformator.java    From SkaETL with Apache License 2.0 5 votes vote down vote up
public void apply(String idProcess, ParameterTransformation parameterTransformation, ObjectNode jsonValue) {
    JsonNode at = at(parameterTransformation.getKeyField(), jsonValue);
    String valueToFormat = at.getNodeType() == JsonNodeType.OBJECT ? at.toString() : at.asText();
    if (StringUtils.isNotBlank(valueToFormat)) {
        put(jsonValue, parameterTransformation.getKeyField() + "_text", valueToFormat);
        remove(jsonValue,parameterTransformation.getKeyField());
    }
}
 
Example 9
Source File: ModelFieldPathsJSONDeserializer.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public ModelFieldPaths deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
	Set<PathChoice> choices = new HashSet<PathChoice>();
       ObjectCodec oc = jsonParser.getCodec();
       JsonNode node = oc.readTree(jsonParser);
       TextNode id = (TextNode)node.get(ID);
       TextNode name = (TextNode)node.get(NAME);
       TextNode queryFieldName = (TextNode)node.get(QUERY_FIELD_NAME);
      // TextNode entity = (TextNode)node.get(ENTITY);
       ArrayNode choicesJson = (ArrayNode) node.get(CHOICES);
       if(queryFieldName==null){
       	throw new JsonProcessingExceptionImpl("Error parsoing the field choices: The "+QUERY_FIELD_NAME+" must be valorized for each field"+node.toString());
       }
       if(choicesJson!=null && id!=null){
       	for(int i=0; i<choicesJson.size(); i++){
       		PathChoice pc = deserializePath(choicesJson.get(i));
       		if(pc!=null){
           		choices.add(pc);
       		}
       	}
       	IModelField field = modelStructure.getField(id.textValue());
       	IQueryField qf = getQueryField(queryFieldName.textValue());
       	
           if(field==null){
           	throw new JsonProcessingExceptionImpl("Error parsoing the field choices: can not find the field with id"+name.textValue()+" and name "+id.textValue()+" in the model structure");
           }
           
           if(qf==null){
           	return null;
           	//throw new FieldNotAttendInTheQuery("Error parsoing the field choices: can not find the field "+queryFieldName.textValue()+"in the model query");
           }
       	

       	return new ModelFieldPaths(qf,field, choices, true);
       }
       throw new JsonProcessingExceptionImpl("Can not deserialize the ModelFieldPaths. The mandatory fields are name and paths "+node.toString());
}
 
Example 10
Source File: ModelFieldPathsJSONDeserializer.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
public Relationship deserializeRelationship(JsonNode node) throws  JsonProcessingException {
       TextNode sourceId = (TextNode)node.get(RelationJSONSerializer.SOURCE_ID);
       TextNode targetId = (TextNode)node.get(RelationJSONSerializer.TARGET_ID);
       TextNode relationId = (TextNode)node.get(RelationJSONSerializer.RELATIONSHIP_ID);
       if(relationId!=null){
       	return getRelationship(relationId.textValue(), sourceId, targetId);
       }else{
       	throw new JsonProcessingExceptionImpl("The relation name is mandatory in the relation definition "+node.toString());
       }
}
 
Example 11
Source File: ModelConversion.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
private static String textOrJson(JsonNode samplingperiodNode) {
    String value = null;
    
    if (!samplingperiodNode.isMissingNode()) {
        value = samplingperiodNode.textValue();
        if (value == null) {
            value = samplingperiodNode.toString();
        }
    }
    return value;
}
 
Example 12
Source File: Input.java    From zentity with Apache License 2.0 5 votes vote down vote up
/**
 * Parse and validate the entity model from the 'model' field of the request body.
 *
 * @param requestBody The request body.
 * @return The parsed "model" field from the request body, or an object from ".zentity-models" index.
 * @throws IOException
 * @throws ValidationException
 */
public static Model parseEntityModel(JsonNode requestBody) throws IOException, ValidationException {
    if (!requestBody.has("model"))
        throw new ValidationException("The 'model' field is missing from the request body while 'entity_type' is undefined.");
    JsonNode model = requestBody.get("model");
    if (!model.isObject())
        throw new ValidationException("Entity model must be an object.");
    return new Model(model.toString());
}
 
Example 13
Source File: Config.java    From digdag with Apache License 2.0 5 votes vote down vote up
private String jsonSample(JsonNode value)
{
    String json = value.toString();
    if (json.length() < 100) {
        return json;
    }
    else {
        return json.substring(0, 97) + "...";
    }
}
 
Example 14
Source File: DescribeTableUnmarshaller.java    From bce-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
public GetTableResponse unmarshall(InputStream inputStream)
        throws Exception {
    String streamContents = Unmarshallers.readStreamContents(inputStream);

    JsonNode root = JsonUtils.jsonNodeOf(streamContents);
    if (!root.isObject()) {
        throw new BceClientException("input json object:"
                                           + root.toString()
                                           + " is not an object");
    }

    JsonNode tableObj = root;
    JsonNode attrListObj = tableObj.get(MolaDbConstants.JSON_ATTRIBUTE_DEFINITIONS);
    List<AttributeDefinition> attrDef = this.parseAttributesDefinistion(attrListObj);

    JsonNode keySchemaNode = tableObj.get(MolaDbConstants.JSON_KEY_SCHEMA);
    this.parseKeySchema(keySchemaNode, result);

    JsonNode provisionNode = tableObj.get(MolaDbConstants.JSON_PROVISION_THROUGHPUT);
    this.parseProvision(provisionNode, result);

    result.setAttributeDefinitions(attrDef);
    String time = tableObj.get(MolaDbConstants.JSON_CREATE_DATE_TIME).asText();
    DateFormat formarter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    Date date = formarter.parse(time);
    result.setCreationDateTime(date);
    result.setItemCount(tableObj.get(MolaDbConstants.JSON_ITEM_COUNT).asLong());
    result.setTableName(tableObj.get(MolaDbConstants.JSON_TABLENAME).asText());
    result.setTableStatus(tableObj.get(MolaDbConstants.JSON_TABLE_STATUS).asText());
    result.setTableSizeInBytes(tableObj.get(MolaDbConstants.JSON_TABLE_SIZE_IN_B).asLong());
    return result;
}
 
Example 15
Source File: SparkTransformServer.java    From DataVec with Apache License 2.0 5 votes vote down vote up
protected String getJsonText() {
    JsonNode tryJson = request().body().asJson();
    if (tryJson != null)
        return tryJson.toString();
    else
        return request().body().asText();
}
 
Example 16
Source File: HoodieJsonPayload.java    From hudi with Apache License 2.0 5 votes vote down vote up
private String getFieldFromJsonOrFail(String field) throws IOException {
  JsonNode node = new ObjectMapper().readTree(getJsonData());
  if (!node.has(field)) {
    throw new HoodieException("Field :" + field + " not found in payload => " + node.toString());
  }
  return node.get(field).textValue();
}
 
Example 17
Source File: WebCampaign.java    From bidder with Apache License 2.0 4 votes vote down vote up
/**
 * Handles the request from the HTTP handler in RTBServer.java
 * 
 * @param request
 *            HttpServlet. The request used to get to this handler.
 * @param in
 *            InputStream. The POST body.
 * @return String. The JSON return (A map) in String form.
 * @throws Exception
 *             on JSON errors.
 */
public String handler(HttpServletRequest request, InputStream in) throws Exception {
	/**
	 * Use jackson to read the content, then use gson to turn it into a map.
	 */
	ObjectMapper mapper = new ObjectMapper();
	JsonNode rootNode = mapper.readTree(in);
	String data = rootNode.toString();

	Map r = new HashMap();
	Map m = mapper.readValue(data, Map.class);
	String cmd = (String) m.get("command");
	if (cmd == null) {
		m.put("error", "No command given");
		m.put("original", data);
		return getString(cmd);
	}

	if (cmd.equals("login")) {
		return doLogin(request, m);
	}

	if (cmd.equals("loginAdmin")) {
		return getAdmin(m);
	}

	if (cmd.equals("showCreative")) {
		return showCreative(m);
	}

	if (cmd.equals("stub")) {
		return doNewCampaign(m);
	}

	if (cmd.equals("deletecampaign")) {
		return doDeleteCampaign(m);
	}
	if (cmd.equals("startcampaign")) {
		return startCampaign(m);
	}
	if (cmd.equals("stopcampaign")) {
		return stopCampaign(m);
	}
	if (cmd.equals("updatecampaign")) {
		return updateCampaign(m);
	}

	if (cmd.equalsIgnoreCase("executeCommand")) {
		return doExecute(m);
	}

	if (cmd.equalsIgnoreCase("dumpFile")) {
		return dumpFile(m);
	}


	if (cmd.equalsIgnoreCase("reloadBidders")) {
		return reloadBidders(m);
	}
	if (cmd.equalsIgnoreCase("saveConfig")) {
		return saveConfig(m);
	}
	if (cmd.equalsIgnoreCase("writeDeletedCampaigns")) {
		return writeDeletedCampaigns(m);
	}

	m.put("error", true);
	m.put("message", "No such command: " + cmd);
	m.put("original", data);
	return getString(cmd);
}
 
Example 18
Source File: PageSourceEntity.java    From gravitee-management-rest-api with Apache License 2.0 4 votes vote down vote up
public void setConfiguration(JsonNode jsonNode) {
    this.configuration = jsonNode.toString();
}
 
Example 19
Source File: BratAnnotationEditor.java    From webanno with Apache License 2.0 4 votes vote down vote up
private Optional<String> bratRenderCommand(CAS aCas)
{
    LOG.trace("[{}][{}] bratRenderCommand", getMarkupId(), vis.getMarkupId());
    
    StopWatch timer = new StopWatch();
    timer.start();
    
    GetDocumentResponse response = new GetDocumentResponse();
    render(response, aCas);
    String json = toJson(response);
    
    // By default, we do a full rendering...
    RenderType renderType = FULL;
    String cmd = "renderData";
    String data = json;
    JsonNode diff;
    String diffJsonStr = null;
    
    // Here, we try to balance server CPU load against network load. So if we have a chance
    // of significantly reducing the data sent to the client via a differential update, then
    // we try that. However, if it is pretty obvious that we won't save a lot, then we will
    // not even try. I.e. we apply some heuristics to see if large parts of the editor have
    // changed.
    AnnotatorState aState = getModelObject();
    boolean tryDifferentialUpdate = lastRenderedWindowStart >= 0
            // Check if we did a far scroll or switch pages
            && Math.abs(lastRenderedWindowStart - aState.getWindowBeginOffset()) < aState
                    .getPreferences().getWindowSize() / 3;

    if (tryDifferentialUpdate) {
        // ... try to render diff
        JsonNode current = null;
        JsonNode previous = null;
        try {
            ObjectMapper mapper = JSONUtil.getObjectMapper();
            current = mapper.readTree(json);
            previous = lastRenderedJson != null ? mapper.readTree(lastRenderedJson) : null;
        }
        catch (IOException e) {
            LOG.error("Unable to generate diff, falling back to full render.", e);
            // Fall-through
        }
        
        if (previous != null && current != null) {
            diff = JsonDiff.asJson(previous, current);
            diffJsonStr = diff.toString();
            
            if (diff instanceof ArrayNode && ((ArrayNode) diff).isEmpty()) {
                // No difference? Well, don't render at all :)
                renderType = SKIP;
            }
            else if (diffJsonStr.length() < json.length()) {
                // Only sent a patch if it is smaller than sending the full data. E.g. when
                // switching pages, the patch usually ends up being twice as large as the full
                // data.
                cmd = "renderDataPatch";
                data = diffJsonStr;
                renderType = DIFFERENTIAL;
            }
            
            // LOG.info("Diff: " + diff);
            // LOG.info("Full: {} Patch: {} Diff time: {}", json.length(), diff.length(),
            // timer);
        }
    }
    
    // Storing the last rendered JSON as string because JsonNodes are not serializable.
    lastRenderedJson = json;
    lastRenderedWindowStart = aState.getWindowBeginOffset();
    
    timer.stop();

    metrics.renderComplete(renderType, timer.getTime(), json, diffJsonStr);
    
    if (SKIP.equals(renderType)) {
        return Optional.empty();
    }
    
    return Optional.of("Wicket.$('" + vis.getMarkupId() + "').dispatcher.post('" + cmd + "', ["
            + data + "]);");
}
 
Example 20
Source File: JsonHelper.java    From Tenable.io-SDK-for-Java with MIT License 2 votes vote down vote up
/**
 * Convert a JsonNode to its string representation.
 *
 * @param json the json
 * @return  the serialized JSON string
 */
public String stringify( JsonNode json ) {
    return json.toString();
}