Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
   *
   * Copyright 1997-2008 Sun Microsystems, Inc. All rights reserved.
   *
   * The contents of this file are subject to the terms of either the GNU
   * General Public License Version 2 only ("GPL") or the Common Development
   * and Distribution License("CDDL") (collectively, the "License").  You
   * may not use this file except in compliance with the License. You can obtain
  * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
  * or glassfish/bootstrap/legal/LICENSE.txt.  See the License for the specific
  * language governing permissions and limitations under the License.
  *
  * When distributing the software, include this License Header Notice in each
  * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
  * Sun designates this particular file as subject to the "Classpath" exception
  * as provided by Sun in the GPL Version 2 section of the License file that
  * accompanied this code.  If applicable, add the following below the License
  * Header, with the fields enclosed by brackets [] replaced by your own
  * identifying information: "Portions Copyrighted [year]
  * [name of copyright owner]"
  *
  * Contributor(s):
  *
  * If you wish your version of this file to be governed by only the CDDL or
  * only the GPL Version 2, indicate your decision by adding "[Contributor]
  * elects to include this software in this distribution under the [CDDL or GPL
  * Version 2] license."  If you don't indicate a single choice of license, a
  * recipient has the option to distribute your version of this file under
  * either the CDDL, the GPL Version 2 or to extend the choice of license to
  * its licensees as provided above.  However, if you add GPL Version 2 code
  * and therefore, elected the GPL Version 2 license, then the option applies
  * only if the new code is made subject to such option by the copyright
  * holder.
  *
  *
  * This file incorporates work covered by the following copyright and
  * permission notice:
  *
  * Copyright 2004 The Apache Software Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  *
  *     http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 
 package org.apache.tomcat.util.http;
 
 import java.io.*;
 import java.util.*;
 import java.text.*;
 
 /* XXX XXX XXX Need a major rewrite  !!!!
  */

This class is used to contain standard internet message headers, used for SMTP (RFC822) and HTTP (RFC2068) messages as well as for MIME (RFC 2045) applications such as transferring typed data and grouping related items in multipart message bodies.

Message headers, as specified in RFC822, include a field name and a field body. Order has no semantic significance, and several fields with the same name may exist. However, most fields do not (and should not) exist more than once in a header.

Many kinds of field body must conform to a specified syntax, including the standard parenthesized comment syntax. This class supports only two simple syntaxes, for dates and integers.

When processing headers, care must be taken to handle the case of multiple same-name fields correctly. The values of such fields are only available as strings. They may be accessed by index (treating the header as an array of fields), or by name (returning an array of string values).

 
 
 /* Headers are first parsed and stored in the order they are
    received. This is based on the fact that most servlets will not
    directly access all headers, and most headers are single-valued.
    ( the alternative - a hash or similar data structure - will add
    an overhead that is not needed in most cases )
    
    Apache seems to be using a similar method for storing and manipulating
    headers.
        
    Future enhancements:
    - hash the headers the first time a header is requested ( i.e. if the
    servlet needs direct access to headers).
   - scan "common" values ( length, cookies, etc ) during the parse
   ( addHeader hook )
   
*/
    


Memory-efficient repository for Mime Headers. When the object is recycled, it will keep the allocated headers[] and all the MimeHeaderField - no GC is generated. For input headers it is possible to use the MessageByte for Fileds - so no GC will be generated. The only garbage is generated when using the String for header names/values - this can't be avoided when the servlet calls header methods, but is easy to avoid inside tomcat. The goal is to use _only_ MessageByte-based Fields, and reduce to 0 the memory overhead of tomcat. TODO: XXX one-buffer parsing - for http ( other protocols don't need that ) XXX remove unused methods XXX External enumerations, with 0 GC. XXX use HeaderName ID

