1 /****************************************************************
2 * Licensed to the Apache Software Foundation (ASF) under one *
3 * or more contributor license agreements. See the NOTICE file *
4 * distributed with this work for additional information *
5 * regarding copyright ownership. The ASF licenses this file *
6 * to you under the Apache License, Version 2.0 (the *
7 * "License"); you may not use this file except in compliance *
8 * with the License. You may obtain a copy of the License at *
9 * *
10 * http://www.apache.org/licenses/LICENSE-2.0 *
11 * *
12 * Unless required by applicable law or agreed to in writing, *
13 * software distributed under the License is distributed on an *
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
15 * KIND, either express or implied. See the License for the *
16 * specific language governing permissions and limitations *
17 * under the License. *
18 ****************************************************************/
19
20 package org.apache.james.mime4j.field;
21
22 import org.apache.commons.logging.Log;
23 import org.apache.commons.logging.LogFactory;
24 import org.apache.james.mime4j.field.address.AddressList;
25 import org.apache.james.mime4j.field.address.Mailbox;
26 import org.apache.james.mime4j.field.address.MailboxList;
27 import org.apache.james.mime4j.field.address.parser.ParseException;
28 import org.apache.james.mime4j.util.ByteSequence;
29
30 /**
31 * Mailbox field such as <code>Sender</code> or <code>Resent-Sender</code>.
32 */
33 public class MailboxField extends AbstractField {
34 private static Log log = LogFactory.getLog(MailboxField.class);
35
36 private boolean parsed = false;
37
38 private Mailbox mailbox;
39 private ParseException parseException;
40
41 MailboxField(final String name, final String body, final ByteSequence raw) {
42 super(name, body, raw);
43 }
44
45 public Mailbox getMailbox() {
46 if (!parsed)
47 parse();
48
49 return mailbox;
50 }
51
52 @Override
53 public ParseException getParseException() {
54 if (!parsed)
55 parse();
56
57 return parseException;
58 }
59
60 private void parse() {
61 String body = getBody();
62
63 try {
64 MailboxList mailboxList = AddressList.parse(body).flatten();
65 if (mailboxList.size() > 0) {
66 mailbox = mailboxList.get(0);
67 }
68 } catch (ParseException e) {
69 if (log.isDebugEnabled()) {
70 log.debug("Parsing value '" + body + "': " + e.getMessage());
71 }
72 parseException = e;
73 }
74
75 parsed = true;
76 }
77
78 static final FieldParser PARSER = new FieldParser() {
79 public ParsedField parse(final String name, final String body,
80 final ByteSequence raw) {
81 return new MailboxField(name, body, raw);
82 }
83 };
84 }