001: /*
002: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
003: *
004: * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
005: *
006: * The contents of this file are subject to the terms of either the GNU
007: * General Public License Version 2 only ("GPL") or the Common Development
008: * and Distribution License("CDDL") (collectively, the "License"). You
009: * may not use this file except in compliance with the License. You can obtain
010: * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
011: * or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
012: * language governing permissions and limitations under the License.
013: *
014: * When distributing the software, include this License Header Notice in each
015: * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
016: * Sun designates this particular file as subject to the "Classpath" exception
017: * as provided by Sun in the GPL Version 2 section of the License file that
018: * accompanied this code. If applicable, add the following below the License
019: * Header, with the fields enclosed by brackets [] replaced by your own
020: * identifying information: "Portions Copyrighted [year]
021: * [name of copyright owner]"
022: *
023: * Contributor(s):
024: *
025: * If you wish your version of this file to be governed by only the CDDL or
026: * only the GPL Version 2, indicate your decision by adding "[Contributor]
027: * elects to include this software in this distribution under the [CDDL or GPL
028: * Version 2] license." If you don't indicate a single choice of license, a
029: * recipient has the option to distribute your version of this file under
030: * either the CDDL, the GPL Version 2 or to extend the choice of license to
031: * its licensees as provided above. However, if you add GPL Version 2 code
032: * and therefore, elected the GPL Version 2 license, then the option applies
033: * only if the new code is made subject to such option by the copyright
034: * holder.
035: */
036: package org.jvnet.mimepull;
037:
038: import java.io.IOException;
039: import java.io.InputStream;
040: import java.io.UnsupportedEncodingException;
041: import java.net.URLDecoder;
042: import java.nio.ByteBuffer;
043: import java.util.*;
044:
045: /**
046: * Represents MIME message. MIME message parsing is done lazily using a
047: * pull parser.
048: *
049: * @author Jitendra Kotamraju
050: */
051: public class MIMEMessage {
052: MIMEConfig config;
053:
054: private final InputStream in;
055: private final List<MIMEPart> partsList;
056: private final Map<String, MIMEPart> partsMap;
057: private final Iterator<MIMEEvent> it;
058: private boolean parsed; // true when entire message is parsed
059: private MIMEPart currentPart;
060: private int currentIndex;
061:
062: /**
063: * @see MIMEMessage(InputStream, String)
064: */
065: public MIMEMessage(InputStream in, String boundary) {
066: this (in, boundary, new MIMEConfig());
067: }
068:
069: /**
070: * Creates a MIME message from the content's stream.
071: *
072: * @param in MIME message stream
073: * @param boundary the separator for parts(pass it without --)
074: * @param config various configuration parameters
075: */
076: public MIMEMessage(InputStream in, String boundary,
077: MIMEConfig config) {
078: this .in = in;
079: this .config = config;
080: MIMEParser parser = new MIMEParser(in, boundary, config);
081: it = parser.iterator();
082:
083: partsList = new ArrayList<MIMEPart>();
084: partsMap = new HashMap<String, MIMEPart>();
085: if (config.isParseEagerly()) {
086: parseAll();
087: }
088: }
089:
090: /**
091: * Gets all the attachments by parsing the entire MIME message. Avoid
092: * this if possible since it is an expensive operation.
093: *
094: * @return list of attachments.
095: */
096: public List<MIMEPart> getAttachments() {
097: if (!parsed) {
098: parseAll();
099: }
100: return partsList;
101: }
102:
103: /**
104: * Creates nth attachment lazily. It doesn't validate
105: * if the message has so many attachments. To
106: * do the validation, the message needs to be parsed.
107: * The parsing of the message is done lazily and is done
108: * while reading the bytes of the part.
109: *
110: * @param index sequential order of the part. starts with zero.
111: * @return attachemnt part
112: */
113: public MIMEPart getPart(int index) {
114: MIMEPart part = (index < partsList.size()) ? partsList
115: .get(index) : null;
116: if (parsed && part == null) {
117: throw new MIMEParsingException("There is no " + index
118: + " attachment part ");
119: }
120: if (part == null) {
121: // Parsing will done lazily and will be driven by reading the part
122: part = new MIMEPart(this );
123: partsList.add(index, part);
124: }
125: return part;
126: }
127:
128: /**
129: * Creates a lazy attachment for a given Content-ID. It doesn't validate
130: * if the message contains an attachment with the given Content-ID. To
131: * do the validation, the message needs to be parsed. The parsing of the
132: * message is done lazily and is done while reading the bytes of the part.
133: *
134: * @param contentId Content-ID of the part, expects Content-ID without <, >
135: * @return attachemnt part
136: */
137: public MIMEPart getPart(String contentId) {
138: MIMEPart part = getDecodedCidPart(contentId);
139: if (parsed && part == null) {
140: throw new MIMEParsingException(
141: "There is no attachment part with Content-ID = "
142: + contentId);
143: }
144: if (part == null) {
145: // Parsing is done lazily and is driven by reading the part
146: part = new MIMEPart(this , contentId);
147: partsMap.put(contentId, part);
148: }
149: return part;
150: }
151:
152: // this is required for Indigo interop, it writes content-id without escaping
153: private MIMEPart getDecodedCidPart(String cid) {
154: MIMEPart part = partsMap.get(cid);
155: if (part == null) {
156: if (cid.indexOf('%') != -1) {
157: try {
158: String tempCid = URLDecoder.decode(cid, "utf-8");
159: part = partsMap.get(tempCid);
160: } catch (UnsupportedEncodingException ue) {
161: // Ignore it
162: }
163: }
164: }
165: return part;
166: }
167:
168: /**
169: * Parses the whole MIME message eagerly
170: */
171: public void parseAll() {
172: while (makeProgress()) {
173: // Nothing to do
174: }
175: }
176:
177: /**
178: * Parses the MIME message in a pull fashion.
179: *
180: * @return
181: * false if the parsing is completed.
182: */
183: public synchronized boolean makeProgress() {
184: if (!it.hasNext()) {
185: return false;
186: }
187:
188: MIMEEvent event = it.next();
189:
190: switch (event.getEventType()) {
191: case START_MESSAGE:
192: break;
193:
194: case START_PART:
195: break;
196:
197: case HEADERS:
198: MIMEEvent.Headers headers = (MIMEEvent.Headers) event;
199: InternetHeaders ih = headers.getHeaders();
200: List<String> cids = ih.getHeader("content-id");
201: String cid = (cids != null) ? cids.get(0) : currentIndex
202: + "";
203: if (cid.length() > 2 && cid.charAt(0) == '<') {
204: cid = cid.substring(1, cid.length() - 1);
205: }
206: MIMEPart listPart = (currentIndex < partsList.size()) ? partsList
207: .get(currentIndex)
208: : null;
209: MIMEPart mapPart = getDecodedCidPart(cid);
210: if (listPart == null && mapPart == null) {
211: currentPart = getPart(cid);
212: partsList.add(currentIndex, currentPart);
213: } else if (listPart == null) {
214: currentPart = mapPart;
215: partsList.add(currentIndex, mapPart);
216: } else if (mapPart == null) {
217: currentPart = listPart;
218: currentPart.setContentId(cid);
219: partsMap.put(cid, currentPart);
220: } else if (listPart != mapPart) {
221: throw new MIMEParsingException(
222: "Created two different attachments using Content-ID and index");
223: }
224: currentPart.setHeaders(ih);
225: break;
226:
227: case CONTENT:
228: MIMEEvent.Content content = (MIMEEvent.Content) event;
229: ByteBuffer buf = content.getData();
230: currentPart.addBody(buf);
231: break;
232:
233: case END_PART:
234: currentPart.doneParsing();
235: ++currentIndex;
236: break;
237:
238: case END_MESSAGE:
239: parsed = true;
240: try {
241: in.close();
242: } catch (IOException ioe) {
243: throw new MIMEParsingException(ioe);
244: }
245: break;
246:
247: default:
248: throw new MIMEParsingException("Unknown Parser state = "
249: + event.getEventType());
250: }
251: return true;
252: }
253: }
|