22
22
import lombok .RequiredArgsConstructor ;
23
23
import org .apache .commons .lang3 .ArrayUtils ;
24
24
import org .apache .commons .lang3 .StringUtils ;
25
+ import org .slf4j .Logger ;
26
+ import org .slf4j .LoggerFactory ;
27
+ import org .springframework .http .MediaType ;
25
28
29
+ import java .nio .charset .Charset ;
26
30
import java .nio .charset .StandardCharsets ;
27
31
28
32
@ Getter
29
33
@ RequiredArgsConstructor (access = AccessLevel .PRIVATE )
30
34
public class DownloadResult {
35
+ private static final Logger LOG = LoggerFactory .getLogger (DownloadResult .class );
36
+
31
37
private final Code code ;
32
38
private final byte [] data ;
33
39
private final String contentType ;
40
+ private final Charset charset ;
34
41
35
42
public static DownloadResult failed (Code code ) {
36
- return new DownloadResult (code , ArrayUtils .EMPTY_BYTE_ARRAY , StringUtils .EMPTY );
43
+ return new DownloadResult (
44
+ code ,
45
+ ArrayUtils .EMPTY_BYTE_ARRAY ,
46
+ StringUtils .EMPTY ,
47
+ StandardCharsets .UTF_8
48
+ );
37
49
}
38
50
39
51
public static DownloadResult succeeded (byte [] data , String contentType ) {
40
- return new DownloadResult (Code .SUCCESS , data , contentType );
52
+ Charset charset = extractCharset (contentType );
53
+ if (charset == null ) {
54
+ charset = StandardCharsets .UTF_8 ;
55
+ }
56
+ return new DownloadResult (Code .SUCCESS , data , contentType , charset );
41
57
}
42
58
43
59
public boolean hasFailed () {
@@ -49,7 +65,7 @@ public boolean hasSucceeded() {
49
65
}
50
66
51
67
public String getDataAsString () {
52
- return new String (data , StandardCharsets . UTF_8 );
68
+ return new String (data , charset );
53
69
}
54
70
55
71
public enum Code {
@@ -62,4 +78,19 @@ public enum Code {
62
78
UNEXPECTED_ERROR ,
63
79
}
64
80
81
+ private static Charset extractCharset (String contentType ) {
82
+ try {
83
+ MediaType mediaType = MediaType .parseMediaType (contentType );
84
+ return mediaType .getCharset ();
85
+
86
+ } catch (IllegalArgumentException ex ) {
87
+ // MediaType.parseMediaType() might throw InvalidMediaTypeException.
88
+ // MediaType.getCharset() might throw IllegalArgumentException,
89
+ // IllegalCharsetNameException, or UnsupportedCharsetException.
90
+ // All of them are inherited from IllegalArgumentException, so we catch only this class
91
+ LOG .debug ("Couldn't extract charset from '{}': {}" , contentType , ex .getMessage ());
92
+ return null ;
93
+ }
94
+ }
95
+
65
96
}
0 commit comments