/android/import-contacts

To get this branch, use:
bzr branch http://bzr.ed.am/android/import-contacts

« back to all changes in this revision

Viewing changes to src/org/waxworlds/edam/importcontacts/VCFImporter.java

  • Committer: edam
  • Date: 2011-03-19 20:33:09 UTC
  • Revision ID: edam@waxworlds.org-20110319203309-5dzfyqrxwk94jtin
- formatting: removed some double-indents on overrunning lines
- updated TODO and NEWS
- rewrote central logic of parser so it makes more sense, looks nicer and has a small optimisation (getting name and params from line only when necessary)
- optimised unnecessary mutliple converting of lines to US-ASCII
- re-wrote line extraction from vcards so that we can lookahead for v3 folded lines
- added support for v3 folded lines

Show diffs side-by-side

added added

removed removed

1
1
/*
2
2
 * VCFImporter.java
3
3
 *
4
 
 * Copyright (C) 2009 to 2011 Tim Marston <tim@ed.am>
 
4
 * Copyright (C) 2009 Tim Marston <edam@waxworlds.org>
5
5
 *
6
6
 * This file is part of the Import Contacts program (hereafter referred
7
7
 * to as "this program"). For more information, see
8
 
 * http://ed.am/dev/android/import-contacts
 
8
 * http://www.waxworlds.org/edam/software/android/import-contacts
9
9
 *
10
10
 * This program is free software: you can redistribute it and/or modify
11
11
 * it under the terms of the GNU General Public License as published by
21
21
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22
22
 */
23
23
 
24
 
package am.ed.importcontacts;
 
24
package org.waxworlds.edam.importcontacts;
25
25
 
26
26
import java.io.BufferedReader;
27
27
import java.io.File;
32
32
import java.io.IOException;
33
33
import java.io.UnsupportedEncodingException;
34
34
import java.nio.ByteBuffer;
35
 
import java.util.ArrayList;
36
35
import java.util.Arrays;
37
 
import java.util.HashMap;
38
36
import java.util.HashSet;
39
37
import java.util.Iterator;
40
38
import java.util.List;
41
 
import java.util.Locale;
42
 
import java.util.NoSuchElementException;
43
39
import java.util.Set;
44
40
import java.util.Vector;
45
41
import java.util.regex.Matcher;
46
42
import java.util.regex.Pattern;
 
43
import java.util.NoSuchElementException;
 
44
import java.lang.UnsupportedOperationException;
47
45
 
48
 
import android.annotation.SuppressLint;
49
46
import android.content.SharedPreferences;
 
47
import android.provider.Contacts;
 
48
import android.provider.Contacts.PhonesColumns;
50
49
 
51
 
public class VcardImporter extends Importer
 
50
public class VCFImporter extends Importer
52
51
{
53
 
        private int _vcard_count = 0;
 
52
        private int _vCardCount = 0;
54
53
        private int _progress = 0;
55
54
 
56
 
        public VcardImporter( Doit doit )
 
55
        public VCFImporter( Doit doit )
57
56
        {
58
57
                super( doit );
59
58
        }
60
59
 
61
 
        @SuppressLint( "SdCardPath" )
62
60
        @Override
63
61
        protected void onImport() throws AbortImportException
64
62
        {
83
81
                                // get files
84
82
                                class VCardFilter implements FilenameFilter {
85
83
                                        public boolean accept( File dir, String name ) {
86
 
                                                return name.toLowerCase( Locale.US ).endsWith( ".vcf" );
 
84
                                                return name.toLowerCase().endsWith( ".vcf" );
87
85
                                        }
88
86
                                }
89
87
                                files = file.listFiles( new VCardFilter() );
111
109
                        countVCardFile( files[ i ] );
112
110
                        setTmpProgress( i );
113
111
                }
114
 
                setProgressMax( _vcard_count ); // will also update tmp progress
 
112
                setProgressMax( _vCardCount );  // will also update tmp progress
115
113
 
116
114
                // import them
117
115
                setProgress( 0 );
118
116
                for( int i = 0; i < files.length; i++ )
119
117
                        importVCardFile( files[ i ] );
120
 
                setProgress( _vcard_count );
121
118
        }
122
119
 
123
120
        private void countVCardFile( File file ) throws AbortImportException
130
127
 
131
128
                        // read
132
129
                        String line;
133
 
                        boolean in_vcard = false;
 
130
                        boolean inVCard = false;
134
131
                        while( ( line = reader.readLine() ) != null )
135
132
                        {
136
 
                                if( !in_vcard )
137
 
                                {
 
133
                                if( !inVCard ) {
138
134
                                        // look for vcard beginning
139
 
                                        if( line.matches( "(?i)BEGIN[ \t]*:[ \t]*VCARD.*" ) ) {
140
 
                                                in_vcard = true;
141
 
                                                _vcard_count++;
142
 
                                        }
143
 
                                        // check for vMsg files
144
 
                                        else if( line.matches( "(?i)BEGIN[ \t]*:[ \t]*VMSG.*" ) ) {
145
 
                                                showError( getText( R.string.error_vcf_vmsgfile )
146
 
                                                        + file.getName() );
 
135
                                        if( line.matches( "^BEGIN:VCARD" ) ) {
 
136
                                                inVCard = true;
 
137
                                                _vCardCount++;
147
138
                                        }
148
139
                                }
149
 
                                else if( line.matches( "(?i)END[ \t]*:[ \t]*VCARD.*" ) )
150
 
                                        in_vcard = false;
 
140
                                else if( line.matches( "^END:VCARD" ) )
 
141
                                        inVCard = false;
151
142
                        }
152
143
 
153
144
                }
176
167
                        FileInputStream istream = new FileInputStream( file );
177
168
                        byte[] content = new byte[ (int)file.length() ];
178
169
                        istream.read( content );
179
 
                        istream = null;
180
170
 
181
171
                        // import
182
172
                        importVCardFileContent( content, file.getName() );
183
173
                }
184
 
                catch( OutOfMemoryError e ) {
185
 
                        showError( R.string.error_outofmemory );
186
 
                }
