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.io; 021 022 import java.io.FilterInputStream; 023 import java.io.IOException; 024 import java.io.InputStream; 025 026 /** 027 * <code>InputStream</code> used by the parser to wrap the original user 028 * supplied stream. This stream keeps track of the current line number. 029 */ 030 public class LineNumberInputStream extends FilterInputStream implements 031 LineNumberSource { 032 private int lineNumber = 1; 033 034 /** 035 * Creates a new <code>LineNumberInputStream</code>. 036 * 037 * @param is 038 * the stream to read from. 039 */ 040 public LineNumberInputStream(InputStream is) { 041 super(is); 042 } 043 044 public int getLineNumber() { 045 return lineNumber; 046 } 047 048 @Override 049 public int read() throws IOException { 050 int b = in.read(); 051 if (b == '\n') { 052 lineNumber++; 053 } 054 return b; 055 } 056 057 @Override 058 public int read(byte[] b, int off, int len) throws IOException { 059 int n = in.read(b, off, len); 060 for (int i = off; i < off + n; i++) { 061 if (b[i] == '\n') { 062 lineNumber++; 063 } 064 } 065 return n; 066 } 067 }