001 /****************************************************************
002 * Licensed to the Apache Software Foundation (ASF) under one *
003 * or more contributor license agreements. See the NOTICE file *
004 * distributed with this work for additional information *
005 * regarding copyright ownership. The ASF licenses this file *
006 * to you under the Apache License, Version 2.0 (the *
007 * "License"); you may not use this file except in compliance *
008 * with the License. You may obtain a copy of the License at *
009 * *
010 * http://www.apache.org/licenses/LICENSE-2.0 *
011 * *
012 * Unless required by applicable law or agreed to in writing, *
013 * software distributed under the License is distributed on an *
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
015 * KIND, either express or implied. See the License for the *
016 * specific language governing permissions and limitations *
017 * under the License. *
018 ****************************************************************/
019
020 package org.apache.james.mime4j.stream;
021
022 import org.apache.james.mime4j.util.ByteSequence;
023 import org.apache.james.mime4j.util.CharsetUtil;
024 import org.apache.james.mime4j.util.ContentUtil;
025 import org.apache.james.mime4j.util.MimeUtil;
026
027 /**
028 * Raw (unstructured) MIME field. The field's body is unparsed and possibly encoded.
029 * <p/>
030 * Instances of this class can be created by using
031 * {@link RawFieldParser#parseField(ByteSequence)} method.
032 */
033 public final class RawField implements Field {
034
035 private final ByteSequence raw;
036 private final int delimiterIdx;
037 private final String name;
038 private final String body;
039
040 RawField(ByteSequence raw, int delimiterIdx, String name, String body) {
041 if (name == null) {
042 throw new IllegalArgumentException("Field may not be null");
043 }
044 this.raw = raw;
045 this.delimiterIdx = delimiterIdx;
046 this.name = name.trim();
047 this.body = body;
048 }
049
050 public RawField(String name, String body) {
051 this(null, -1, name, body);
052 }
053
054 public ByteSequence getRaw() {
055 return raw;
056 }
057
058 public String getName() {
059 return name;
060 }
061
062 public String getBody() {
063 if (body != null) {
064 return body;
065 }
066 if (raw != null) {
067 int len = raw.length();
068 int off = delimiterIdx + 1;
069 if (len > off + 1 && (CharsetUtil.isWhitespace((char) (raw.byteAt(off) & 0xff)))) {
070 off++;
071 }
072 return MimeUtil.unfold(ContentUtil.decode(raw, off, len - off));
073 }
074 return null;
075 }
076
077 public int getDelimiterIdx() {
078 return delimiterIdx;
079 }
080
081 @Override
082 public String toString() {
083 if (raw != null) {
084 return ContentUtil.decode(raw);
085 } else {
086 StringBuilder buf = new StringBuilder();
087 buf.append(name);
088 buf.append(": ");
089 if (body != null) {
090 buf.append(body);
091 }
092 return buf.toString();
093 }
094 }
095
096 }