Author(s):
dac@eng.sun.com
James Todd [gonzo@eng.sun.com]
Costin Manolache
kevin seguin
public class MimeHeaders {
    
Initial size - should be == average number of headers per request XXX make it configurable ( fine-tuning of web-apps )
    public static final int DEFAULT_HEADER_SIZE=8;
    
    
The header fields.
    private MimeHeaderField[] headers = new
The current number of header fields.
    private int count;

    
Creates a new MimeHeaders object using a default buffer size.
    public MimeHeaders() {
    }

    
Clears all header fields.
    // [seguin] added for consistency -- most other objects have recycle().
    public void recycle() {
        clear();
    }

    
Clears all header fields.
    public void clear() {
	for (int i = 0; i < i++) {
	    [i].recycle();
	}
	 = 0;
    }

    
EXPENSIVE!!! only for debugging.
    public String toString() {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        pw.println("=== MimeHeaders ===");
        Enumeration e = names();
        while (e.hasMoreElements()) {
            String n = (String)e.nextElement();
            pw.println(n + " = " + getHeader(n));
        }
        return sw.toString();
    }
    // -------------------- Idx access to headers ----------
    
    
Returns the current number of header fields.
    public int size() {
	return ;
    }

    
Returns the Nth header name, or null if there is no such header. This may be used to iterate through all header fields.
    public MessageBytes getName(int n) {
	return n >= 0 && n <  ? [n].getName() : null;
    }

    
Returns the Nth header value, or null if there is no such header. This may be used to iterate through all header fields.
    public MessageBytes getValue(int n) {
	return n >= 0 && n <  ? [n].getValue() : null;
    }

    
Find the index of a header with the given name.
    public int findHeaderString nameint starting ) {
	// We can use a hash - but it's not clear how much
	// benefit you can get - there is an  overhead 
	// and the number of headers is small (4-5 ?)
	// Another problem is that we'll pay the overhead
	// of constructing the hashtable
	// A custom search tree may be better
        for (int i = startingi < i++) {
	    if ([i].getName().equalsIgnoreCase(name)) {
                return i;
            }
        }
        return -1;
    }
    
    // -------------------- --------------------

    
Returns an enumeration of strings representing the header field names. Field names may appear multiple times in this enumeration, indicating that multiple fields with that name exist in this header.
    public Enumeration names() {
	return new NamesEnumerator(this);
    }
    public Enumeration values(String name) {
	return new ValuesEnumerator(thisname);
    }
    // -------------------- Adding headers --------------------
    

    
Adds a partially constructed field to the header. This field has not had its name or value initialized.
    private MimeHeaderField createHeader() {
	int len = .;
	if ( >= len) {
	    // expand header list array
	    MimeHeaderField tmp[] = new MimeHeaderField[ * 2];
	    System.arraycopy(, 0, tmp, 0, len);
	     = tmp;
	}
	if ((mh = []) == null) {
	    [] = mh = new MimeHeaderField();
	}
	return mh;
    }

    
Create a new named header , return the MessageBytes container for the new value
    public MessageBytes addValueString name ) {
	mh.getName().setString(name);
	return mh.getValue();
    }

    
Create a new named header using un-translated byte[]. The conversion to chars can be delayed until encoding is known.
    public MessageBytes addValue(byte b[], int startNint len)
    {
	mhf.getName().setBytes(bstartNlen);
	return mhf.getValue();
    }

    
Create a new named header using translated char[].
    public MessageBytes addValue(char c[], int startNint len)
    {
	mhf.getName().setChars(cstartNlen);
	return mhf.getValue();
    }

    
Allow "set" operations - return a MessageBytes container for the header value ( existing header or new if this .
    public MessageBytes setValueString name ) {
        for ( int i = 0; i < i++ ) {
            if([i].getName().equalsIgnoreCase(name)) {
                for ( int j=i+1; j < j++ ) {
                    if([j].getName().equalsIgnoreCase(name)) {
                        removeHeader(j--);
                    }
                }
                return [i].getValue();
            }
        }
        MimeHeaderField mh = createHeader();
        mh.getName().setString(name);
        return mh.getValue();
    }
    //-------------------- Getting headers --------------------
    
