View Javadoc
1   /*
2    * This file is part of ***  M y C o R e  ***
3    * See http://www.mycore.de/ for details.
4    *
5    * MyCoRe is free software: you can redistribute it and/or modify
6    * it under the terms of the GNU General Public License as published by
7    * the Free Software Foundation, either version 3 of the License, or
8    * (at your option) any later version.
9    *
10   * MyCoRe is distributed in the hope that it will be useful,
11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   * GNU General Public License for more details.
14   *
15   * You should have received a copy of the GNU General Public License
16   * along with MyCoRe.  If not, see <http://www.gnu.org/licenses/>.
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  
26  import org.mycore.common.MCRConstants;
27  
28  /**
29   * Reads MCRContent from a String's text.
30   * 
31   * @author Frank L\u00FCtzenkichen
32   */
33  public class MCRStringContent extends MCRContent {
34  
35      private String text;
36  
37      private byte[] bytes;
38  
39      /**
40       * Reads content from the given string, 
41       */
42      public MCRStringContent(String text) {
43          this.text = text;
44          try {
45              setEncoding(MCRConstants.DEFAULT_ENCODING);
46          } catch (UnsupportedEncodingException e) {
47              throw new RuntimeException(e);
48          }
49      }
50  
51      /** 
52       * Sets the character encoding to use when transforming the text to a byte stream.
53       * By default, this is {@link MCRConstants#DEFAULT_ENCODING}.
54       */
55      @Override
56      public void setEncoding(String encoding) throws UnsupportedEncodingException {
57          super.setEncoding(encoding);
58          this.bytes = asByteArray();
59      }
60  
61      @Override
62      public InputStream getInputStream() throws IOException {
63          return new ByteArrayInputStream(asByteArray());
64      }
65  
66      @Override
67      public byte[] asByteArray() throws UnsupportedEncodingException {
68          return text.getBytes(encoding);
69      }
70  
71      public String asString() {
72          return text;
73      }
74  
75      @Override
76      public long length() throws IOException {
77          return bytes.length;
78      }
79  
80      @Override
81      public long lastModified() throws IOException {
82          return -1;
83      }
84  
85      @Override
86      public String getETag() throws IOException {
87          String eTag = getSimpleWeakETag(getSystemId(), length(), lastModified());
88          return eTag == null ? null : eTag.substring(2);
89      }
90  }