94ebb02029d613d5ab1ec98cd89651026a11fa59
[zxing.git] / core / src / com / google / zxing / client / result / EmailDoCoMoResultParser.java
1 /*
2  * Copyright 2007 ZXing authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package com.google.zxing.client.result;
18
19 import com.google.zxing.Result;
20
21 /**
22  * Implements the "MATMSG" email message entry format.
23  *
24  * Supported keys: TO, SUB, BODY
25  *
26  * @author Sean Owen
27  */
28 final class EmailDoCoMoResultParser extends AbstractDoCoMoResultParser {
29
30   public static EmailAddressParsedResult parse(Result result) {
31     String rawText = result.getText();
32     if (rawText == null || !rawText.startsWith("MATMSG:")) {
33       return null;
34     }
35     String[] rawTo = matchDoCoMoPrefixedField("TO:", rawText, true);
36     if (rawTo == null) {
37       return null;
38     }
39     String to = rawTo[0];
40     if (!isBasicallyValidEmailAddress(to)) {
41       return null;
42     }
43     String subject = matchSingleDoCoMoPrefixedField("SUB:", rawText, false);
44     String body = matchSingleDoCoMoPrefixedField("BODY:", rawText, false);
45     return new EmailAddressParsedResult(to, subject, body, "mailto:" + to);
46   }
47
48   /**
49    * This implements only the most basic checking for an email address's validity -- that it contains
50    * an '@' and a '.', and that it contains no space or LF.
51    * We want to generally be lenient here since this class is only intended to encapsulate what's
52    * in a barcode, not "judge" it.
53    */
54   static boolean isBasicallyValidEmailAddress(String email) {
55     if (email == null) {
56       return false;
57     }
58     boolean atFound = false;
59     boolean periodFound = false;
60     for (int i = 0; i < email.length(); i++) {
61       char c = email.charAt(i);
62       if (c == '@') {
63         if (atFound) {
64           return false;
65         }
66         atFound = true;
67       } else if (c == '.') {
68         periodFound = true;
69       } else if (c == ' ' || c == '\n') {
70         return false;
71       }
72     }
73     return atFound && periodFound;
74   }
75
76 }