Finds and returns a header field with the given name. If no such field exists, null is returned. If more than one such field is in the header, an arbitrary one is returned.
    public MessageBytes getValue(String name) {
        for (int i = 0; i < i++) {
	    if ([i].getName().equalsIgnoreCase(name)) {
                return [i].getValue();
            }
        }
        return null;
    }

    
Finds and returns a unique header field with the given name. If no such field exists, null is returned. If the specified header field is not unique then an java.lang.IllegalArgumentException is thrown.
    public MessageBytes getUniqueValue(String name) {
        MessageBytes result = null;
        for (int i = 0; i < i++) {
            if ([i].getName().equalsIgnoreCase(name)) {
                if (result == null) {
                    result = [i].getValue();
                } else {
                    throw new IllegalArgumentException();
                }
            }
        }
        return result;
    }
    
    // bad shortcut - it'll convert to string ( too early probably,
    // encoding is guessed very late )
    public String getHeader(String name) {
	MessageBytes mh = getValue(name);
	return mh != null ? mh.toString() : null;
    }
    // -------------------- Removing --------------------
    
Removes a header field with the specified name. Does nothing if such a field could not be found.

Parameters:
name the name of the header field to be removed
    public void removeHeader(String name) {
        // XXX
        // warning: rather sticky code; heavily tuned
        for (int i = 0; i < i++) {
            if ([i].getName().equalsIgnoreCase(name)) {
                removeHeader(i--);
            }
        }
    }

    
Removes the headers with the given name whose values contain the given string.

Parameters:
name The name of the headers to be removed
str The string to check the header values against
    public void removeHeader(String nameString str) {
        for (int i = 0; i < i++) {
            if ([i].getName().equalsIgnoreCase(name)
                    && getValue(i) != null
                    && getValue(i).toString() != null
                    && getValue(i).toString().indexOf(str) != -1) {
                removeHeader(i--);
            }
        }
    }

    
reset and swap with last header

Parameters:
idx the index of the header to remove.
    private void removeHeader(int idx) {
        MimeHeaderField mh = [idx];
        
        mh.recycle();
        [idx] = [ - 1];
        [ - 1] = mh;
        --;
    }
Enumerate the distinct header names. Each nextElement() is O(n) ( a comparation is done with all previous elements ). This is less frequesnt than add() - we want to keep add O(1).
class NamesEnumerator implements Enumeration {
    int pos;
    int size;
    String next;
    NamesEnumerator(MimeHeaders headers) {
	this.=headers;
	=0;
	 = headers.size();
    }
    private void findNext() {
	=null;
	for(  ; ++ ) {
	    forint j=0; j< ; j++ ) {
		if.getNamej ).equalsIgnoreCase )) {
		    // duplicate.
		    =null;
		    break;
		}
	    }
	    if!=null ) {
		// it's not a duplicate
		break;
	    }
	}
	// next time findNext is called it will try the
	// next element
	++;
    }
    
    public boolean hasMoreElements() {
	return !=null;
    }
    public Object nextElement() {
	String current=;
	return current;
    }
Enumerate the values for a (possibly ) multiple value element.
class ValuesEnumerator implements Enumeration {
    int pos;
    int size;
    String name;
    ValuesEnumerator(MimeHeaders headersString name) {
        this.=name;
	this.=headers;
	=0;
	 = headers.size();
    }
    private void findNext() {
	=null;
	for( ; ++ ) {
	    MessageBytes n1=.getName );
	    ifn1.equalsIgnoreCase )) {
		break;
	    }
	}
	++;
    }
    
    public boolean hasMoreElements() {
	return !=null;
    }
    public Object nextElement() {
	return current.toString();
    }
    
    protected final MessageBytes nameB = MessageBytes.newInstance();
    protected final MessageBytes valueB = MessageBytes.newInstance();

    
Creates a new, uninitialized header field.
    public MimeHeaderField() {
    }
    public void recycle() {
    }
    public MessageBytes getName() {
	return ;
    }
    public MessageBytes getValue() {
	return ;
    }
New to GrepCode? Check out our FAQ X