VCardParserImpl_V21.java revision 2c9cf383b1c956c7185e97c2417ebd85b48fc0ac
1/*
2 * Copyright (C) 2010 The Android Open Source Project
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 */
16package com.android.vcard;
17
18import android.text.TextUtils;
19import android.util.Base64;
20import android.util.Log;
21
22import com.android.vcard.exception.VCardAgentNotSupportedException;
23import com.android.vcard.exception.VCardException;
24import com.android.vcard.exception.VCardInvalidCommentLineException;
25import com.android.vcard.exception.VCardInvalidLineException;
26import com.android.vcard.exception.VCardVersionException;
27
28import java.io.BufferedReader;
29import java.io.IOException;
30import java.io.InputStream;
31import java.io.InputStreamReader;
32import java.io.Reader;
33import java.util.ArrayList;
34import java.util.Collection;
35import java.util.HashSet;
36import java.util.List;
37import java.util.Set;
38
39/**
40 * <p>
41 * Basic implementation achieving vCard parsing. Based on vCard 2.1.
42 * </p>
43 * @hide
44 */
45/* package */ class VCardParserImpl_V21 {
46    private static final String LOG_TAG = VCardConstants.LOG_TAG;
47
48    protected static final class CustomBufferedReader extends BufferedReader {
49        private long mTime;
50
51        /**
52         * Needed since "next line" may be null due to end of line.
53         */
54        private boolean mNextLineIsValid;
55        private String mNextLine;
56
57        public CustomBufferedReader(Reader in) {
58            super(in);
59        }
60
61        @Override
62        public String readLine() throws IOException {
63            if (mNextLineIsValid) {
64                final String ret = mNextLine;
65                mNextLine = null;
66                mNextLineIsValid = false;
67                return ret;
68            }
69
70            final long start = System.currentTimeMillis();
71            final String line = super.readLine();
72            final long end = System.currentTimeMillis();
73            mTime += end - start;
74            return line;
75        }
76
77        /**
78         * Read one line, but make this object store it in its queue.
79         */
80        public String peekLine() throws IOException {
81            if (!mNextLineIsValid) {
82                final long start = System.currentTimeMillis();
83                final String line = super.readLine();
84                final long end = System.currentTimeMillis();
85                mTime += end - start;
86
87                mNextLine = line;
88                mNextLineIsValid = true;
89            }
90
91            return mNextLine;
92        }
93
94        public long getTotalmillisecond() {
95            return mTime;
96        }
97    }
98
99    private static final String DEFAULT_ENCODING = "8BIT";
100    private static final String DEFAULT_CHARSET = "UTF-8";
101
102    protected final String mIntermediateCharset;
103
104    private final List<VCardInterpreter> mInterpreterList = new ArrayList<VCardInterpreter>();
105    private boolean mCanceled;
106
107    /**
108     * <p>
109     * The encoding type for deconding byte streams. This member variable is
110     * reset to a default encoding every time when a new item comes.
111     * </p>
112     * <p>
113     * "Encoding" in vCard is different from "Charset". It is mainly used for
114     * addresses, notes, images. "7BIT", "8BIT", "BASE64", and
115     * "QUOTED-PRINTABLE" are known examples.
116     * </p>
117     */
118    protected String mCurrentEncoding;
119
120    protected String mCurrentCharset;
121
122    /**
123     * <p>
124     * The reader object to be used internally.
125     * </p>
126     * <p>
127     * Developers should not directly read a line from this object. Use
128     * getLine() unless there some reason.
129     * </p>
130     */
131    protected CustomBufferedReader mReader;
132
133    /**
134     * <p>
135     * Set for storing unkonwn TYPE attributes, which is not acceptable in vCard
136     * specification, but happens to be seen in real world vCard.
137     * </p>
138     * <p>
139     * We just accept those invalid types after emitting a warning for each of it.
140     * </p>
141     */
142    protected final Set<String> mUnknownTypeSet = new HashSet<String>();
143
144    /**
145     * <p>
146     * Set for storing unkonwn VALUE attributes, which is not acceptable in
147     * vCard specification, but happens to be seen in real world vCard.
148     * </p>
149     * <p>
150     * We just accept those invalid types after emitting a warning for each of it.
151     * </p>
152     */
153    protected final Set<String> mUnknownValueSet = new HashSet<String>();
154
155
156    public VCardParserImpl_V21() {
157        this(VCardConfig.VCARD_TYPE_DEFAULT);
158    }
159
160    public VCardParserImpl_V21(int vcardType) {
161        mIntermediateCharset =  VCardConfig.DEFAULT_INTERMEDIATE_CHARSET;
162    }
163
164    /**
165     * @return true when a given property name is a valid property name.
166     */
167    protected boolean isValidPropertyName(final String propertyName) {
168        if (!(getKnownPropertyNameSet().contains(propertyName.toUpperCase()) ||
169                propertyName.startsWith("X-"))
170                && !mUnknownTypeSet.contains(propertyName)) {
171            mUnknownTypeSet.add(propertyName);
172            Log.w(LOG_TAG, "Property name unsupported by vCard 2.1: " + propertyName);
173        }
174        return true;
175    }
176
177    /**
178     * @return String. It may be null, or its length may be 0
179     * @throws IOException
180     */
181    protected String getLine() throws IOException {
182        return mReader.readLine();
183    }
184
185    protected String peekLine() throws IOException {
186        return mReader.peekLine();
187    }
188
189    /**
190     * @return String with it's length > 0
191     * @throws IOException
192     * @throws VCardException when the stream reached end of line
193     */
194    protected String getNonEmptyLine() throws IOException, VCardException {
195        String line;
196        while (true) {
197            line = getLine();
198            if (line == null) {
199                throw new VCardException("Reached end of buffer.");
200            } else if (line.trim().length() > 0) {
201                return line;
202            }
203        }
204    }
205
206    /**
207     * <code>
208     * vcard = "BEGIN" [ws] ":" [ws] "VCARD" [ws] 1*CRLF
209     *         items *CRLF
210     *         "END" [ws] ":" [ws] "VCARD"
211     * </code>
212     * @return False when reaching end of file.
213     */
214    private boolean parseOneVCard() throws IOException, VCardException {
215        // reset for this entire vCard.
216        mCurrentEncoding = DEFAULT_ENCODING;
217        mCurrentCharset = DEFAULT_CHARSET;
218
219        boolean allowGarbage = false;
220        if (!readBeginVCard(allowGarbage)) {
221            return false;
222        }
223        for (VCardInterpreter interpreter : mInterpreterList) {
224            interpreter.onEntryStarted();
225        }
226        parseItems();
227        for (VCardInterpreter interpreter : mInterpreterList) {
228            interpreter.onEntryEnded();
229        }
230        return true;
231    }
232
233    /**
234     * @return True when successful. False when reaching the end of line
235     * @throws IOException
236     * @throws VCardException
237     */
238    protected boolean readBeginVCard(boolean allowGarbage) throws IOException, VCardException {
239        // TODO: use consructPropertyLine().
240        String line;
241        do {
242            while (true) {
243                line = getLine();
244                if (line == null) {
245                    return false;
246                } else if (line.trim().length() > 0) {
247                    break;
248                }
249            }
250            final String[] strArray = line.split(":", 2);
251            final int length = strArray.length;
252
253            // Although vCard 2.1/3.0 specification does not allow lower cases,
254            // we found vCard file emitted by some external vCard expoter have such
255            // invalid Strings.
256            // e.g. BEGIN:vCard
257            if (length == 2 && strArray[0].trim().equalsIgnoreCase("BEGIN")
258                    && strArray[1].trim().equalsIgnoreCase("VCARD")) {
259                return true;
260            } else if (!allowGarbage) {
261                throw new VCardException("Expected String \"BEGIN:VCARD\" did not come "
262                        + "(Instead, \"" + line + "\" came)");
263            }
264        } while (allowGarbage);
265
266        throw new VCardException("Reached where must not be reached.");
267    }
268
269    /**
270     * Parses lines other than the first "BEGIN:VCARD". Takes care of "END:VCARD"n and
271     * "BEGIN:VCARD" in nested vCard.
272     */
273    /*
274     * items = *CRLF item / item
275     *
276     * Note: BEGIN/END aren't include in the original spec while this method handles them.
277     */
278    protected void parseItems() throws IOException, VCardException {
279        boolean ended = false;
280
281        try {
282            ended = parseItem();
283        } catch (VCardInvalidCommentLineException e) {
284            Log.e(LOG_TAG, "Invalid line which looks like some comment was found. Ignored.");
285        }
286
287        while (!ended) {
288            try {
289                ended = parseItem();
290            } catch (VCardInvalidCommentLineException e) {
291                Log.e(LOG_TAG, "Invalid line which looks like some comment was found. Ignored.");
292            }
293        }
294    }
295
296    /*
297     * item = [groups "."] name [params] ":" value CRLF / [groups "."] "ADR"
298     * [params] ":" addressparts CRLF / [groups "."] "ORG" [params] ":" orgparts
299     * CRLF / [groups "."] "N" [params] ":" nameparts CRLF / [groups "."]
300     * "AGENT" [params] ":" vcard CRLF
301     */
302    protected boolean parseItem() throws IOException, VCardException {
303        // Reset for an item.
304        mCurrentEncoding = DEFAULT_ENCODING;
305
306        final String line = getNonEmptyLine();
307        final VCardProperty propertyData = constructPropertyData(line);
308
309        final String propertyNameUpper = propertyData.getName().toUpperCase();
310        final String propertyRawValue = propertyData.getRawValue();
311
312        if (propertyNameUpper.equals(VCardConstants.PROPERTY_BEGIN)) {
313            if (propertyRawValue.equalsIgnoreCase("VCARD")) {
314                handleNest();
315            } else {
316                throw new VCardException("Unknown BEGIN type: " + propertyRawValue);
317            }
318        } else if (propertyNameUpper.equals(VCardConstants.PROPERTY_END)) {
319            if (propertyRawValue.equalsIgnoreCase("VCARD")) {
320                return true;  // Ended.
321            } else {
322                throw new VCardException("Unknown END type: " + propertyRawValue);
323            }
324        } else {
325            parseItemInter(propertyData, propertyNameUpper);
326        }
327        return false;
328    }
329
330    private void parseItemInter(VCardProperty property, String propertyNameUpper)
331            throws IOException, VCardException {
332        String propertyRawValue = property.getRawValue();
333        if (propertyNameUpper.equals(VCardConstants.PROPERTY_AGENT)) {
334            handleAgent(property);
335        } else if (isValidPropertyName(propertyNameUpper)) {
336            if (propertyNameUpper.equals(VCardConstants.PROPERTY_VERSION) &&
337                    !propertyRawValue.equals(getVersionString())) {
338                throw new VCardVersionException(
339                        "Incompatible version: " + propertyRawValue + " != " + getVersionString());
340            }
341            handlePropertyValue(property, propertyNameUpper);
342        } else {
343            throw new VCardException("Unknown property name: \"" + propertyNameUpper + "\"");
344        }
345    }
346
347    private void handleNest() throws IOException, VCardException {
348        for (VCardInterpreter interpreter : mInterpreterList) {
349            interpreter.onEntryStarted();
350        }
351        parseItems();
352        for (VCardInterpreter interpreter : mInterpreterList) {
353            interpreter.onEntryEnded();
354        }
355    }
356
357    // For performance reason, the states for group and property name are merged into one.
358    static private final int STATE_GROUP_OR_PROPERTY_NAME = 0;
359    static private final int STATE_PARAMS = 1;
360    // vCard 3.0 specification allows double-quoted parameters, while vCard 2.1 does not.
361    static private final int STATE_PARAMS_IN_DQUOTE = 2;
362
363    protected VCardProperty constructPropertyData(String line) throws VCardException {
364        final VCardProperty propertyData = new VCardProperty();
365
366        final int length = line.length();
367        if (length > 0 && line.charAt(0) == '#') {
368            throw new VCardInvalidCommentLineException();
369        }
370
371        int state = STATE_GROUP_OR_PROPERTY_NAME;
372        int nameIndex = 0;
373
374        // This loop is developed so that we don't have to take care of bottle neck here.
375        // Refactor carefully when you need to do so.
376        for (int i = 0; i < length; i++) {
377            final char ch = line.charAt(i);
378            switch (state) {
379                case STATE_GROUP_OR_PROPERTY_NAME: {
380                    if (ch == ':') {  // End of a property name.
381                        final String propertyName = line.substring(nameIndex, i);
382                        propertyData.setName(propertyName);
383                        propertyData.setRawValue( i < length - 1 ? line.substring(i + 1) : "");
384                        return propertyData;
385                    } else if (ch == '.') {  // Each group is followed by the dot.
386                        final String groupName = line.substring(nameIndex, i);
387                        if (groupName.length() == 0) {
388                            Log.w(LOG_TAG, "Empty group found. Ignoring.");
389                        } else {
390                            propertyData.addGroup(groupName);
391                        }
392                        nameIndex = i + 1;  // Next should be another group or a property name.
393                    } else if (ch == ';') {  // End of property name and beginneng of parameters.
394                        final String propertyName = line.substring(nameIndex, i);
395                        propertyData.setName(propertyName);
396                        nameIndex = i + 1;
397                        state = STATE_PARAMS;  // Start parameter parsing.
398                    }
399                    // TODO: comma support (in vCard 3.0 and 4.0).
400                    break;
401                }
402                case STATE_PARAMS: {
403                    if (ch == '"') {
404                        if (VCardConstants.VERSION_V21.equalsIgnoreCase(getVersionString())) {
405                            Log.w(LOG_TAG, "Double-quoted params found in vCard 2.1. " +
406                                    "Silently allow it");
407                        }
408                        state = STATE_PARAMS_IN_DQUOTE;
409                    } else if (ch == ';') {  // Starts another param.
410                        handleParams(propertyData, line.substring(nameIndex, i));
411                        nameIndex = i + 1;
412                    } else if (ch == ':') {  // End of param and beginenning of values.
413                        handleParams(propertyData, line.substring(nameIndex, i));
414                        propertyData.setRawValue(i < length - 1 ? line.substring(i + 1) : "");
415                        return propertyData;
416                    }
417                    break;
418                }
419                case STATE_PARAMS_IN_DQUOTE: {
420                    if (ch == '"') {
421                        if (VCardConstants.VERSION_V21.equalsIgnoreCase(getVersionString())) {
422                            Log.w(LOG_TAG, "Double-quoted params found in vCard 2.1. " +
423                                    "Silently allow it");
424                        }
425                        state = STATE_PARAMS;
426                    }
427                    break;
428                }
429            }
430        }
431
432        throw new VCardInvalidLineException("Invalid line: \"" + line + "\"");
433    }
434
435    /*
436     * params = ";" [ws] paramlist paramlist = paramlist [ws] ";" [ws] param /
437     * param param = "TYPE" [ws] "=" [ws] ptypeval / "VALUE" [ws] "=" [ws]
438     * pvalueval / "ENCODING" [ws] "=" [ws] pencodingval / "CHARSET" [ws] "="
439     * [ws] charsetval / "LANGUAGE" [ws] "=" [ws] langval / "X-" word [ws] "="
440     * [ws] word / knowntype
441     */
442    protected void handleParams(VCardProperty propertyData, String params)
443            throws VCardException {
444        final String[] strArray = params.split("=", 2);
445        if (strArray.length == 2) {
446            final String paramName = strArray[0].trim().toUpperCase();
447            String paramValue = strArray[1].trim();
448            if (paramName.equals("TYPE")) {
449                handleType(propertyData, paramValue);
450            } else if (paramName.equals("VALUE")) {
451                handleValue(propertyData, paramValue);
452            } else if (paramName.equals("ENCODING")) {
453                handleEncoding(propertyData, paramValue);
454            } else if (paramName.equals("CHARSET")) {
455                handleCharset(propertyData, paramValue);
456            } else if (paramName.equals("LANGUAGE")) {
457                handleLanguage(propertyData, paramValue);
458            } else if (paramName.startsWith("X-")) {
459                handleAnyParam(propertyData, paramName, paramValue);
460            } else {
461                throw new VCardException("Unknown type \"" + paramName + "\"");
462            }
463        } else {
464            handleParamWithoutName(propertyData, strArray[0]);
465        }
466    }
467
468    /**
469     * vCard 3.0 parser implementation may throw VCardException.
470     */
471    protected void handleParamWithoutName(VCardProperty propertyData, final String paramValue) {
472        handleType(propertyData, paramValue);
473    }
474
475    /*
476     * ptypeval = knowntype / "X-" word
477     */
478    protected void handleType(VCardProperty propertyData, final String ptypeval) {
479        if (!(getKnownTypeSet().contains(ptypeval.toUpperCase())
480                || ptypeval.startsWith("X-"))
481                && !mUnknownTypeSet.contains(ptypeval)) {
482            mUnknownTypeSet.add(ptypeval);
483            Log.w(LOG_TAG, String.format("TYPE unsupported by %s: ", getVersion(), ptypeval));
484        }
485        propertyData.addParameter(VCardConstants.PARAM_TYPE, ptypeval);
486    }
487
488    /*
489     * pvalueval = "INLINE" / "URL" / "CONTENT-ID" / "CID" / "X-" word
490     */
491    protected void handleValue(VCardProperty propertyData, final String pvalueval) {
492        if (!(getKnownValueSet().contains(pvalueval.toUpperCase())
493                || pvalueval.startsWith("X-")
494                || mUnknownValueSet.contains(pvalueval))) {
495            mUnknownValueSet.add(pvalueval);
496            Log.w(LOG_TAG, String.format(
497                    "The value unsupported by TYPE of %s: ", getVersion(), pvalueval));
498        }
499        propertyData.addParameter(VCardConstants.PARAM_VALUE, pvalueval);
500    }
501
502    /*
503     * pencodingval = "7BIT" / "8BIT" / "QUOTED-PRINTABLE" / "BASE64" / "X-" word
504     */
505    protected void handleEncoding(VCardProperty propertyData, String pencodingval)
506            throws VCardException {
507        if (getAvailableEncodingSet().contains(pencodingval) ||
508                pencodingval.startsWith("X-")) {
509            propertyData.addParameter(VCardConstants.PARAM_ENCODING, pencodingval);
510            // Update encoding right away, as this is needed to understanding other params.
511            mCurrentEncoding = pencodingval;
512        } else {
513            throw new VCardException("Unknown encoding \"" + pencodingval + "\"");
514        }
515    }
516
517    /**
518     * <p>
519     * vCard 2.1 specification only allows us-ascii and iso-8859-xxx (See RFC 1521),
520     * but recent vCard files often contain other charset like UTF-8, SHIFT_JIS, etc.
521     * We allow any charset.
522     * </p>
523     */
524    protected void handleCharset(VCardProperty propertyData, String charsetval) {
525        mCurrentCharset = charsetval;
526        propertyData.addParameter(VCardConstants.PARAM_CHARSET, charsetval);
527    }
528
529    /**
530     * See also Section 7.1 of RFC 1521
531     */
532    protected void handleLanguage(VCardProperty propertyData, String langval)
533            throws VCardException {
534        String[] strArray = langval.split("-");
535        if (strArray.length != 2) {
536            throw new VCardException("Invalid Language: \"" + langval + "\"");
537        }
538        String tmp = strArray[0];
539        int length = tmp.length();
540        for (int i = 0; i < length; i++) {
541            if (!isAsciiLetter(tmp.charAt(i))) {
542                throw new VCardException("Invalid Language: \"" + langval + "\"");
543            }
544        }
545        tmp = strArray[1];
546        length = tmp.length();
547        for (int i = 0; i < length; i++) {
548            if (!isAsciiLetter(tmp.charAt(i))) {
549                throw new VCardException("Invalid Language: \"" + langval + "\"");
550            }
551        }
552        propertyData.addParameter(VCardConstants.PARAM_LANGUAGE, langval);
553    }
554
555    private boolean isAsciiLetter(char ch) {
556        if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
557            return true;
558        }
559        return false;
560    }
561
562    /**
563     * Mainly for "X-" type. This accepts any kind of type without check.
564     */
565    protected void handleAnyParam(
566            VCardProperty propertyData, String paramName, String paramValue) {
567        propertyData.addParameter(paramName, paramValue);
568    }
569
570    protected void handlePropertyValue(VCardProperty property, String propertyName)
571            throws IOException, VCardException {
572        final String propertyNameUpper = property.getName().toUpperCase();
573        String propertyRawValue = property.getRawValue();
574        final String sourceCharset = VCardConfig.DEFAULT_INTERMEDIATE_CHARSET;
575        final Collection<String> charsetCollection =
576                property.getParameters(VCardConstants.PARAM_CHARSET);
577        String targetCharset =
578                ((charsetCollection != null) ? charsetCollection.iterator().next() : null);
579        if (TextUtils.isEmpty(targetCharset)) {
580            targetCharset = VCardConfig.DEFAULT_IMPORT_CHARSET;
581        }
582
583        // TODO: have "separableProperty" which reflects vCard spec..
584        if (propertyNameUpper.equals(VCardConstants.PROPERTY_ADR)
585                || propertyNameUpper.equals(VCardConstants.PROPERTY_ORG)
586                || propertyNameUpper.equals(VCardConstants.PROPERTY_N)) {
587            List<String> encodedValueList = new ArrayList<String>();
588
589            // vCard 2.1 does not allow QUOTED-PRINTABLE here, but some softwares/devices emit
590            // such data.
591            if (mCurrentEncoding.equalsIgnoreCase(VCardConstants.PARAM_ENCODING_QP)) {
592                // First we retrieve Quoted-Printable String from vCard entry, which may include
593                // multiple lines.
594                final String quotedPrintablePart = getQuotedPrintablePart(propertyRawValue);
595
596                // "Raw value" from the view of users should contain all part of QP string.
597                // TODO: add test for this handling
598                property.setRawValue(quotedPrintablePart);
599
600                // We split Quoted-Printable String using semi-colon before decoding it, as
601                // the Quoted-Printable may have semi-colon, which confuses splitter.
602                final List<String> quotedPrintableValueList =
603                        VCardUtils.constructListFromValue(quotedPrintablePart, getVersion());
604                for (String quotedPrintableValue : quotedPrintableValueList) {
605                    String encoded = VCardUtils.parseQuotedPrintable(quotedPrintableValue,
606                            false, sourceCharset, targetCharset);
607                    encodedValueList.add(encoded);
608                }
609            } else {
610                final List<String> rawValueList =
611                    VCardUtils.constructListFromValue(propertyRawValue, getVersion());
612                for (String rawValue : rawValueList) {
613                    encodedValueList.add(VCardUtils.convertStringCharset(
614                            rawValue, sourceCharset, targetCharset));
615                }
616            }
617
618            property.setValues(encodedValueList);
619            for (VCardInterpreter interpreter : mInterpreterList) {
620                interpreter.onPropertyCreated(property);
621            }
622            return;
623        }
624
625        final String upperEncoding = mCurrentEncoding.toUpperCase();
626        if (upperEncoding.equals(VCardConstants.PARAM_ENCODING_QP)) {
627            final String quotedPrintablePart = getQuotedPrintablePart(propertyRawValue);
628            final String propertyEncodedValue =
629                    VCardUtils.parseQuotedPrintable(quotedPrintablePart,
630                            false, sourceCharset, targetCharset);
631            property.setRawValue(quotedPrintablePart);
632            property.setValues(propertyEncodedValue);
633            for (VCardInterpreter interpreter : mInterpreterList) {
634                interpreter.onPropertyCreated(property);
635            }
636        } else if (upperEncoding.equals(VCardConstants.PARAM_ENCODING_BASE64)
637                || upperEncoding.equals(VCardConstants.PARAM_ENCODING_B)) {
638            // It is very rare, but some BASE64 data may be so big that
639            // OutOfMemoryError occurs. To ignore such cases, use try-catch.
640            try {
641                final String base64Property = getBase64(propertyRawValue);
642                try {
643                    property.setByteValue(Base64.decode(base64Property, Base64.DEFAULT));
644                } catch (IllegalArgumentException e) {
645                    throw new VCardException("Decode error on base64 photo: " + propertyRawValue);
646                }
647                for (VCardInterpreter interpreter : mInterpreterList) {
648                    interpreter.onPropertyCreated(property);
649                }
650            } catch (OutOfMemoryError error) {
651                Log.e(LOG_TAG, "OutOfMemoryError happened during parsing BASE64 data!");
652                for (VCardInterpreter interpreter : mInterpreterList) {
653                    interpreter.onPropertyCreated(property);
654                }
655            }
656        } else {
657            if (!(upperEncoding.equals("7BIT") || upperEncoding.equals("8BIT") ||
658                    upperEncoding.startsWith("X-"))) {
659                Log.w(LOG_TAG,
660                        String.format("The encoding \"%s\" is unsupported by vCard %s",
661                                mCurrentEncoding, getVersionString()));
662            }
663
664            // Some device uses line folding defined in RFC 2425, which is not allowed
665            // in vCard 2.1 (while needed in vCard 3.0).
666            //
667            // e.g.
668            // BEGIN:VCARD
669            // VERSION:2.1
670            // N:;Omega;;;
671            // EMAIL;INTERNET:"Omega"
672            //   <omega@example.com>
673            // FN:Omega
674            // END:VCARD
675            //
676            // The vCard above assumes that email address should become:
677            // "Omega" <omega@example.com>
678            //
679            // But vCard 2.1 requires Quote-Printable when a line contains line break(s).
680            //
681            // For more information about line folding,
682            // see "5.8.1. Line delimiting and folding" in RFC 2425.
683            //
684            // We take care of this case more formally in vCard 3.0, so we only need to
685            // do this in vCard 2.1.
686            if (getVersion() == VCardConfig.VERSION_21) {
687                StringBuilder builder = null;
688                while (true) {
689                    final String nextLine = peekLine();
690                    // We don't need to care too much about this exceptional case,
691                    // but we should not wrongly eat up "END:VCARD", since it critically
692                    // breaks this parser's state machine.
693                    // Thus we roughly look over the next line and confirm it is at least not
694                    // "END:VCARD". This extra fee is worth paying. This is exceptional
695                    // anyway.
696                    if (!TextUtils.isEmpty(nextLine) &&
697                            nextLine.charAt(0) == ' ' &&
698                            !"END:VCARD".contains(nextLine.toUpperCase())) {
699                        getLine();  // Drop the next line.
700
701                        if (builder == null) {
702                            builder = new StringBuilder();
703                            builder.append(propertyRawValue);
704                        }
705                        builder.append(nextLine.substring(1));
706                    } else {
707                        break;
708                    }
709                }
710                if (builder != null) {
711                    propertyRawValue = builder.toString();
712                }
713            }
714
715            ArrayList<String> propertyValueList = new ArrayList<String>();
716            String value = VCardUtils.convertStringCharset(
717                    maybeUnescapeText(propertyRawValue), sourceCharset, targetCharset);
718            propertyValueList.add(value);
719            property.setValues(propertyValueList);
720            for (VCardInterpreter interpreter : mInterpreterList) {
721                interpreter.onPropertyCreated(property);
722            }
723        }
724    }
725
726    /**
727     * <p>
728     * Parses and returns Quoted-Printable.
729     * </p>
730     *
731     * @param firstString The string following a parameter name and attributes.
732     *            Example: "string" in
733     *            "ADR:ENCODING=QUOTED-PRINTABLE:string\n\r".
734     * @return whole Quoted-Printable string, including a given argument and
735     *         following lines. Excludes the last empty line following to Quoted
736     *         Printable lines.
737     * @throws IOException
738     * @throws VCardException
739     */
740    private String getQuotedPrintablePart(String firstString)
741            throws IOException, VCardException {
742        // Specifically, there may be some padding between = and CRLF.
743        // See the following:
744        //
745        // qp-line := *(qp-segment transport-padding CRLF)
746        // qp-part transport-padding
747        // qp-segment := qp-section *(SPACE / TAB) "="
748        // ; Maximum length of 76 characters
749        //
750        // e.g. (from RFC 2045)
751        // Now's the time =
752        // for all folk to come=
753        // to the aid of their country.
754        if (firstString.trim().endsWith("=")) {
755            // remove "transport-padding"
756            int pos = firstString.length() - 1;
757            while (firstString.charAt(pos) != '=') {
758            }
759            StringBuilder builder = new StringBuilder();
760            builder.append(firstString.substring(0, pos + 1));
761            builder.append("\r\n");
762            String line;
763            while (true) {
764                line = getLine();
765                if (line == null) {
766                    throw new VCardException("File ended during parsing a Quoted-Printable String");
767                }
768                if (line.trim().endsWith("=")) {
769                    // remove "transport-padding"
770                    pos = line.length() - 1;
771                    while (line.charAt(pos) != '=') {
772                    }
773                    builder.append(line.substring(0, pos + 1));
774                    builder.append("\r\n");
775                } else {
776                    builder.append(line);
777                    break;
778                }
779            }
780            return builder.toString();
781        } else {
782            return firstString;
783        }
784    }
785
786    protected String getBase64(String firstString) throws IOException, VCardException {
787        final StringBuilder builder = new StringBuilder();
788        builder.append(firstString);
789
790        while (true) {
791            final String line = peekLine();
792            if (line == null) {
793                throw new VCardException("File ended during parsing BASE64 binary");
794            }
795
796            // vCard 2.1 requires two spaces at the end of BASE64 strings, but some vCard doesn't
797            // have them. We try to detect those cases using colon and semi-colon, given BASE64
798            // does not contain it.
799            // E.g.
800            //      TEL;TYPE=WORK:+5555555
801            // or
802            //      END:VCARD
803            int colonIndex = line.indexOf(":");
804            int semiColonIndex = line.indexOf(";");
805            if (colonIndex > -1 || semiColonIndex > -1) {
806                // Find the minimum index that is greater than -1.
807                final int minIndex;
808                if (colonIndex == -1) {
809                    minIndex = semiColonIndex;
810                } else if (semiColonIndex == -1) {
811                    minIndex = colonIndex;
812                } else {
813                    minIndex = Math.min(colonIndex, semiColonIndex);
814                }
815
816                if (getKnownPropertyNameSet().contains(line.substring(0, minIndex).toUpperCase())) {
817                    Log.w(LOG_TAG, "Found a next property during parsing a BASE64 string, " +
818                            "which must not contain semi-colon or colon. Treat the line as next "
819                            + "property.");
820                    Log.w(LOG_TAG, "Problematic line: " + line.trim());
821                    break;
822                }
823            }
824
825            // Consume the line.
826            getLine();
827
828            if (line.length() == 0) {
829                break;
830            }
831            builder.append(line);
832        }
833
834        return builder.toString();
835    }
836
837    /*
838     * vCard 2.1 specifies AGENT allows one vcard entry. Currently we emit an
839     * error toward the AGENT property.
840     * // TODO: Support AGENT property.
841     * item =
842     * ... / [groups "."] "AGENT" [params] ":" vcard CRLF vcard = "BEGIN" [ws]
843     * ":" [ws] "VCARD" [ws] 1*CRLF items *CRLF "END" [ws] ":" [ws] "VCARD"
844     */
845    protected void handleAgent(final VCardProperty property) throws VCardException {
846        if (!property.getRawValue().toUpperCase().contains("BEGIN:VCARD")) {
847            // Apparently invalid line seen in Windows Mobile 6.5. Ignore them.
848            for (VCardInterpreter interpreter : mInterpreterList) {
849                interpreter.onPropertyCreated(property);
850            }
851            return;
852        } else {
853            throw new VCardAgentNotSupportedException("AGENT Property is not supported now.");
854        }
855    }
856
857    /**
858     * For vCard 3.0.
859     */
860    protected String maybeUnescapeText(final String text) {
861        return text;
862    }
863
864    /**
865     * Returns unescaped String if the character should be unescaped. Return
866     * null otherwise. e.g. In vCard 2.1, "\;" should be unescaped into ";"
867     * while "\x" should not be.
868     */
869    protected String maybeUnescapeCharacter(final char ch) {
870        return unescapeCharacter(ch);
871    }
872
873    /* package */ static String unescapeCharacter(final char ch) {
874        // Original vCard 2.1 specification does not allow transformation
875        // "\:" -> ":", "\," -> ",", and "\\" -> "\", but previous
876        // implementation of
877        // this class allowed them, so keep it as is.
878        if (ch == '\\' || ch == ';' || ch == ':' || ch == ',') {
879            return String.valueOf(ch);
880        } else {
881            return null;
882        }
883    }
884
885    /**
886     * @return {@link VCardConfig#VERSION_21}
887     */
888    protected int getVersion() {
889        return VCardConfig.VERSION_21;
890    }
891
892    /**
893     * @return {@link VCardConfig#VERSION_30}
894     */
895    protected String getVersionString() {
896        return VCardConstants.VERSION_V21;
897    }
898
899    protected Set<String> getKnownPropertyNameSet() {
900        return VCardParser_V21.sKnownPropertyNameSet;
901    }
902
903    protected Set<String> getKnownTypeSet() {
904        return VCardParser_V21.sKnownTypeSet;
905    }
906
907    protected Set<String> getKnownValueSet() {
908        return VCardParser_V21.sKnownValueSet;
909    }
910
911    protected Set<String> getAvailableEncodingSet() {
912        return VCardParser_V21.sAvailableEncoding;
913    }
914
915    protected String getDefaultEncoding() {
916        return DEFAULT_ENCODING;
917    }
918
919    protected String getDefaultCharset() {
920        return DEFAULT_CHARSET;
921    }
922
923    protected String getCurrentCharset() {
924        return mCurrentCharset;
925    }
926
927    public void addInterpreter(VCardInterpreter interpreter) {
928        mInterpreterList.add(interpreter);
929    }
930
931    public void parse(InputStream is) throws IOException, VCardException {
932        if (is == null) {
933            throw new NullPointerException("InputStream must not be null.");
934        }
935
936        final InputStreamReader tmpReader = new InputStreamReader(is, mIntermediateCharset);
937        mReader = new CustomBufferedReader(tmpReader);
938
939        final long start = System.currentTimeMillis();
940        for (VCardInterpreter interpreter : mInterpreterList) {
941            interpreter.onVCardStarted();
942        }
943
944        // vcard_file = [wsls] vcard [wsls]
945        while (true) {
946            synchronized (this) {
947                if (mCanceled) {
948                    Log.i(LOG_TAG, "Cancel request has come. exitting parse operation.");
949                    break;
950                }
951            }
952            if (!parseOneVCard()) {
953                break;
954            }
955        }
956
957        for (VCardInterpreter interpreter : mInterpreterList) {
958            interpreter.onVCardEnded();
959        }
960    }
961
962    public void parseOne(InputStream is) throws IOException, VCardException {
963        if (is == null) {
964            throw new NullPointerException("InputStream must not be null.");
965        }
966
967        final InputStreamReader tmpReader = new InputStreamReader(is, mIntermediateCharset);
968        mReader = new CustomBufferedReader(tmpReader);
969
970        final long start = System.currentTimeMillis();
971        for (VCardInterpreter interpreter : mInterpreterList) {
972            interpreter.onVCardStarted();
973        }
974        parseOneVCard();
975        for (VCardInterpreter interpreter : mInterpreterList) {
976            interpreter.onVCardEnded();
977        }
978    }
979
980    public final synchronized void cancel() {
981        Log.i(LOG_TAG, "ParserImpl received cancel operation.");
982        mCanceled = true;
983    }
984}
985