187
174
                catch( FileNotFoundException e ) {
188
175
                        showError( getText( R.string.error_filenotfound ) +
189
176
                                file.getName() );
197
184
                throws AbortImportException
198
185
        {
199
186
                // go through lines
200
 
                Vcard vcard = null;
201
 
                int vcard_start_line = 0;
 
187
                VCard vCard = null;
202
188
                ContentLineIterator cli = new ContentLineIterator( content );
203
189
                while( cli.hasNext() )
204
190
                {
205
 
                        ContentLine content_line = cli.next();
206
 
 
207
 
                        // get a US-ASCII version of the string, for processing
208
 
                        String line = content_line.getUsAsciiLine();
209
 
 
210
 
                        if( vcard == null ) {
 
191
                        ByteBuffer buffer = cli.next();
 
192
 
 
193
                        // get a US-ASCII version of the line for processing
 
194
                        String line;
 
195
                        try {
 
196
                                line = new String( buffer.array(), buffer.position(),
 
197
                                        buffer.limit() - buffer.position(), "US-ASCII" );
 
198
                        }
 
199
                        catch( UnsupportedEncodingException e ) {
 
200
                                // we know US-ASCII is supported, so appease the compiler...
 
201
                                line = "";
 
202
                        }
 
203
 
 
204
                        if( vCard == null ) {
211
205
                                // look for vcard beginning
212
 
                                if( line.matches( "(?i)BEGIN[ \t]*:[ \t]*VCARD.*" ) ) {
213
 
                                        setProgress( _progress++ );
214
 
                                        vcard = new Vcard();
215
 
                                        vcard_start_line = cli.getLineNumber();
 
206
                                if( line.matches( "^BEGIN:VCARD" ) ) {
 
207
                                        setProgress( ++_progress );
 
208
                                        vCard = new VCard();
216
209
                                }
217
210
                        }
218
211
                        else {
219
212
                                // look for vcard content or ending
220
 
                                if( line.matches( "(?i)END[ \t]*:[ \t]*VCARD.*" ) )
 
213
                                if( line.matches( "^END:VCARD" ) )
221
214
                                {
222
 
                                        // finalise the vcard/contact
 
215
                                        // store vcard and do away with it
223
216
                                        try {
224
 
                                                vcard.finaliseVcard();
225
 
 
226
 
                                                // pass the finalised contact to the importer
227
 
                                                importContact( vcard );
228
 
                                        }
229
 
                                        catch( Vcard.ParseException e ) {
230
 
                                                if( !showContinue(
231
 
                                                        getText( R.string.error_vcf_parse ).toString()
232
 
                                                        + fileName +
233
 
                                                        getText( R.string.error_vcf_parse_line ).toString()
234
 
                                                        + cli.getLineNumber() + ":\n" + e.getMessage() ) )
235
 
                                                {
236
 
                                                        finish( ACTION_ABORT );
237
 
                                                }
238
 
                                                else
239
 
                                                        skipContact();
240
 
                                        }
241
 
                                        catch( ContactData.ContactNotIdentifiableException e ) {
242
 
                                                if( !showContinue(
243
 
                                                        getText( R.string.error_vcf_parse ).toString()
244
 
                                                        + fileName +
245
 
                                                        getText( R.string.error_vcf_parse_line ).toString()
246
 
                                                        + vcard_start_line + ":\n" + getText(
247
 
                                                                R.string.error_vcf_notenoughinfo ).toString()
248
 
                                                ) )
249
 
                                                {
250
 
                                                        finish( ACTION_ABORT );
251
 
                                                }
252
 
                                                else
253
 
                                                        skipContact();
254
 
                                        }
255
 
 
256
 
                                        // discard this vcard
257
 
                                        vcard = null;
 
217
                                                vCard.finaliseParsing();
 
218
                                                importContact( vCard );
 
219
                                        }
 
220
                                        catch( VCard.ParseException e ) {
 
221
                                                skipContact();
 
222
                                                if( !showContinue(
 
223
                                                        getText( R.string.error_vcf_parse ).toString()
 
224
                                                        + fileName + "\n" + e.getMessage() ) )
 
225
                                                {
 
226
                                                        finish( ACTION_ABORT );
 
227
                                                }
 
228
                                        }
 
229
                                        catch( VCard.SkipContactException e ) {
 
230
                                                skipContact();
 
231
                                                // do nothing
 
232
                                        }
 
233
                                        vCard = null;
258
234
                                }
259
235
                                else
260
236
                                {
261
237
                                        // try giving the line to the vcard
262
238
                                        try {
263
 
                                                vcard.parseLine( content_line );
 
239
                                                vCard.parseLine( buffer, line,
 
240
                                                        cli.doesNextLineLookFolded() );
264
241
                                        }
265
 
                                        catch( Vcard.ParseException e ) {
 
242
                                        catch( VCard.ParseException e ) {
266
243
                                                skipContact();
267
244
                                                if( !showContinue(
268
245
                                                        getText( R.string.error_vcf_parse ).toString()
269
 
                                                        + fileName +
270
 
                                                        getText( R.string.error_vcf_parse_line ).toString()
271
 
                                                        + cli.getLineNumber() + "\n" + e.getMessage() ) )
 
246
                                                        + fileName + "\n" + e.getMessage() ) )
272
247
                                                {
273
248
                                                        finish( ACTION_ABORT );
274
249
                                                }
276
251
                                                // although we're continuing, we still need to abort
277
252
                                                // this vCard. Further lines will be ignored until we
278
253
                                                // get to another BEGIN:VCARD line.
279
 
                                                vcard = null;
 
254
                                                vCard = null;
280
255
                                        }
281
 
                                        catch( Vcard.SkipImportException e ) {
 
256
                                        catch( VCard.SkipContactException e ) {
282
257
                                                skipContact();
283
258
                                                // abort this vCard. Further lines will be ignored until
284
259
                                                // we get to another BEGIN:VCARD line.
285
 
                                                vcard = null;
 
260
                                                vCard = null;
286
261
                                        }
287
262
                                }
288
263
                        }
289
264
                }
290
265
        }
291
266
 
292
 
        class ContentLine
293
 
        {
294
 
                private ByteBuffer _buffer;
295
 
                private boolean _folded_next;
296
 
                private String _line;
297
 
 
298
 
                public ContentLine( ByteBuffer buffer, boolean folded_next )
299
 
                {
300
 
                        _buffer = buffer;
301
 
                        _folded_next = folded_next;
302
 
                        _line = null;
303
 
                }
304
 
 
305
 
                public ByteBuffer getBuffer()
306
 
                {
307
 
                        return _buffer;
308
 
                }
309
 
 
310
 
                public boolean doesNextLineLookFolded()
311
 
                {
312
 
                        return _folded_next;
313
 
                }
314
 
 
315
 
                public String getUsAsciiLine()
316
 
                {
317
 
                        // generated line and cache it
318
 
                        if( _line == null ) {
319
 
                                try {
320
 
                                        _line = new String( _buffer.array(), _buffer.position(),
321
 
                                                _buffer.limit() - _buffer.position(), "US-ASCII" );
322
 
                                }
323
 
                                catch( UnsupportedEncodingException e ) {
324
 
                                        // we know US-ASCII *is* supported, so appease the
325
 
                                        // compiler...
326
 
                                }
327
 
                        }
328
 
 
329
 
                        // return cached line
330
 
                        return _line;
331
 
                }
332
 
        }
333
 
 
334
 
        class ContentLineIterator implements Iterator< ContentLine >
 
267
        class ContentLineIterator implements Iterator< ByteBuffer >
335
268
        {
336
269
                protected byte[] _content = null;
337
270
                protected int _pos = 0;
338
 
                protected int _line = 0;
339
271
 
340
272
                public ContentLineIterator( byte[] content )
341
273
                {
349
281
                }
350
282
 
351
283
                @Override
352
 
                public ContentLine next()
 
284
                public ByteBuffer next()
353
285
                {
354
286
                        int initial_pos = _pos;
355
287
 
361
293
                                        int to = ( _pos > 0 && _content[ _pos - 1 ] == '\r' &&
362
294
                                                _pos > initial_pos )? _pos - 1 : _pos;
363
295
                                        _pos++;
364
 
                                        _line++;
365
 
                                        return new ContentLine(
366
 
                                                ByteBuffer.wrap( _content, initial_pos,
367
 
                                                        to - initial_pos ),
368
 
                                                doesNextLineLookFolded() );
 
296
                                        return ByteBuffer.wrap( _content, initial_pos,
 
297
                                                to - initial_pos );
369
298
                                }
370
299
 
371
300
                        // we didn't find one, but were there bytes left?
372
301
                        if( _pos != initial_pos ) {
373
302
                                int to = _pos;
374
303
                                _pos++;
375
 
                                _line++;
376
 
                                return new ContentLine(
377
 
                                        ByteBuffer.wrap( _content, initial_pos,
378
 
                                                to - initial_pos ),
379
 
                                        doesNextLineLookFolded() );
 
304
                                return ByteBuffer.wrap( _content, initial_pos,
 
305
                                        to - initial_pos );
380
306
                        }
381
307
 
382
308
                        // no bytes left
394
320
                 * onto the end of this one?
395
321
                 * @return
396
322
                 */
397
 
                private boolean doesNextLineLookFolded()
 
323
                public boolean doesNextLineLookFolded()
398
324
                {
399
325
                        return _pos > 0 && _pos < _content.length &&
400
 
                                _content[ _pos - 1 ] == '\n' &&
401
 
                                ( _content[ _pos ] == ' ' || _content[ _pos ] == '\t' );
402
 
                }
403
 
 
404
 
                public int getLineNumber()
405
 
                {
406
 
                        return _line;
 
326
                                _content[ _pos - 1 ] == '\n' && _content[ _pos ] == ' ';
407
327
                }
408
328
        }
409
329
 
410
 
        private class Vcard extends ContactData
 
330
        private class VCard extends ContactData
411
331
        {
412
332
                private final static int NAMELEVEL_NONE = 0;
413
 
                private final static int NAMELEVEL_N = 1;
 
333
                private final static int NAMELEVEL_ORG = 1;
414
334
                private final static int NAMELEVEL_FN = 2;
415
 
 
416
 
                private final static int MULTILINE_NONE = 0;
417
 
                private final static int MULTILINE_ENCODED = 1; // v2.1 quoted-printable
418
 
                private final static int MULTILINE_ESCAPED = 2; // v2.1 \\CRLF
419
 
                private final static int MULTILINE_FOLDED = 3;  // MIME-DIR folding
 
335
                private final static int NAMELEVEL_N = 3;
420
336
 
421
337
                private String _version = null;
422
 
                private Vector< ContentLine > _content_lines = null;
 
338
                private Vector< ByteBuffer > _buffers = null;
423
339
                private int _name_level = NAMELEVEL_NONE;
424
 
                private int _parser_multiline_state = MULTILINE_NONE;
 
340
                private boolean _parser_in_encoded_multiline = false;
 
341
                private boolean _parser_in_folded_multiline = false;
425
342
                private String _parser_current_name_and_params = null;
426
343
                private String _parser_buffered_value_so_far = "";
427
 
                private String _cached_organisation = null;
428
 
                private String _cached_title = null;
429
344
 
430
345
                protected class UnencodeResult
431
346
                {
461
376
 
462
377
                        public ParseException( int res )
463
378
                        {
464
 
                                super( VcardImporter.this.getText( res ).toString() );
 
379
                                super( VCFImporter.this.getText( res ).toString() );
465
380
                        }
466
381
                }
467
382
 
468
383
                @SuppressWarnings("serial")
469
 
                protected class SkipImportException extends Exception { }
 
384
                protected class SkipContactException extends Exception { }
470
385
 
471
 
                private String extractCollonPartFromLine( ContentLine content_line,
472
 
                        boolean former )
 
386
                private String extractCollonPartFromLine( ByteBuffer buffer,
 
387
                        String line, boolean former )
473
388
                {
474
389
                        String ret = null;
475
390
 
 
391
                        // get a US-ASCII version of the line for processing, unless we were
 
392
                        // supplied with one
 
393
                        if( line == null ) {
 
394
                                try {
 
395
                                        line = new String( buffer.array(), buffer.position(),
 
396
                                                buffer.limit() - buffer.position(), "US-ASCII" );
 
397
                                }
 
398
                                catch( UnsupportedEncodingException e ) {
 
399
                                        // we know US-ASCII is supported, so appease the compiler...
 
400
                                        line = "";
 
401
                                }
 
402
                        }
 
403
 
476
404
                        // split line into name and value parts and check to make sure we
477
405
                        // only got 2 parts and that the first part is not zero in length
478
 
                        String[] parts = content_line.getUsAsciiLine().split( ":", 2 );
 
406
                        String[] parts = line.split( ":", 2 );
479
407
                        if( parts.length == 2 && parts[ 0 ].length() > 0 )
480
408
                                ret = parts[ former? 0 : 1 ];
481
409
 
482
410
                        return ret;
483
411
                }
484
412
 
485
 
                private String extractNameAndParamsFromLine( ContentLine content_line )
486
 
                {
487
 
                        return extractCollonPartFromLine( content_line, true ).trim();
488
 
                }
489
 
 
490
 
                private String extractValueFromLine( ContentLine content_line )
491
 
                {
492
 
                        return extractCollonPartFromLine( content_line, false );
493
 
                }
494
 
 
495
 
                public void parseLine( ContentLine content_line )
496
 
                        throws ParseException, SkipImportException,
 
413
                private String extractNameAndParamsFromLine( ByteBuffer buffer,
 
414
                        String line )
 
415
                {
 
416
                        return extractCollonPartFromLine( buffer, line, true );
 
417
                }
 
418
 
 
419
                private String extractValueFromLine( ByteBuffer buffer, String line )
 
420
                {
 
421
                        return extractCollonPartFromLine( buffer, line, false );
 
422
                }
 
423
 
 
424
                public void parseLine( ByteBuffer buffer, String line,
 
425
                        boolean next_line_looks_folded )
 
426
                        throws ParseException, SkipContactException,
497
427
                        AbortImportException
498
428
                {
499
429
                        // do we have a version yet?
501
431
                        {
502
432
                                // tentatively get name and params from line
503
433
                                String name_and_params =
504
 
                                        extractNameAndParamsFromLine( content_line );
 
434
                                        extractNameAndParamsFromLine( buffer, line );
505
435
 
506
436
                                // is it a version line?
507
437
                                if( name_and_params != null &&
508
 
                                        name_and_params.equalsIgnoreCase( "VERSION" ) )
 
438
                                        name_and_params.equals( "VERSION" ) )
509
439
                                {
510
440
                                        // yes, get it!
511
 
                                        String value = extractValueFromLine( content_line ).trim();
 
441
                                        String value = extractValueFromLine( buffer, line );
512
442
                                        if( !value.equals( "2.1" ) && !value.equals( "3.0" ) )
513
443
                                                throw new ParseException( R.string.error_vcf_version );
514
444
                                        _version = value;
515
445
 
516
446
                                        // parse any buffers we've been accumulating while we waited
517
447
                                        // for a version
518
 
                                        if( _content_lines != null )
519
 
                                                for( int i = 0; i < _content_lines.size(); i++ )
520
 
                                                        parseLine( _content_lines.get( i ) );
521
 
                                        _content_lines = null;
 
448
                                        if( _buffers != null )
 
449
                                                for( int i = 0; i < _buffers.size(); i++ )
 
450
                                                        parseLine( _buffers.get( i ), null,
 
451
                                                                i + 1 < _buffers.size() &&
 
452
                                                                _buffers.get( i + 1 ).hasRemaining() &&
 
453
                                                                _buffers.get( i + 1 ).get(
 
454
                                                                        _buffers.get( i + 1 ).position() ) == ' ' );
 
455
                                        _buffers = null;
522
456
                                }
523
457
                                else
524
458
                                {
525
459
                                        // no, so stash this line till we get a version
526
 
                                        if( _content_lines == null )
527
 
                                                _content_lines = new Vector< ContentLine >();
528
 
                                        _content_lines.add( content_line );
 
460
                                        if( _buffers == null )
 
461
                                                _buffers = new Vector< ByteBuffer >();
 
462
                                        _buffers.add( buffer );
529
463
                                }
530
464
                        }
531
465
                        else
532
466
                        {
533
467
                                // name and params and the position in the buffer where the
534
 
                                // "value" part of the line starts
 
468
                                // "value" part of the line start
535
469
                                String name_and_params;
536
470
                                int pos;
537
471
 
538
 
                                if( _parser_multiline_state != MULTILINE_NONE )
 
472
                                if( _parser_in_encoded_multiline ||
 
473
                                        _parser_in_folded_multiline )
539
474
                                {
540
475
                                        // if we're currently in a multi-line value, use the stored
541
476
                                        // property name and parameters
542
477
                                        name_and_params = _parser_current_name_and_params;
543
478
 
544
 
                                        // skip some initial line characters, depending on the type
545
 
                                        // of multi-line we're handling
546
 
                                        pos = content_line.getBuffer().position();
547
 
                                        switch( _parser_multiline_state )
548
 
                                        {
549
 
                                        case MULTILINE_FOLDED:
 
479
                                        pos = buffer.position();
 
480
 
 
481
                                        // for folded multi-lines, skip the single space at the
 
482
                                        // start of the next line
 
483
                                        if( _parser_in_folded_multiline )
550
484
                                                pos++;
551
 
                                                break;
552
 
                                        case MULTILINE_ENCODED:
553
 
                                                while( pos < content_line.getBuffer().limit() && (
554
 
                                                        content_line.getBuffer().get( pos ) == ' ' ||
555
 
                                                        content_line.getBuffer().get( pos ) == '\t' ) )
 
485
 
 
486
                                        // else, this must be an encoded multi-line, so skip any
 
487
                                        // whitespace we find at the start of the next line
 
488
                                        else
 
489
                                                while( pos < buffer.limit() && (
 
490
                                                        buffer.get( pos ) == ' ' ||
 
491
                                                        buffer.get( pos ) == '\t' ) )
556
492
                                                {
557
493
                                                        pos++;
558
494
                                                }
559
 
                                                break;
560
 
                                        default:
561
 
                                                // do nothing
562
 
                                        }
563
 
 
564
 
                                        // take us out of multi-line so that we can re-detect that
565
 
                                        // this line is a multi-line or not
566
 
                                        _parser_multiline_state = MULTILINE_NONE;
567
495
                                }
568
496
                                else
569
497
                                {
570
 
                                        // skip empty lines
571
 
                                        if( content_line.getUsAsciiLine().trim().length() == 0 )
572
 
                                                return;
573
 
 
574
498
                                        // get name and params from line, and since we're not
575
499
                                        // parsing a subsequent line in a multi-line, this should
576
500
                                        // not fail, or it's an error
577
501
                                        name_and_params =
578
 
                                                extractNameAndParamsFromLine( content_line );
 
502
                                                extractNameAndParamsFromLine( buffer, line );
579
503
                                        if( name_and_params == null )
580
504
                                                throw new ParseException(
581
505
                                                        R.string.error_vcf_malformed );
582
506
 
583
507
                                        // calculate how many chars to skip from beginning of line
584
508
                                        // so we skip the property "name:" part
585
 
                                        pos = content_line.getBuffer().position() +
586
 
                                                name_and_params.length() + 1;
 
509
                                        pos = buffer.position() + name_and_params.length() + 1;
587
510
 
588
511
                                        // reset the saved multi-line state
589
512
                                        _parser_current_name_and_params = name_and_params;
592
515
 
593
516
                                // get value from buffer, as raw bytes
594
517
                                ByteBuffer value;
595
 
                                value = ByteBuffer.wrap( content_line.getBuffer().array(), pos,
596
 
                                        content_line.getBuffer().limit() - pos );
 
518
                                value = ByteBuffer.wrap( buffer.array(), pos,
 
519
                                        buffer.limit() - pos );
597
520
 
598
521
                                // get parameter parts
599
522
                                String[] name_param_parts = name_and_params.split( ";", -1 );
600
523
                                for( int i = 0; i < name_param_parts.length; i++ )
601
524
                                        name_param_parts[ i ] = name_param_parts[ i ].trim();
602
525
 
603
 
                                // determine whether we care about this entry
604
 
                                final HashSet< String > interesting_fields =
605
 
                                        new HashSet< String >( Arrays.asList( new String[] { "N",
606
 
                                                "FN", "ORG", "TITLE", "TEL", "EMAIL", "ADR", "LABEL" }
607
 
                                ) );
608
 
                                boolean is_interesting_field =
609
 
                                        interesting_fields.contains(
610
 
                                                name_param_parts[ 0 ].toUpperCase( Locale.US ) );
611
 
 
612
526
                                // parse encoding parameter
613
527
                                String encoding = checkParam( name_param_parts, "ENCODING" );
614
 
                                if( encoding != null )
615
 
                                        encoding = encoding.toUpperCase( Locale.US );
616
 
                                if( is_interesting_field && encoding != null &&
617
 
                                        !encoding.equalsIgnoreCase( "8BIT" ) &&
618
 
                                        !encoding.equalsIgnoreCase( "QUOTED-PRINTABLE" ) )
619
 
                                        //&& !encoding.equalsIgnoreCase( "BASE64" ) )
 
528
                                if( encoding != null ) encoding = encoding.toUpperCase();
 
529
                                if( encoding != null && !encoding.equals( "8BIT" ) &&
 
530
                                        !encoding.equals( "QUOTED-PRINTABLE" ) )
 
531
                                        //&& !encoding.equals( "BASE64" ) )
620
532
                                {
621
533
                                        throw new ParseException( R.string.error_vcf_encoding );
622
534
                                }
623
535
 
624
536
                                // parse charset parameter
625
537
                                String charset = checkParam( name_param_parts, "CHARSET" );
626
 
                                if( charset != null )
627
 
                                        charset = charset.toUpperCase( Locale.US );
628
 
                                if( charset != null &&
629
 
                                        !charset.equalsIgnoreCase( "US-ASCII" ) &&
630
 
                                        !charset.equalsIgnoreCase( "ASCII" ) &&
631
 
                                        !charset.equalsIgnoreCase( "UTF-8" ) )
 
538
                                if( charset != null ) charset = charset.toUpperCase();
 
539
                                if( charset != null && !charset.equals( "US-ASCII" ) &&
 
540
                                        !charset.equals( "ASCII" ) &&
 
541
                                        !charset.equals( "UTF-8" ) )
632
542
                                {
633
543
                                        throw new ParseException( R.string.error_vcf_charset );
634
544
                                }
636
546
                                // do unencoding (or default to a fake unencoding result with
637
547
                                // the raw string)
638
548
                                UnencodeResult unencoding_result = null;
639
 
                                if( encoding != null &&
640
 
                                        encoding.equalsIgnoreCase( "QUOTED-PRINTABLE" ) )
641
 
                                {
 
549
                                if( encoding != null && encoding.equals( "QUOTED-PRINTABLE" ) )
642
550
                                        unencoding_result = unencodeQuotedPrintable( value );
643
 
                                }
644
 
//                              else if( encoding != null &&
645
 
//                                      encoding.equalsIgnoreCase( "BASE64" ) )
646
 
//                              {
 
551
//                              else if( encoding != null && encoding.equals( "BASE64" ) )
647
552
//                                      unencoding_result = unencodeBase64( props[ 1 ], charset );
648
 
//                              }
649
553
                                if( unencoding_result != null ) {
650
554
                                        value = unencoding_result.getBuffer();
651
 
                                        if( unencoding_result.isAnotherLineRequired() )
652
 
                                                _parser_multiline_state = MULTILINE_ENCODED;
 
555
                                        _parser_in_encoded_multiline =
 
556
                                                unencoding_result.isAnotherLineRequired();
653
557
                                }
654
558
 
655
 
                                // convert 8-bit US-ASCII charset to UTF-8 (where no charset is
656
 
                                // specified for a v2.1 vcard entry, we assume it's US-ASCII)
657
 
                                if( ( charset == null && _version.equals( "2.1" ) ) ||
658
 
                                        ( charset != null && (
659
 
                                                charset.equalsIgnoreCase( "ASCII" ) ||
660
 
                                                charset.equalsIgnoreCase( "US-ASCII" ) ) ) )
661
 
                                {
 
559
                                // convert 8-bit ASCII charset to US-ASCII
 
560
                                if( charset == null || charset.equals( "ASCII" ) ) {
662
561
                                        value = transcodeAsciiToUtf8( value );
 
562
                                        charset = "UTF-8";
663
563
                                }
664
564
 
665
 
                                // process charset (value is now in UTF-8)
 
565
                                // process charset
666
566
                                String string_value;
667
567
                                try {
668
568
                                        string_value = new String( value.array(), value.position(),
669
 
                                                value.limit() - value.position(), "UTF-8" );
 
569
                                                value.limit() - value.position(), charset );
670
570
                                } catch( UnsupportedEncodingException e ) {
671
571
                                        throw new ParseException( R.string.error_vcf_charset );
672
572
                                }
673
573
 
674
 
                                // for some entries that have semicolon-separated value parts,
675
 
                                // check to see if the value ends in an escape character, which
676
 
                                // indicates that we have a multi-line value
677
 
                                if( ( name_param_parts[ 0 ].equalsIgnoreCase( "N" ) ||
678
 
                                        name_param_parts[ 0 ].equalsIgnoreCase( "ORG" ) ||
679
 
                                        name_param_parts[ 0 ].equalsIgnoreCase( "ADR" ) ) &&
680
 
                                        doesStringEndInAnEscapeChar( string_value ) )
681
 
                                {
682
 
                                        _parser_multiline_state = MULTILINE_ESCAPED;
683
 
                                        string_value = string_value.substring( 0,
684
 
                                                string_value.length() - 1 );
685
 
                                }
686
 
 
687
 
                                // if we know we're not in an encoding-based multi-line, check
688
 
                                // to see if we're in a folded multi-line
689
 
                                if( _parser_multiline_state == MULTILINE_NONE &&
690
 
                                        content_line.doesNextLineLookFolded() )
691
 
                                {
692
 
                                        _parser_multiline_state = MULTILINE_FOLDED;
693
 
                                }
694
 
 
695
 
                                // handle multi-lines by buffering them and parsing them when we
696
 
                                // are processing the last line in a multi-line sequence
697
 
                                if( _parser_multiline_state != MULTILINE_NONE ) {
 
574
                                // now we know whether we're in an encoding multi-line,
 
575
                                // determine if we're in a v3 folded multi-line or not
 
576
                                _parser_in_folded_multiline = !_parser_in_encoded_multiline &&
 
577
                                        _version.equals( "3.0" ) && next_line_looks_folded;
 
578
 
 
579
                                // handle multi-line requests
 
580
                                if( _parser_in_encoded_multiline ||
 
581
                                        _parser_in_folded_multiline )
 
582
                                {
698
583
                                        _parser_buffered_value_so_far += string_value;
699
584
                                        return;
700
585
                                }
 
586
 
 
587
                                // add on buffered multi-line content
701
588
                                String complete_value =
702
 
                                        ( _parser_buffered_value_so_far + string_value ).trim();
 
589
                                        _parser_buffered_value_so_far + string_value;
703
590
 
704
591
                                // ignore empty values
705
592
                                if( complete_value.length() < 1 ) return;
706
593
 
707
594
                                // parse some properties
708
 
                                if( name_param_parts[ 0 ].equalsIgnoreCase( "N" ) )
 
595
                                if( name_param_parts[ 0 ].equals( "N" ) )
709
596
                                        parseN( name_param_parts, complete_value );
710
 
                                else if( name_param_parts[ 0 ].equalsIgnoreCase( "FN" ) )
 
597
                                else if( name_param_parts[ 0 ].equals( "FN" ) )
711
598
                                        parseFN( name_param_parts, complete_value );
712
 
                                else if( name_param_parts[ 0 ].equalsIgnoreCase( "ORG" ) )
 
599
                                else if( name_param_parts[ 0 ].equals( "ORG" ) )
713
600
                                        parseORG( name_param_parts, complete_value );
714
 
                                else if( name_param_parts[ 0 ].equalsIgnoreCase( "TITLE" ) )
715
 
                                        parseTITLE( name_param_parts, complete_value );
716
 
                                else if( name_param_parts[ 0 ].equalsIgnoreCase( "TEL" ) )
 
601
                                else if( name_param_parts[ 0 ].equals( "TEL" ) )
717
602
                                        parseTEL( name_param_parts, complete_value );
718
 
                                else if( name_param_parts[ 0 ].equalsIgnoreCase( "EMAIL" ) )
 
603
                                else if( name_param_parts[ 0 ].equals( "EMAIL" ) )
719
604
                                        parseEMAIL( name_param_parts, complete_value );
720
 
                                else if( name_param_parts[ 0 ].equalsIgnoreCase( "ADR" ) )
721
 
                                        parseADR( name_param_parts, complete_value );
722
 
                                else if( name_param_parts[ 0 ].equalsIgnoreCase( "LABEL" ) )
723
 
                                        parseLABEL( name_param_parts, complete_value );
724
 
                                else if( name_param_parts[ 0 ].equalsIgnoreCase( "NOTE" ) )
725
 
                                        parseNOTE( name_param_parts, complete_value );
726
 
                        }
727
 
                }
728
 
 
729
 
                private boolean doesStringEndInAnEscapeChar( String string )
730
 
                {
731
 
                        // count the number of backslashes at the end of the string
732
 
                        int count = 0;
733
 
                        for( int a = string.length() - 1; a >= 0; a-- )
734
 
                                if( string.charAt( a ) == '\\' )
735
 
                                        count++;
736
 
                                else
737
 
                                        break;
738
 
 
739
 
                        // if there are an even number of backslashes then the final one
740
 
                        // doesn't count
741
 
                        return ( count & 1 ) == 1;
742
 
                }
743
 
 
744
 
                private String[] splitValueByCharacter( String value, char character )
745
 
                {
746
 
                        // split string in to parts by specified character
747
 
                        ArrayList< String > parts = new ArrayList< String >(
748
 
                                Arrays.asList( value.split( "" + character ) ) );
749
 
 
750
 
                        // go through parts
751
 
                        for( int a = 0; a < parts.size(); a++ )
752
 
                        {
753
 
                                String str = parts.get( a );
754
 
 
755
 
                                // look for parts that end in an escape character, but ignore
756
 
                                // the final part. We've already detected escape chars at the
757
 
                                // end of the final part in parseLine() and handled multi-lines
758
 
                                // accordingly.
759
 
                                if( a < parts.size() - 1 &&
760
 
                                        doesStringEndInAnEscapeChar( str ) )
761
 
                                {
762
 
                                        // append the escaped character, join the next part to this
763
 
                                        // part and remove the next part
764
 
                                        parts.set( a, str.substring( 0, str.length() - 1 ) +
765
 
                                                character + parts.get( a + 1 ) );
766
 
                                        parts.remove( a + 1 );
767
 
 
768
 
                                        // re-visit this part
769
 
                                        a--;
770
 
                                        continue;
771
 
                                }
772
 
 
773
 
                                // trim and replace string
774
 
                                str = str.trim();
775
 
                                parts.set( a, str );
776
 
                        }
777
 
 
778
 
                        String[] ret = new String[ parts.size() ];
779
 
                        return parts.toArray( ret );
780
 
                }
781
 
 
782
 
                private String unescapeValue( String value )
783
 
                {
784
 
                        StringBuilder ret = new StringBuilder( value.length() );
785
 
                        boolean in_escape = false;
786
 
                        for( int a = 0; a < value.length(); a++ )
787
 
                        {
788
 
                                int c = value.codePointAt( a );
789
 
 
790
 
                                // process a normal character
791
 
                                if( !in_escape ) {
792
 
                                        if( c == '\\' )
793
 
                                                in_escape = true;
794
 
                                        else
795
 
                                                ret.append( Character.toChars( c ) );
796
 
                                        continue;
797
 
                                }
798
 
 
799
 
                                // process an escape sequence
800
 
                                in_escape = false;
801
 
                                switch( c )
802
 
                                {
803
 
                                case 'T':
804
 
                                case 't':
805
 
                                        // add tab (invalid/non-standard, but accepted)
806
 
                                        ret.append( '\t' );
807
 
                                        break;
808
 
                                case 'N':
809
 
                                case 'n':
810
 
                                        // add newline
811
 
                                        ret.append( '\n' );
812
 
                                        break;
813
 
                                case '\\':
814
 
                                case ',':
815
 
                                case ';':
816
 
                                        // add escaped character
817
 
                                        ret.append( Character.toChars( c ) );
818
 
                                        break;
819
 
                                default:
820
 
                                        // unknown escape sequence, so add it unescaped
821
 
                                        // (invalid/non-standard, but accepted)
822
 
                                        ret.append( "\\" );
823
 
                                        ret.append( Character.toChars( c ) );
824
 
                                        break;
825
 
                                }
826
 
                        }
827
 
 
828
 
                        return ret.toString();
 
605
                        }
829
606
                }
830
607
 
831
608
                private void parseN( String[] params, String value )
 
609
                        throws ParseException, SkipContactException,
 
610
                        AbortImportException
832
611
                {
833
612
                        // already got a better name?
834
613
                        if( _name_level >= NAMELEVEL_N ) return;
835
614
 
836
615
                        // get name parts
837
 
                        String[] name_parts = splitValueByCharacter( value, ';' );
 
616
                        String[] name_parts = value.split( ";" );
 
617
                        for( int i = 0; i < name_parts.length; i++ )
 
618
                                name_parts[ i ] = name_parts[ i ].trim();
838
619
 
839
620
                        // build name
840
621
                        value = "";
841
 
                        final int[] part_order = { 3, 1, 2, 0, 4 };
842
 
                        for( int a = 0; a < part_order.length; a++ )
843
 
                                if( name_parts.length > part_order[ a ] &&
844
 
                                        name_parts[ part_order[ a ] ].length() > 0 )
845
 
                                {
846
 
                                        // split this part in to it's comma-separated bits
847
 
                                        String[] name_part_parts = splitValueByCharacter(
848
 
                                                name_parts[ part_order[ a ] ], ',' );
849
 
                                        for( int b = 0; b < name_part_parts.length; b++ )
850
 
                                                if( name_part_parts[ b ].length() > 0 )
851
 
                                                {
852
 
                                                        if( value.length() > 0 ) value += " ";
853
 
                                                        value += name_part_parts[ b ];
854
 
                                                }
855
 
                                }
 
622
                        if( name_parts.length > 1 && name_parts[ 1 ].length() > 0 )
 
623
                                value += name_parts[ 1 ];
 
624
                        if( name_parts.length > 0 && name_parts[ 0 ].length() > 0 )
 
625
                                value += ( value.length() == 0? "" : " " ) + name_parts[ 0 ];
856
626
 
857
627
                        // set name
858
 
                        setName( unescapeValue( value ) );
 
628
                        setName( value );
859
629
                        _name_level = NAMELEVEL_N;
 
630
 
 
631
                        // check now to see if we need to import this contact (to avoid
 
632
                        // parsing the rest of the vCard unnecessarily)
 
633
                        if( !isImportRequired( getName() ) )
 
634
                                throw new SkipContactException();
860
635
                }
861
636
 
862
637
                private void parseFN( String[] params, String value )
 
638
                        throws ParseException, SkipContactException
863
639
                {
864
640
                        // already got a better name?
865
641
                        if( _name_level >= NAMELEVEL_FN ) return;
866
642
 
867
643
                        // set name
868
 
                        setName( unescapeValue( value ) );
 
644
                        setName( value );
869
645
                        _name_level = NAMELEVEL_FN;
870
646
                }
871
647
 
872
648
                private void parseORG( String[] params, String value )
 
649
                        throws ParseException, SkipContactException
873
650
                {
 
651
                        // already got a better name?
 
652
                        if( _name_level >= NAMELEVEL_ORG ) return;
 
653
 
874
654
                        // get org parts
875
 
                        String[] org_parts = splitValueByCharacter( value, ';' );
876
 
                        if( org_parts == null || org_parts.length < 1 ) return;
877
 
 
878
 
                        // build organisation name
879
 
                        StringBuilder builder = new StringBuilder(
880
 
                                String.valueOf( org_parts[ 0 ] ) );
881
 
                        for( int a = 1; a < org_parts.length; a++ )
882
 
                                builder.append( ", " ).append( org_parts[ a ] );
883
 
                        String organisation = unescapeValue( builder.toString() );
884
 
 
885
 
                        // set organisation name (using a title we've previously found)
886
 
                        addOrganisation( organisation, _cached_title, true );
887
 
 
888
 
                        // if we've not previously found a title, store this organisation
889
 
                        // name (we'll need it when we find a title to update the
890
 
                        // organisation, by name), else if we *have* previously found a
891
 
                        // title, clear it (since we just used it)
892
 
                        if( _cached_title == null )
893
 
                                _cached_organisation = organisation;
894
 
                        else
895
 
                                _cached_title = null;
896
 
                }
897
 
 
898
 
                private void parseTITLE( String[] params, String value )
899
 
                {
900
 
                        value = unescapeValue( value );
901
 
 
902
 
                        // if we previously had an organisation, look it up and append this
903
 
                        // title to it
904
 
                        if( _cached_organisation != null && hasOrganisations() ) {
905
 
                                HashMap< String, ExtraDetail > datas = getOrganisations();
906
 
                                ExtraDetail detail = datas.get( _cached_organisation );
907
 
                                if( detail != null )
908
 
                                        detail.setExtra( value );
909
 
                        }
910
 
 
911
 
                        // same as when handling organisation, if we've not previously found
912
 
                        // an organisation we store this title, else we clear it (since we
913
 
                        // just appended this title to it)
914
 
                        if( _cached_organisation == null )
915
 
                                _cached_title = value;
916
 
                        else
917
 
                                _cached_organisation = null;
 
655
                        String[] org_parts = value.split( ";" );
 
656
                        for( int i = 0; i < org_parts.length; i++ )
 
657
                                org_parts[ i ] = org_parts[ i ].trim();
 
658
 
 
659
                        // build name
 
660
                        if( org_parts.length > 1 && org_parts[ 0 ].length() == 0 )
 
661
                                value = org_parts[ 1 ];
 
662
                        else
 
663
                                value = org_parts[ 0 ];
 
664
 
 
665
                        // set name
 
666
                        setName( value );
 
667
                        _name_level = NAMELEVEL_ORG;
918
668
                }
919
669
 
920
670
                private void parseTEL( String[] params, String value )
 
671
                        throws ParseException
921
672
                {
922
673
                        if( value.length() == 0 ) return;
923
674
 
926
677
                                "PAGER", "BBS", "MODEM", "CAR", "ISDN", "VIDEO" ) );
927
678
 
928
679
                        // here's the logic...
929
 
                        boolean is_preferred = types.contains( "PREF" );
930
 
                        int type;
 
680
                        boolean preferred = types.contains( "PREF" );
 
681
                        int type = PhonesColumns.TYPE_MOBILE;
 
682
                        if( types.contains( "VOICE" ) )
 
683
                                if( types.contains( "WORK" ) )
 
684
                                        type = PhonesColumns.TYPE_WORK;
 
685
                                else
 
686
                                        type = PhonesColumns.TYPE_HOME;
 
687
                        else if( types.contains( "CELL" ) || types.contains( "VIDEO" ) )
 
688
                                type = PhonesColumns.TYPE_MOBILE;
931
689
                        if( types.contains( "FAX" ) )
932
690
                                if( types.contains( "HOME" ) )
933
 
                                        type = TYPE_FAX_HOME;
 
691
                                        type = PhonesColumns.TYPE_FAX_HOME;
934
692
                                else
935
 
                                        type = TYPE_FAX_WORK;
936
 
                        else if( types.contains( "CELL" ) || types.contains( "VIDEO" ) )
937
 
                                type = TYPE_MOBILE;
938
 
                        else if( types.contains( "PAGER" ) )
939
 
                                type = TYPE_PAGER;
940
 
                        else if( types.contains( "WORK" ) )
941
 
                                type = TYPE_WORK;
942
 
                        else
943
 
                                type = TYPE_HOME;
 
693
                                        type = PhonesColumns.TYPE_FAX_WORK;
 
694
                        if( types.contains( "PAGER" ) )
 
695
                                type = PhonesColumns.TYPE_PAGER;
944
696
 
945
697
                        // add phone number
946
 
                        addNumber( value, type, is_preferred );
 
698
                        addPhone( value, type, preferred );
947
699
                }
948
700
 
949
701
                public void parseEMAIL( String[] params, String value )
 
702
                        throws ParseException
950
703
                {
951
704
                        if( value.length() == 0 ) return;
952
705
 
953
706
                        Set< String > types = extractTypes( params, Arrays.asList(
954
707
                                "PREF", "WORK", "HOME", "INTERNET" ) );
955
708
 
956
 
                        // add email address
957
 
                        boolean is_preferred = types.contains( "PREF" );
958
 
                        int type;
959
 
                        if( types.contains( "WORK" ) )
960
 
                                type = TYPE_WORK;
961
 
                        else
962
 
                                type = TYPE_HOME;
963
 
 
964
 
                        addEmail( unescapeValue( value ), type, is_preferred );
965
 
                }
966
 
 
967
 
                private void parseADR( String[] params, String value )
968
 
                {
969
 
                        // get address parts
970
 
                        String[] adr_parts = splitValueByCharacter( value, ';' );
971
 
 
972
 
                        // build address
973
 
                        value = "";
974
 
                        for( int a = 0; a < adr_parts.length; a++ )
975
 
                                if( adr_parts[ a ].length() > 0 )
976
 
                                {
977
 
                                        // version 3.0 vCards allow further splitting by comma
978
 
                                        if( _version.equals( "3.0" ) )
979
 
                                        {
980
 
                                                // split this part in to it's comma-separated bits and
981
 
                                                // add them on individual lines
982
 
                                                String[] adr_part_parts =
983
 
                                                        splitValueByCharacter( adr_parts[ a ], ',' );
984
 
                                                for( int b = 0; b < adr_part_parts.length; b++ )
985
 
                                                        if( adr_part_parts[ b ].length() > 0 )
986
 
                                                        {
987
 
                                                                if( value.length() > 0 ) value += "\n";
988
 
                                                                value += adr_part_parts[ b ];
989
 
                                                        }
990
 
                                        }
991
 
                                        else
992
 
                                        {
993
 
                                                // add this part on an individual line
994
 
                                                if( value.length() > 0 ) value += "\n";
995
 
                                                value += adr_parts[ a ];
996
 
                                        }
997
 
                                }
998
 
 
999
 
                        Set< String > types = extractTypes( params, Arrays.asList(
1000
 
                                "PREF", "WORK", "HOME" ) );
1001
 
 
1002
 
                        // add address
1003
 
                        int type;
1004
 
                        if( types.contains( "WORK" ) )
1005
 
                                type = TYPE_WORK;
1006
 
                        else
1007
 
                                type = TYPE_HOME;
1008
 
 
1009
 
                        addAddress( unescapeValue( value ), type );
1010
 
                }
1011
 
 
1012
 
                private void parseLABEL( String[] params, String value )
1013
 
                {
1014
 
                        Set< String > types = extractTypes( params, Arrays.asList(
1015
 
                                "PREF", "WORK", "HOME" ) );
1016
 
 
1017
 
                        // add address
1018
 
                        int type;
1019
 
                        if( types.contains( "WORK" ) )
1020
 
                                type = TYPE_WORK;
1021
 
                        else
1022
 
                                type = TYPE_HOME;
1023
 
 
1024
 
                        addAddress( unescapeValue( value ), type );
1025
 
                }
1026
 
 
1027
 
                private void parseNOTE( String[] params, String value )
1028
 
                {
1029
 
                        addNote( unescapeValue( value ) );
1030
 
                }
1031
 
 
1032
 
                public void finaliseVcard()
1033
 
                        throws ParseException, ContactNotIdentifiableException
 
709
                        // here's the logic...
 
710
                        boolean preferred = types.contains( "PREF" );
 
711
                        if( types.contains( "WORK" ) )
 
712
                                addEmail( value, Contacts.ContactMethods.TYPE_WORK, preferred );
 
713
                        else
 
714
                                addEmail( value, Contacts.ContactMethods.TYPE_HOME, preferred );
 
715
                }
 
