1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.mycore.common.content;
20
21 import java.io.ByteArrayInputStream;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.UnsupportedEncodingException;
25 import java.security.MessageDigest;
26
27 import org.jdom2.output.Format;
28 import org.mycore.common.MCRConstants;
29 import org.mycore.common.config.MCRConfiguration2;
30 import org.mycore.common.content.streams.MCRMD5InputStream;
31
32
33
34
35
36
37
38 public abstract class MCRXMLContent extends MCRContent {
39
40
41
42
43
44
45 protected static Format defaultFormat;
46
47 static {
48 boolean prettyXML = MCRConfiguration2.getBoolean("MCR.IFS2.PrettyXML").orElse(true);
49 defaultFormat = prettyXML ? Format.getPrettyFormat().setIndent(" ") : Format.getRawFormat();
50 defaultFormat.setEncoding(MCRConstants.DEFAULT_ENCODING);
51 }
52
53
54 protected Format format = defaultFormat;
55
56 public MCRXMLContent() {
57 try {
58 this.setEncoding(MCRConstants.DEFAULT_ENCODING);
59 } catch (UnsupportedEncodingException e) {
60 throw new RuntimeException(e);
61 }
62 }
63
64
65
66
67
68
69 public void setFormat(Format format) {
70 this.format = format;
71 }
72
73 @Override
74 public InputStream getInputStream() throws IOException {
75 return new ByteArrayInputStream(asByteArray());
76 }
77
78 @Override
79 public MCRContent ensureXML() {
80 return this;
81 }
82
83 @Override
84 public String getMimeType() throws IOException {
85 return super.getMimeType() == null ? "text/xml" : super.getMimeType();
86 }
87
88 @Override
89 public long length() throws IOException {
90 return asByteArray().length;
91 }
92
93 @Override
94 public String getETag() throws IOException {
95 MessageDigest md5Digest = MCRMD5InputStream.buildMD5Digest();
96 byte[] byteArray = asByteArray();
97 md5Digest.update(byteArray, 0, byteArray.length);
98 byte[] digest = md5Digest.digest();
99 String md5String = MCRMD5InputStream.getMD5String(digest);
100 return '"' + md5String + '"';
101 }
102
103 @Override
104 public void setEncoding(String encoding) throws UnsupportedEncodingException {
105 super.setEncoding(encoding);
106 this.format = format.clone();
107 format.setEncoding(encoding);
108 }
109 }