1
+ package org .cyclonedx .util .serializer ;
2
+
3
+ import java .io .IOException ;
4
+
5
+ import com .fasterxml .jackson .core .JsonGenerator ;
6
+ import com .fasterxml .jackson .databind .SerializerProvider ;
7
+ import com .fasterxml .jackson .databind .ser .std .StdSerializer ;
8
+ import com .fasterxml .jackson .dataformat .xml .ser .ToXmlGenerator ;
9
+ import org .cyclonedx .Version ;
10
+ import org .cyclonedx .model .Hash ;
11
+ import org .cyclonedx .model .Hash .Algorithm ;
12
+ import org .cyclonedx .model .VersionFilter ;
13
+
14
+ public class HashSerializer
15
+ extends StdSerializer <Hash >
16
+ {
17
+ private final Version version ;
18
+
19
+ public HashSerializer (final Version version ) {
20
+ this (Hash .class , version );
21
+ }
22
+
23
+ public HashSerializer (final Class <Hash > t , final Version version ) {
24
+ super (t );
25
+ this .version = version ;
26
+ }
27
+
28
+ @ Override
29
+ public void serialize (
30
+ final Hash hash , final JsonGenerator gen , final SerializerProvider provider ) throws IOException
31
+ {
32
+ if (!shouldSerializeField (hash .getAlgorithm ())) {
33
+ return ;
34
+ }
35
+
36
+ if (gen instanceof ToXmlGenerator ) {
37
+ serializeXml ((ToXmlGenerator ) gen , hash );
38
+ }
39
+ else {
40
+ serializeJson (gen , hash );
41
+ }
42
+ }
43
+
44
+ private void serializeXml (final ToXmlGenerator toXmlGenerator , final Hash hash ) throws IOException {
45
+ toXmlGenerator .writeStartObject ();
46
+
47
+ toXmlGenerator .setNextIsAttribute (true );
48
+ toXmlGenerator .writeFieldName ("alg" );
49
+ toXmlGenerator .writeString (hash .getAlgorithm ());
50
+ toXmlGenerator .setNextIsAttribute (false );
51
+
52
+ toXmlGenerator .setNextIsUnwrapped (true );
53
+ toXmlGenerator .writeStringField ("" , hash .getValue ());
54
+
55
+ toXmlGenerator .writeEndObject ();
56
+ }
57
+
58
+ private void serializeJson (final JsonGenerator gen , final Hash hash )
59
+ throws IOException
60
+ {
61
+ gen .writeStartObject ();
62
+ gen .writeStringField ("alg" , hash .getAlgorithm ());
63
+ gen .writeStringField ("content" , hash .getValue ());
64
+ gen .writeEndObject ();
65
+ }
66
+
67
+ @ Override
68
+ public Class <Hash > handledType () {
69
+ return Hash .class ;
70
+ }
71
+
72
+ private boolean shouldSerializeField (String value ) {
73
+ try {
74
+ Algorithm algorithm = Algorithm .fromSpec (value );
75
+ VersionFilter filter = algorithm .getClass ().getField (algorithm .name ()).getAnnotation (VersionFilter .class );
76
+ return filter == null || filter .value ().getVersion () <= version .getVersion ();
77
+ }
78
+ catch (NoSuchFieldException e ) {
79
+ return false ;
80
+ }
81
+ }
82
+ }
0 commit comments