716
 
 
717
                public void finaliseParsing()
 
718
                        throws ParseException, SkipContactException,
 
719
                        AbortImportException
1034
720
                {
1035
721
                        // missing version (and data is present)
1036
 
                        if( _version == null && _content_lines != null )
 
722
                        if( _version == null && _buffers != null )
1037
723
                                throw new ParseException( R.string.error_vcf_malformed );
1038
724
 
1039
 
                        // finalise the parent class
1040
 
                        finalise();
 
725
                        //  missing name properties?
 
726
                        if( _name_level == NAMELEVEL_NONE )
 
727
                                throw new ParseException( R.string.error_vcf_noname );
 
728
 
 
729
                        // check if we should import this one? If we've already got an 'N'-
 
730
                        // type name, this will already have been done by parseN() so we
 
731
                        // mustn't do this here (or it could prompt twice!)
 
732
                        if( _name_level < NAMELEVEL_N && !isImportRequired( getName() ) )
 
733
                                throw new SkipContactException();
1041
734
                }
1042
735
 
1043
 
                /**
1044
 
                 * Amongst the params, find the value of the first, only, of any with
1045
 
                 * the specified name
1046
 
                 * @param params
1047
 
                 * @param name
1048
 
                 * @return a value, or null
1049
 
                 */
