~ubuntu-branches/ubuntu/utopic/libjaudiotagger-java/utopic

« back to all changes in this revision

Viewing changes to src/org/jaudiotagger/tag/datatype/TextEncodedStringNullTerminated.java

  • Committer: Bazaar Package Importer
  • Author(s): Varun Hiremath, Damien Raude-Morvan, Varun Hiremath
  • Date: 2009-04-01 19:17:56 UTC
  • mfrom: (1.1.1 upstream)
  • Revision ID: james.westby@ubuntu.com-20090401191756-bygniim270guy7o1
Tags: 1.0.9-1
[ Damien Raude-Morvan ]
* New upstream release
* debian/watch: Use java.net repository (which contains new releases!)
* debian/control:
  - Build-Depends on default-jdk-builddep
  - Bump Standards-Version to 3.8.1 (no changes needed)
  - Change section to "java"
* debian/rules: use default-java as JAVA_HOME
* debina/orig-tar.{sh|excludes}: strip audio and others binary files from ZIP
* debian/build.xml:
  - compile with "nowarn" to keep build log readable
  - exclude LogFormatter from build (use com.sun classes)
* debian/ant.properties: new source directory is "src" in orig.tar.gz
* Add myself as Uploaders

[ Varun Hiremath ]
* Accept changes made by Damien Raude-Morvan (Closes: #522130)

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
package org.jaudiotagger.tag.datatype;
 
2
 
 
3
import org.jaudiotagger.tag.InvalidDataTypeException;
 
4
import org.jaudiotagger.tag.id3.AbstractTagFrameBody;
 
5
import org.jaudiotagger.tag.id3.valuepair.TextEncoding;
 
6
 
 
7
import java.nio.ByteBuffer;
 
8
import java.nio.CharBuffer;
 
9
import java.nio.charset.*;
 
10
 
 
11
/**
 
12
 * Represents a String whose size is determined by finding of a null character at the end of the String.
 
13
 * <p/>
 
14
 * The String itself might be of length zero (i.e just consist of the null character). The String will be encoded based
 
15
 * upon the text encoding of the frame that it belongs to.
 
16
 */
 
17
public class TextEncodedStringNullTerminated extends AbstractString
 
18
{
 
19
    /**
 
20
     * Creates a new TextEncodedStringNullTerminated datatype.
 
21
     *
 
22
     * @param identifier identifies the frame type
 
23
     */
 
24
    public TextEncodedStringNullTerminated(String identifier, AbstractTagFrameBody frameBody)
 
25
    {
 
26
        super(identifier, frameBody);
 
27
    }
 
28
 
 
29
    /**
 
30
     * Creates a new TextEncodedStringNullTerminated datatype, with value
 
31
     *
 
32
     * @param identifier
 
33
     * @param frameBody
 
34
     * @param value
 
35
     */
 
36
    public TextEncodedStringNullTerminated(String identifier, AbstractTagFrameBody frameBody, String value)
 
37
    {
 
38
        super(identifier, frameBody, value);
 
39
    }
 
40
 
 
41
    public TextEncodedStringNullTerminated(TextEncodedStringNullTerminated object)
 
42
    {
 
43
        super(object);
 
44
    }
 
45
 
 
46
    public boolean equals(Object obj)
 
47
    {
 
48
        if (obj instanceof TextEncodedStringNullTerminated == false)
 
49
        {
 
50
            return false;
 
51
        }
 
52
        return super.equals(obj);
 
53
    }
 
54
 
 
55
    /**
 
56
     * Read a string from buffer upto null character (if exists)
 
57
     * <p/>
 
58
     * Must take into account the text encoding defined in the Encoding Object
 
59
     * ID3 Text Frames often allow multiple strings seperated by the null char
 
60
     * appropriate for the encoding.
 
61
     *
 
62
     * @param arr    this is the buffer for the frame
 
63
     * @param offset this is where to start reading in the buffer for this field
 
64
     */
 
65
    public void readByteArray(byte[] arr, int offset) throws InvalidDataTypeException
 
66
    {
 
67
        int bufferSize = 0;
 
68
 
 
69
        logger.finer("Reading from array starting from offset:" + offset);
 
70
        int size = 0;
 
71
 
 
72
        //Get the Specified Decoder
 
73
        String charSetName = getTextEncodingCharSet();
 
74
        CharsetDecoder decoder = Charset.forName(charSetName).newDecoder();
 
75
 
 
76
        //We only want to load up to null terminator, data after this is part of different
 
77
        //field and it may not be possible to decode it so do the check before we do
 
78
        //do the decoding,encoding dependent.
 
79
        ByteBuffer buffer = ByteBuffer.wrap(arr, offset, arr.length - offset);
 
80
        int endPosition = 0;
 
81
 
 
82
        //Latin-1 and UTF-8 strings are terminated by a single-byte null,
 
83
        //while UTF-16 and its variants need two bytes for the null terminator.
 
84
        final boolean nullIsOneByte = (charSetName.equals(TextEncoding.CHARSET_ISO_8859_1) || charSetName.equals(TextEncoding.CHARSET_UTF_8));
 
85
 
 
86
        boolean isNullTerminatorFound = false;
 
87
        while (buffer.hasRemaining())
 
88
        {
 
89
            byte nextByte = buffer.get();
 
90
            if (nextByte == 0x00)
 
91
            {
 
92
                if (nullIsOneByte)
 
93
                {
 
94
                    buffer.mark();
 
95
                    buffer.reset();
 
96
                    endPosition = buffer.position() - 1;
 
97
                    logger.finest("Null terminator found starting at:" + endPosition);
 
98
 
 
99
                    isNullTerminatorFound = true;
 
100
                    break;
 
101
                }
 
102
                else
 
103
                {
 
104
                    // Looking for two-byte null
 
105
                    if (buffer.hasRemaining())
 
106
                    {
 
107
                        nextByte = buffer.get();
 
108
                        if (nextByte == 0x00)
 
109
                        {
 
110
                            buffer.mark();
 
111
                            buffer.reset();
 
112
                            endPosition = buffer.position() - 2;
 
113
                            logger.finest("UTF16:Null terminator found starting  at:" + endPosition);
 
114
                            isNullTerminatorFound = true;
 
115
                            break;
 
116
                        }
 
117
                        else
 
118
                        {
 
119
                            //Nothing to do, we have checked 2nd value of pair it was not a null terminator
 
120
                            //so will just start looking again in next invocation of loop
 
121
                        }
 
122
                    }
 
123
                    else
 
124
                    {
 
125
                        buffer.mark();
 
126
                        buffer.reset();
 
127
                        endPosition = buffer.position() - 1;
 
128
                        logger.warning("UTF16:Should be two null terminator marks but only found one starting at:" + endPosition);
 
129
 
 
130
                        isNullTerminatorFound = true;
 
131
                        break;
 
132
                    }
 
133
                }
 
134
            }
 
135
            else
 
136
            {
 
137
                //If UTF16, we should only be looking on 2 byte boundaries
 
138
                if (!nullIsOneByte)
 
139
                {
 
140
                    if (buffer.hasRemaining())
 
141
                    {
 
142
                        buffer.get();
 
143
                    }
 
144
                }
 
145
            }
 
146
        }
 
147
 
 
148
        if (isNullTerminatorFound == false)
 
149
        {
 
150
            throw new InvalidDataTypeException("Unable to find null terminated string");
 
151
        }
 
152
 
 
153
 
 
154
        logger.finest("End Position is:" + endPosition + "Offset:" + offset);
 
155
 
 
156
        //Set Size so offset is ready for next field (includes the null terminator)
 
157
        size = endPosition - offset;
 
158
        size++;
 
159
        if (!nullIsOneByte)
 
160
        {
 
161
            size++;
 
162
        }
 
163
        setSize(size);
 
164
 
 
165
        //Decode buffer if runs into problems should throw exception which we
 
166
        //catch and then set value to empty string. (We don't read the null terminator
 
167
        //because we dont want to display this)
 
168
        bufferSize = endPosition - offset;
 
169
        logger.finest("Text size is:" + bufferSize);
 
170
        if (bufferSize == 0)
 
171
        {
 
172
            value = "";
 
173
        }
 
174
        else
 
175
        {
 
176
            //Decode sliced inBuffer
 
177
            ByteBuffer inBuffer = ByteBuffer.wrap(arr, offset, bufferSize).slice();
 
178
            CharBuffer outBuffer = CharBuffer.allocate(bufferSize);
 
179
            decoder.reset();
 
180
            CoderResult coderResult = decoder.decode(inBuffer, outBuffer, true);
 
181
            if (coderResult.isError())
 
182
            {
 
183
                logger.warning("Problem decoding text encoded null terminated string:" + coderResult.toString());
 
184
            }
 
185
            decoder.flush(outBuffer);
 
186
            outBuffer.flip();
 
187
            value = outBuffer.toString();
 
188
        }
 
189
        //Set Size so offset is ready for next field (includes the null terminator)
 
190
        logger.info("Read NullTerminatedString:" + value + " size inc terminator:" + size);
 
191
    }
 
192
 
 
193
    /**
 
194
     * Write String into byte array, adding a null character to the end of the String
 
195
     *
 
196
     * @return the data as a byte array in format to write to file
 
197
     */
 
198
    public byte[] writeByteArray()
 
199
    {
 
200
        logger.info("Writing NullTerminatedString." + value);
 
201
        byte[] data = null;
 
202
        //Write to buffer using the CharSet defined by getTextEncodingCharSet()
 
203
        //Add a null terminator which will be encoded based on encoding.
 
204
        try
 
205
        {
 
206
            String charSetName = getTextEncodingCharSet();
 
207
            if (charSetName.equals(TextEncoding.CHARSET_UTF_16))
 
208
            {
 
209
                charSetName = TextEncoding.CHARSET_UTF_16_ENCODING_FORMAT;
 
210
                CharsetEncoder encoder = Charset.forName(charSetName).newEncoder();
 
211
                //Note remember LE BOM is ff fe but tis is handled by encoder Unicode char is fe ff
 
212
                ByteBuffer bb = encoder.encode(CharBuffer.wrap('\ufeff' + (String) value + '\0'));
 
213
                data = new byte[bb.limit()];
 
214
                bb.get(data, 0, bb.limit());
 
215
            }
 
216
            else
 
217
            {
 
218
                CharsetEncoder encoder = Charset.forName(charSetName).newEncoder();
 
219
                ByteBuffer bb = encoder.encode(CharBuffer.wrap((String) value + '\0'));
 
220
                data = new byte[bb.limit()];
 
221
                bb.get(data, 0, bb.limit());
 
222
            }
 
223
        }
 
224
        //Should never happen so if does throw a RuntimeException
 
225
        catch (CharacterCodingException ce)
 
226
        {
 
227
            logger.severe(ce.getMessage());
 
228
            throw new RuntimeException(ce);
 
229
        }
 
230
        setSize(data.length);
 
231
        return data;
 
232
    }
 
233
 
 
234
    protected String getTextEncodingCharSet()
 
235
    {
 
236
        byte textEncoding = this.getBody().getTextEncoding();
 
237
        String charSetName = TextEncoding.getInstanceOf().getValueForId(textEncoding);
 
238
        logger.finest("text encoding:" + textEncoding + " charset:" + charSetName);
 
239
        return charSetName;
 
240
    }
 
241
}