git-svn-id: http://zxing.googlecode.com/svn/trunk@290 59b500cc-1b3d-0410-9834-0bbf25f...
[zxing.git] / core / src / com / google / zxing / client / result / NDEFTextParsedResult.java
1 /*
2  * Copyright 2008 Google Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package com.google.zxing.client.result;
18
19 import com.google.zxing.Result;
20
21 /**
22  * Recognizes an NDEF message that encodes text according to the
23  * "Text Record Type Definition" specification.
24  *
25  * @author srowen@google.com (Sean Owen)
26  */
27 public final class NDEFTextParsedResult extends AbstractNDEFParsedResult {
28
29   private static final byte TEXT_WELL_KNOWN_TYPE = (byte) 0x54;
30
31   private final String language;
32   private final String text;
33
34   private NDEFTextParsedResult(String language, String text) {
35     super(ParsedReaderResultType.NDEF_TEXT);
36     this.language = language;
37     this.text = text;
38   }
39
40   public static NDEFTextParsedResult parse(Result result) {
41     byte[] bytes = result.getRawBytes();
42     if (!isMaybeNDEF(bytes)) {
43       return null;
44     }
45
46     int payloadLength = bytes[2] & 0xFF;
47
48     // Next 1 byte is type
49     if (bytes[3] != TEXT_WELL_KNOWN_TYPE) {
50       return null;
51     }
52
53     // Text record
54     byte statusByte = bytes[4];
55     boolean isUTF16 = (statusByte & 0x80) != 0;
56     int languageLength = statusByte & 0x1F;
57
58     // language is always ASCII-encoded:
59     String language = bytesToString(bytes, 5, languageLength, "US-ASCII");
60     String encoding = isUTF16 ? "UTF-16" : "UTF-8";
61     String text = bytesToString(bytes, 5 + languageLength, payloadLength - languageLength - 1, encoding);
62     return new NDEFTextParsedResult(language, text);
63   }
64
65   public String getLanguage() {
66     return language;
67   }
68
69   public String getText() {
70     return text;
71   }
72
73   public String getDisplayResult() {
74     return text;
75   }
76
77 }