1050
736
                private String checkParam( String[] params, String name )
1051
737
                {
1052
 
                        String[] res = checkParams( params, name );
1053
 
                        return res.length > 0? res[ 0 ] : null;
1054
 
                }
1055
 
 
1056
 
                /**
1057
 
                 * Amongst the params, find the values of any with the specified name
1058
 
                 * @param params
1059
 
                 * @param name
1060
 
                 * @return an array of values, or null
1061
 
                 */
1062
 
                private String[] checkParams( String[] params, String name )
1063
 
                {
1064
 
                        HashSet< String > ret = new HashSet< String >();
1065
 
 
1066
738
                        Pattern p = Pattern.compile(
1067
 
                                "^" + name + "[ \\t]*=[ \\t]*(\"?)(.*)\\1$",
1068
 
                                Pattern.CASE_INSENSITIVE );
 
739
                                "^" + name + "[ \\t]*=[ \\t]*(\"?)(.*)\\1$" );
1069
740
                        for( int i = 0; i < params.length; i++ ) {
1070
741
                                Matcher m = p.matcher( params[ i ] );
1071
742
                                if( m.matches() )
1072
 
                                        ret.add( m.group( 2 ) );
 
743
                                        return m.group( 2 );
1073
744
                        }
1074
 
 
1075
 
                        return (String[]) ret.toArray( new String[ ret.size() ] );
 
