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 020package org.apache.james.mime4j.field; 021 022import org.apache.james.mime4j.codec.DecodeMonitor; 023import org.apache.james.mime4j.dom.FieldParser; 024import org.apache.james.mime4j.dom.field.ContentLengthField; 025import org.apache.james.mime4j.stream.Field; 026 027/** 028 * Represents a <code>Content-Length</code> field. 029 */ 030public class ContentLengthFieldImpl extends AbstractField implements ContentLengthField { 031 032 private boolean parsed = false; 033 private long contentLength; 034 035 ContentLengthFieldImpl(Field rawField, DecodeMonitor monitor) { 036 super(rawField, monitor); 037 } 038 039 private void parse() { 040 parsed = true; 041 contentLength = -1; 042 String body = getBody(); 043 if (body != null) { 044 try { 045 contentLength = Long.parseLong(body); 046 if (contentLength < 0) { 047 contentLength = -1; 048 if (monitor.isListening()) { 049 monitor.warn("Negative content length: " + body, 050 "ignoring Content-Length header"); 051 } 052 } 053 } catch (NumberFormatException e) { 054 if (monitor.isListening()) { 055 monitor.warn("Invalid content length: " + body, 056 "ignoring Content-Length header"); 057 } 058 } 059 } 060 } 061 062 public long getContentLength() { 063 if (!parsed) { 064 parse(); 065 } 066 return contentLength; 067 } 068 069 public static final FieldParser<ContentLengthField> PARSER = new FieldParser<ContentLengthField>() { 070 071 public ContentLengthField parse(final Field rawField, final DecodeMonitor monitor) { 072 return new ContentLengthFieldImpl(rawField, monitor); 073 } 074 075 }; 076}