CycloneDX / cyclonedx-core-java

CycloneDX SBOM Model and Utils for Creating and Validating BOMs
https://cyclonedx.org/
Apache License 2.0
81 stars 59 forks source link

BomJsonGenerator.toJsonString() unexpectedly replaces all new lines in Strings with spaces #394

Closed benken-parasoft closed 3 months ago

benken-parasoft commented 5 months ago

If I serialize a org.cyclonedx.model.Bom to JSON using BomJsonGenerator.toJsonString() then I unexpectedly lose newlines in various strings, like license and copyright text where new lines are especially important.

I tracked down the problem to org.cyclonedx.util.serializer.TrimStringSerializer. This serializer is not just trimming but is also replacing carriage return, line feed, and tab characters with a space. These should be preserved in the JSON. Jackson will correctly escape such characters, like encoding newlines as '\n'.

In contrast, BomXmlGenerator is fine. The XML version has newlines correctly preserved in the XML.

I am currently working around the issue as follows:

    private static void removeTrimStringSerializer(BomJsonGenerator jsonGenerator) {
        ObjectMapper mapper = ((AbstractBomJsonGenerator) jsonGenerator).getMapper();
        SerializerFactory newSerializerFactory = BeanSerializerFactory.instance;
        SerializationConfig serializationConfig = mapper.getSerializationConfig();
        JavaType javaType = serializationConfig.constructType(String.class);
        BeanDescription beanDesc = serializationConfig.introspect(javaType);
        SerializerFactoryConfig serializerFactoryConfig = ((BasicSerializerFactory) mapper.getSerializerFactory()).getFactoryConfig();
        for (Serializers serializers : serializerFactoryConfig.serializers()) {
            JsonSerializer<?> stringSerializer = serializers.findSerializer(serializationConfig, javaType, beanDesc);
            if (!(stringSerializer instanceof TrimStringSerializer)) {
                newSerializerFactory = newSerializerFactory.withAdditionalSerializers(serializers);
            }
        }
        mapper.setSerializerFactory(newSerializerFactory);
    }
nscuro commented 3 months ago

Appears to be a duplicate of ~#394~ (Edit: #135).

benken-parasoft commented 3 months ago

Appears to be a duplicate of https://github.com/CycloneDX/cyclonedx-core-java/issues/394

A duplicate of itself? This is a real issue. Copyright and license text can be large with a lot of newlines. BomJsonGenerator strips them out! In contrast, BomXmlGenerator is fine and preserves everything.

nscuro commented 3 months ago

Too much copy-pasting. Meant to link to #135.

benken-parasoft commented 3 months ago

Too much copy-pasting. Meant to link to https://github.com/CycloneDX/cyclonedx-core-java/issues/135.

Thanks! I'll follow this one instead.