745
                        return null;
1076
746
                }
1077
747
 
1078
 
                /**
1079
 
                 * Amongst the params, return any type values present. For v2.1 vCards,
1080
 
                 * those types are just parameters. For v3.0, they are prefixed with
1081
 
                 * "TYPE=". There may also be multiple type parameters.
1082
 
                 * @param params an array of params to look for types in
1083
 
                 * @param valid_types an list of upper-case type values to look for
1084
 
                 * @return a set of present type values
1085
 
                 */
1086
748
                private Set< String > extractTypes( String[] params,
1087
749
                        List< String > valid_types )
1088
750
                {
1089
751
                        HashSet< String > types = new HashSet< String >();
1090
752
 
1091
753
                        // get 3.0-style TYPE= param
1092
 
                        String type_params[] = checkParams( params, "TYPE" );
1093
 
                        for( int a = 0; a < type_params.length; a++ )
1094
 
                        {
1095
 
                                // check for a comma-separated list of types (why? I don't think
1096
 
                                // this is in the specs!)
1097
 
                                String[] parts = type_params[ a ].split( "," );
1098
 
                                for( int i = 0; i < parts.length; i++ ) {
1099
 
                                        String ucpart = parts[ i ].toUpperCase( Locale.US );
1100
 
                                        if( valid_types.contains( ucpart ) )
1101
 
                                                types.add( ucpart );
1102
 
                                }
 
754
                        String type_param;
 
755
                        if( ( type_param = checkParam( params, "TYPE" ) ) != null ) {
 
756
                                String[] parts = type_param.split( "," );
 
757
                                for( int i = 0; i < parts.length; i++ )
 
758
                                        if( valid_types.contains( parts[ i ] ) )
 
759
                                                types.add( parts[ i ] );
1103
760
                        }
1104
761
 
1105
762
                        // get 2.1-style type param
1106
763
                        if( _version.equals( "2.1" ) ) {
1107
 
                                for( int i = 1; i < params.length; i++ ) {
1108
 
                                        String ucparam = params[ i ].toUpperCase( Locale.US );
1109
 
                                        if( valid_types.contains( ucparam ) )
1110
 
                                                types.add( ucparam );
1111
 
                                }
 
764
                                for( int i = 1; i < params.length; i++ )
 
765
                                        if( valid_types.contains( params[ i ] ) )
 
766
                                                types.add( params[ i ] );
1112
767
                        }
1113
768
 
1114
769
                        return types;